@serifpersia/dango 3.0.3
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/LICENSE +21 -0
- package/README.md +247 -0
- package/client/dist/assets/AnimeInfo-CMxs0nRH.css +1 -0
- package/client/dist/assets/AnimeInfo-DVdaocCl.js +1 -0
- package/client/dist/assets/AnimeInfoPage-Bx5EvGt-.js +2 -0
- package/client/dist/assets/Asmr-C2i9GKD4.css +1 -0
- package/client/dist/assets/Asmr-CIjmFtRH.js +2 -0
- package/client/dist/assets/Asmr.module-DPG2JhDJ.js +1 -0
- package/client/dist/assets/AvSyncCalibrator-CIYcyon5.css +1 -0
- package/client/dist/assets/AvSyncCalibrator-vqErH7Cm.js +10 -0
- package/client/dist/assets/ErrorMessage-BwSjzblw.js +1 -0
- package/client/dist/assets/ErrorMessage-CXoRbrLN.css +1 -0
- package/client/dist/assets/Home-D7YfGBUk.js +1 -0
- package/client/dist/assets/Home-DKCfEiwl.css +1 -0
- package/client/dist/assets/Insights-BljI64Ua.css +1 -0
- package/client/dist/assets/Insights-CLQGrlpX.js +1 -0
- package/client/dist/assets/Manga-DQ9HYnpk.js +1 -0
- package/client/dist/assets/Manga-H8Wb04w3.css +1 -0
- package/client/dist/assets/Map-CXFqXmsZ.css +1 -0
- package/client/dist/assets/Map-L_ryVBTq.js +1 -0
- package/client/dist/assets/Mature-BeWzAJ7B.js +1 -0
- package/client/dist/assets/Mature-DJmUUtlF.css +1 -0
- package/client/dist/assets/Player-CYpd__FP.js +30 -0
- package/client/dist/assets/Player-DreAhybc.css +1 -0
- package/client/dist/assets/PlayerRedirect-fxUAp9JV.js +1 -0
- package/client/dist/assets/PlayerSettings-BcsotxP9.js +1 -0
- package/client/dist/assets/PlayerSettings-Cqua1CDD.css +1 -0
- package/client/dist/assets/QueueRail-B9Pgbqc3.js +1 -0
- package/client/dist/assets/QueueRail-BnaltOP8.css +1 -0
- package/client/dist/assets/Radio-BvdY5twD.js +1 -0
- package/client/dist/assets/Radio-CUuYy3DY.css +1 -0
- package/client/dist/assets/Search-BzO-aRP7.css +1 -0
- package/client/dist/assets/Search-R9YLAXS1.js +1 -0
- package/client/dist/assets/Search.module-D8ZbQAiK.js +1 -0
- package/client/dist/assets/Settings-9kYcXdTR.js +21 -0
- package/client/dist/assets/Settings-DF8JThUL.css +1 -0
- package/client/dist/assets/SkeletonGrid-D5vRvX5q.js +1 -0
- package/client/dist/assets/SkeletonGrid-DEbYtO4H.css +1 -0
- package/client/dist/assets/SynopsisText-BlFw0R-0.js +1 -0
- package/client/dist/assets/SynopsisText-CUgOjOxt.css +1 -0
- package/client/dist/assets/Trackers-DfZlnnVq.js +2 -0
- package/client/dist/assets/Trackers-Dt9lR_uP.css +1 -0
- package/client/dist/assets/Tv-CVKC2YBs.css +1 -0
- package/client/dist/assets/Tv-Db1Wx_b7.js +15 -0
- package/client/dist/assets/Watchlist-B2nkNZqM.css +1 -0
- package/client/dist/assets/Watchlist-a77CYtzu.js +1 -0
- package/client/dist/assets/hls-6Owgw2Aj.js +1 -0
- package/client/dist/assets/hls-BOLXTnjL.js +42 -0
- package/client/dist/assets/index-B6qdXFtl.css +1 -0
- package/client/dist/assets/index-B8TPVaIS.js +30354 -0
- package/client/dist/assets/index-CpjgU8ou.js +178 -0
- package/client/dist/assets/useAnimeInfoData-BOfyi9UJ.js +1 -0
- package/client/dist/assets/useIsMobile-CM15uQn8.css +1 -0
- package/client/dist/assets/useIsMobile-Cb8HcKRj.js +1 -0
- package/client/dist/assets/useMatureConsent-CZMYBVXd.js +1 -0
- package/client/dist/assets/vendor-rLNfZm7Y.js +1 -0
- package/client/dist/av-sync-test.mp4 +0 -0
- package/client/dist/favicon.ico +0 -0
- package/client/dist/index.html +31 -0
- package/client/dist/logo-mochi.png +0 -0
- package/client/dist/logo-sakura.png +0 -0
- package/client/dist/logo.png +0 -0
- package/client/dist/placeholder.svg +4 -0
- package/client/dist/robots.txt +3 -0
- package/orchestrator.js +416 -0
- package/package.json +89 -0
- package/server/dist/app-auth.js +231 -0
- package/server/dist/config.js +133 -0
- package/server/dist/controllers/auth.controller.js +247 -0
- package/server/dist/controllers/data.controller.js +785 -0
- package/server/dist/controllers/insights.controller.js +197 -0
- package/server/dist/controllers/proxy.controller.js +665 -0
- package/server/dist/controllers/settings.controller.js +267 -0
- package/server/dist/controllers/watchlist.controller.js +967 -0
- package/server/dist/db.js +152 -0
- package/server/dist/discord-gateway.js +381 -0
- package/server/dist/discord-rpc.js +424 -0
- package/server/dist/github-sync.js +403 -0
- package/server/dist/google.js +549 -0
- package/server/dist/lib/anilist.js +1519 -0
- package/server/dist/lib/anischedule.js +202 -0
- package/server/dist/lib/ipc.js +32 -0
- package/server/dist/lib/kitsu.js +552 -0
- package/server/dist/lib/mal.js +886 -0
- package/server/dist/lib/migration.js +335 -0
- package/server/dist/lib/temp-ids.js +11 -0
- package/server/dist/lib/tmdb.js +71 -0
- package/server/dist/lib/tracker/anilist-tracker.js +250 -0
- package/server/dist/lib/tracker/sync.service.js +312 -0
- package/server/dist/logger.js +19 -0
- package/server/dist/providers/123anime.provider.js +240 -0
- package/server/dist/providers/anilight.provider.js +366 -0
- package/server/dist/providers/animepahe.provider.js +531 -0
- package/server/dist/providers/animeya.provider.js +746 -0
- package/server/dist/providers/base-provider.js +45 -0
- package/server/dist/providers/hn.provider.js +473 -0
- package/server/dist/providers/ht.provider.js +439 -0
- package/server/dist/providers/jasmr.provider.js +504 -0
- package/server/dist/providers/kaa.provider.js +388 -0
- package/server/dist/providers/manga/manga.types.js +10 -0
- package/server/dist/providers/manga/mangadex.provider.js +227 -0
- package/server/dist/providers/manga/mangapill.provider.js +232 -0
- package/server/dist/providers/megaplay.provider.js +583 -0
- package/server/dist/providers/op.provider.js +440 -0
- package/server/dist/providers/provider.interface.js +2 -0
- package/server/dist/providers/title-matching.js +234 -0
- package/server/dist/providers/wh.provider.js +600 -0
- package/server/dist/rclone.js +126 -0
- package/server/dist/repositories/insights.repository.js +43 -0
- package/server/dist/repositories/mal-cache.repository.js +66 -0
- package/server/dist/repositories/notifications.repository.js +40 -0
- package/server/dist/repositories/queue.repository.js +64 -0
- package/server/dist/repositories/settings.repository.js +15 -0
- package/server/dist/repositories/shows-meta.repository.js +43 -0
- package/server/dist/repositories/temp-show-ids.repository.js +54 -0
- package/server/dist/repositories/watched-episodes.repository.js +54 -0
- package/server/dist/repositories/watchlist.repository.js +74 -0
- package/server/dist/routes/asmr.routes.js +72 -0
- package/server/dist/routes/auth.routes.js +28 -0
- package/server/dist/routes/data.routes.js +50 -0
- package/server/dist/routes/discord-gateway.routes.js +57 -0
- package/server/dist/routes/insights.routes.js +12 -0
- package/server/dist/routes/lan-auth.routes.js +49 -0
- package/server/dist/routes/manga.routes.js +115 -0
- package/server/dist/routes/proxy.routes.js +15 -0
- package/server/dist/routes/radio.routes.js +143 -0
- package/server/dist/routes/settings.routes.js +27 -0
- package/server/dist/routes/tracker.routes.js +143 -0
- package/server/dist/routes/translate.routes.js +90 -0
- package/server/dist/routes/tv.routes.js +843 -0
- package/server/dist/routes/watchlist.routes.js +312 -0
- package/server/dist/server.js +310 -0
- package/server/dist/shipped-defaults.js +8 -0
- package/server/dist/sync-config.js +32 -0
- package/server/dist/sync.js +506 -0
- package/server/dist/utils/cookie.utils.js +17 -0
- package/server/dist/utils/db-utils.js +15 -0
- package/server/dist/utils/env.utils.js +83 -0
- package/server/dist/utils/machine-id.js +46 -0
- package/server/dist/utils/request-context.js +5 -0
- package/server/dist/utils/security.utils.js +99 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const B=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},ll=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=cl},cl=Number.MAX_SAFE_INTEGER||9007199254740991;let q=(function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n})({}),R=(function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",n.UNKNOWN="unknown",n})({}),p=(function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n})({});function hl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ei={exports:{}},Dr;function ul(){return Dr||(Dr=1,(function(n,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.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 d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;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=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(m.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)m.path=f.path,d.params||(m.params=f.params,d.query||(m.query=f.query));else{var y=f.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;m.path=o.normalizePath(E)}return m.path===null&&(m.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(m)},parseURL:function(l){var c=s.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(ei)),ei.exports}var Zi=ul();class Ji{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}}}var se={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},H={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},de={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class aa{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,fl(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}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={[de.AUDIO]:null,[de.VIDEO]:null,[de.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ji),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Zi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[de.AUDIO]=null,e[de.VIDEO]=null,e[de.AUDIOVIDEO]=null,this.url=null}}function Ee(n){return n.sn!=="initSegment"}function Yt(n,e){return n.sn===e?.sn&&n.level===e.level}function _i(n,e){return n.sn===e?.sn&&n.level===e.level&&n.cc===e.cc}class us extends aa{constructor(e,t){super(t),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=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(B(e)&&B(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=B(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!B(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ee(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)}}class dl extends aa{constructor(e,t,s,i,r){super(s),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=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===H.SUBTITLE&&this.stats.loading.end>0)}}function oa(n,e){const t=Object.getPrototypeOf(n);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||oa(t,e)}}function fl(n,e){const t=oa(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}function gl(n,e,t){return(e=yl(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function ue(){return ue=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},ue.apply(null,arguments)}function Pr(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function j(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Pr(Object(t),!0).forEach(function(s){gl(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Pr(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function Xs(n,e){if(n==null)return{};var t,s,i=ml(n,e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);for(s=0;s<r.length;s++)t=r[s],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(n,t)&&(i[t]=n[t])}return i}function ml(n,e){if(n==null)return{};var t={};for(var s in n)if({}.hasOwnProperty.call(n,s)){if(e.indexOf(s)!==-1)continue;t[s]=n[s]}return t}function pl(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function yl(n){var e=pl(n,"string");return typeof e=="symbol"?e:e+""}function Ms(n){switch(n.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:case R.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function la(n){return n.details.startsWith("key")}function ca(n){return la(n)&&!!n.frag&&!n.frag.decryptdata}function Cr(n,e){const t=Ms(e);return n.default[`${t?"timeout":"error"}Retry`]}function er(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function kr(n){return j(j({},n),{errorRetry:null,timeoutRetry:null})}function Zt(n,e,t,s){if(!n)return!1;const i=s?.code,r=e<n.maxNumRetry&&(El(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function El(n){return Jt(n)||!!n&&(n<400||n>499)}function Jt(n){return n===0&&navigator.onLine===!1}function ha(n,e){return e>0&&n.loadError>0&&n.loadErrorTime!==0&&self.performance.now()-n.loadErrorTime>e}class Pt{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Tl{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Pt(e),this.fast_=new Pt(t),this.defaultTTFB_=i,this.ttfb_=new Pt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new Pt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Pt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Pt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){if(t<=0)return;const s=Math.min(this.minDelayMs_,t/1e5),i=8*t,r=Math.max(e,s)/1e3,a=i/r;this.fast_.sample(r,a),this.slow_.sample(r,a)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,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 Ge{constructor(e,t){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 s=`[${e}]:`;this.trace=yt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const yt=function(){},Sl={trace:yt,debug:yt,log:yt,warn:yt,info:yt,error:yt};function Di(){return ue({},Sl)}function vl(n,e){const t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):yt}function Or(n,e,t){return e[n]?e[n].bind(e):vl(n,t)}const Pi=Di();function xl(n,e,t){const s=Di();if(typeof console=="object"&&n===!0||typeof n=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Or(r,n,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.2`)}catch{return Di()}i.forEach(r=>{Pi[r]=Or(r,n)})}else ue(Pi,s);return s}const le=Pi;function xt(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Al(n){return typeof self<"u"&&n===self.ManagedMediaSource}function ua(n,e){const t=Object.keys(n),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(a=>s.indexOf(a)===-1)}function Il(n){return btoa(String.fromCharCode(...n))}function Qs(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}const Ll="utf-16",ti="utf-16be",wr="utf-16le",_s="utf-8";function Rl(n,e={}){let t;Qs(n)?t=new DataView(n):t=new DataView(n.buffer,n.byteOffset,n.byteLength);let s=0,{encoding:i}=e;if(!i){const c=t.getUint8(0),h=t.getUint8(1);c==239&&h==187&&t.getUint8(2)==191?(i=_s,s=3):c==254&&h==255?(i=ti,s=2):c==255&&h==254?(i=wr,s=2):i=_s}if(typeof TextDecoder<"u")return new TextDecoder(i).decode(t);const{byteLength:r}=t,a=i!==ti;let o="",l;for(;s<r;){switch(i){case _s:if(l=t.getUint8(s),l<128)s++;else if(l>=194&&l<=223)if(s+1<r){const c=t.getUint8(s+1);c>=128&&c<=191?(l=(l&31)<<6|c&63,s+=2):s++}else s++;else if(l>=224&&l<=239)if(s+2<=r-1){const c=t.getUint8(s+1),h=t.getUint8(s+2);c>=128&&c<=191&&h>=128&&h<=191?(l=(l&15)<<12|(c&63)<<6|h&63,s+=3):s++}else s++;else if(l>=240&&l<=244)if(s+3<=r-1){const c=t.getUint8(s+1),h=t.getUint8(s+2),u=t.getUint8(s+3);c>=128&&c<=191&&h>=128&&h<=191&&u>=128&&u<=191?(l=(l&7)<<18|(c&63)<<12|(h&63)<<6|u&63,s+=4):s++}else s++;else s++;break;case ti:case Ll:case wr:l=t.getUint16(s,a),s+=2;break}o+=String.fromCodePoint(l)}return o}function bl(n){const e=typeof n=="string"?new URL(n):n;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function da(n,e){if(n<0)return-da(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const s=Math.floor(n*t);return(s%2===0?s:s+1)/t}else return Math.round(n*t)/t}function _l(n,e){let t;try{t=new URL(n)}catch{return n}const s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1),a=Math.min(i.length,r.length);for(let o=0;o<a&&i[o]===r[o];o++)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}function fa(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const i=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?i:i&3|8).toString(16)})}}}function tr(n,e){return e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function Zs(n,e){let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t}function Dl(n,e){return tr(n,e)&&Zs(n,e+6)+10<=n.length-e}function ga(n,e){return e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function es(n,e){const t=e;let s=0;for(;tr(n,e);){s+=10;const i=Zs(n,e+6);s+=i,ga(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)}function Pl(n){return Qs(n)?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function si(n,e=0,t=1/0){return Cl(n,e,t,Uint8Array)}function Cl(n,e,t,s){const i=kl(n);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const a=Ol(n)?n.byteOffset:0,o=(a+n.byteLength)/r,l=(a+e)/r,c=Math.floor(Math.max(0,Math.min(l,o)));return new s(i,c,Math.floor(Math.min(c+Math.max(t,0),o))-c)}function kl(n){return Qs(n)?n:n.buffer}function Ol(n){return n&&Qs(n.buffer)&&n.byteLength!==void 0&&n.byteOffset!==void 0}function Ue(n,e=!1){const t=e?n.indexOf(0):n.length,s=Rl(new DataView(n.buffer,n.byteOffset,t),{encoding:_s});return e?s:s.replace(/\0/g,"")}function wl(n){const e={key:n.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(n.size<2)return;if(n.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=n.data.subarray(1).indexOf(0);if(s===-1)return;const i=Ue(si(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Ue(si(n.data,3+s,a));let l;return i==="-->"?l=Ue(si(n.data,4+s+a)):l=Pl(n.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=l,e}function Ml(n){if(n.size<2)return;const e=Ue(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function Fl(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1;const{data:s}=n,i=Ue(s.subarray(t),!0);t+=i.length+1;const r=Ue(s.subarray(t));return{key:n.type,info:i,data:r}}const e=Ue(n.data.subarray(1));return{key:n.type,info:"",data:e}}function Nl(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1;const s=Ue(n.data.subarray(t),!0);t+=s.length+1;const i=Ue(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Ue(n.data);return{key:n.type,info:"",data:e}}function Bl(n){return n.type==="PRIV"?Ml(n):n.type[0]==="W"?Nl(n):n.type==="APIC"?wl(n):Fl(n)}function $l(n){const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=Zs(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}}const ds=10,Ul=10;function ma(n){let e=0;const t=[];for(;tr(n,e);){const s=Zs(n,e+6);n[e+5]>>6&1&&(e+=ds),e+=ds;const i=e+s;for(;e+Ul<i;){const r=$l(n.subarray(e)),a=Bl(r);a&&t.push(a),e+=r.size+ds}ga(n,e)&&(e+=ds)}return t}function pa(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function Gl(n){if(n.data.byteLength===8){const e=new Uint8Array(n.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function sr(n){const e=ma(n);for(const t of e)if(pa(t))return Gl(t)}function Ie(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function ya(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function ir(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Ze(n){return String.fromCharCode.apply(null,n)}const st=Math.pow(2,32)-1,Z={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},Ea={video:1,audio:2,id3:3,text:4};function Ta(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function K(n,e){const t=n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3];return t<0?4294967296+t:t}function Mr(n,e){let t=K(n,e);return t*=Math.pow(2,32),t+=K(n,e+4),t}function fs(n,e){let t="";for(let s=e;s<n.length;s++)if(t+=String.fromCharCode(n[s]),n[s]===0)return t;return null}function Ci(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function Se(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255}function Fr(n,e,t){const s=e.byteOffset-n.byteOffset-8,i=8+t,r=e.byteLength+8-i;r<8||(Se(n,s,i),Se(n,s+i,r),Se(n,s+i+4,Z.free))}function ki(n,e){return[n.byteOffset-e-8,n.byteOffset-e+n.byteLength]}function Sa(n,e){e.sort((o,l)=>o[0]-l[0]);const t=e.reduce((o,[l,c])=>o+c-l,0),s=new Uint8Array(n.byteLength-t);let i=0,r=0;for(let o=0;o<e.length;o++){const[l,c]=e[o];s.set(n.subarray(i,l),r),r+=l-i,i=c}return s.set(n.subarray(i),r),{result:s,dropped:t,droppedBefore:o=>e.reduce((l,[c,h])=>h<=o?l+h-c:l,0)}}function Vl(n){const e=J(n,["moov"]);if(e.length!==1||J(n,["moof"]).length)return null;const t=n.byteOffset,s=[],i=[];let r=!1;const a=J(e[0],["trak"]);for(let f=0;f<a.length;f++){const g=a[f],m=J(g,["mdia","hdlr"])[0];if((m?Ze(m.subarray(8,12)):"")==="vide"){r=!0;continue}const E=J(g,["tkhd"])[0];if(!E)return null;const S=E[0];i.push(K(E,S===0?12:20)),s.push(ki(g,t))}if(!r||!s.length)return null;const o=J(e[0],["mvex"])[0];let l=0;if(o){const f=J(o,["trex"]);for(let g=0;g<f.length;g++){const m=f[g];i.indexOf(K(m,4))!==-1&&(s.push(ki(m,t)),l+=m.byteLength+8)}}const{result:c,dropped:h,droppedBefore:u}=Sa(n,s),d=e[0].byteOffset-t-8;if(Se(c,d,e[0].byteLength+8-h),o&&l){const f=o.byteOffset-t-8;Se(c,f-u(f),o.byteLength+8-l)}return c}function Kl(n,e,t,s,i){if(t<1)return null;const r=J(n,["moof"]);if(r.length!==1)return null;const a=r[0],o=n.byteOffset,l=[],c=[],h=J(a,["traf"]);let u=!0;for(let m=0;m<h.length;m++){const y=h[m],E=J(y,["tfhd"])[0];if(!E)return null;K(E,4)===e?(l.push(y),K(E,0)&131072||(u=!1)):c.push(ki(y,o))}if(!l.length||c.length&&!u)return null;if(s!==void 0){let m=t;for(let E=0;E<l.length;E++){const S=l[E];let T=0;const v=J(S,["trun"]);for(let I=0;I<v.length;I++){const b=v[I],_=Math.min(m,K(b,4));if(_){Se(n,b.byteOffset-o+4,_);const L=K(b,0)&16777215,P=(L&256?4:0)+(L&512?4:0)+(L&1024?4:0)+(L&2048?4:0);Fr(n,b,8+(L&1?4:0)+(L&4?4:0)+_*P)}else Se(n,b.byteOffset-o-4,Z.free);m-=_,T+=_}const x=J(S,["senc"])[0];x&&Se(n,x.byteOffset-o+4,T);const A=J(S,["saiz"])[0];if(A){const I=A[1]<<16|A[2]<<8|A[3];let b=4;I&1&&(b+=8);const _=A[b];b+=1,Se(n,A.byteOffset-o+b,T),Fr(n,A,b+4+(_===0?T:0))}}const y=J(n,["mdat"]);if(y.length===1){const E=y[0].byteOffset-o-8;Se(n,E,s-E)}}let d=n,f=0,g=()=>0;if(c.length){({result:d,dropped:f,droppedBefore:g}=Sa(n,c)),Se(d,a.byteOffset-o-8,a.byteLength+8-f);for(let m=0;m<l.length;m++){const y=l[m],E=g(y.byteOffset-o),S=J(y,["trun"]);for(let T=0;T<S.length;T++){const v=S[T];K(v,0)&1&&Se(d,v.byteOffset-o-E+8,K(v,8)-f)}if(E){const T=J(y,["saio"]);for(let v=0;v<T.length;v++){const x=T[v],A=x[0]===0?4:8;let I=K(x,0)&1?12:4,b=K(x,I);for(I+=4;b--;I+=A){const _=I+A-4;Se(d,x.byteOffset-o-E+_,K(x,_)-E)}}}}}if(i){const{durationOffset:m,value:y}=i;Se(d,m-g(m),y)}return s!==void 0?d.subarray(0,s-f):d}function Hl(n,e){const t=n.byteLength;for(let s=0;s<t;){const i=K(n,s);if(i>8&&K(n,s+4)===Z[e])return!0;s=i>1?s+i:t}return!1}function J(n,e){const t=[];return e.length&&va(n,e,0,0,n.byteLength,t),t}function va(n,e,t,s,i,r){const a=e[t];if(a?.length!==4)return;const o=a.charCodeAt(0),l=a.charCodeAt(1),c=a.charCodeAt(2),h=a.charCodeAt(3),u=e.length-1;for(let d=s;d<i;){const f=d+8<=i,g=d+4<=i?n[d]*16777216+(n[d+1]<<16|n[d+2]<<8|n[d+3]):K(n,d),m=g>1?d+g:i;if(f&&n[d+4]===o&&n[d+5]===l&&n[d+6]===c&&n[d+7]===h){const y=Math.min(m,i);t===u?r.push(n.subarray(d+8,y)):va(n,e,t+1,d+8,y,r)}d=m}}function Yl(n){const e=[],t=n[0];let s=8;const i=K(n,s);s+=4;let r=0,a=0;t===0?(r=K(n,s),a=K(n,s+4),s+=8):(r=Mr(n,s),a=Mr(n,s+8),s+=16),s+=2;let o=n.length+a;const l=Ta(n,s);s+=2;for(let c=0;c<l;c++){let h=s;const u=K(n,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return le.warn("SIDX has hierarchical references (not supported)"),null;const g=K(n,h);h+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:l,references:e}}function xa(n){const e=[],t=J(n,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],a=J(r,["tkhd"])[0];if(a){let o=a[0];const l=K(a,o===0?12:20),c=J(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=K(c,o===0?12:20),u=J(r,["mdia","hdlr"])[0];if(u){const d=Ze(u.subarray(8,12)),f={soun:de.AUDIO,vide:de.VIDEO}[d],g=J(r,["mdia","minf","stbl","stsd"])[0],m=Wl(g);f?(e[l]={timescale:h,type:f,stsd:m},e[f]=j({timescale:h,id:l},m)):e[l]={timescale:h,type:d,stsd:m}}}}}return J(n,["moov","mvex","trex"]).forEach(i=>{const r=K(i,4),a=e[r];a&&(a.default={duration:K(i,12),sampleSize:K(i,16),flags:K(i,20)})}),e}function Wl(n){const e=n.subarray(8),t=e.subarray(86),s=Ze(e.subarray(4,8));let i=s,r;const a=s==="enca"||s==="encv";if(a){const c=J(e,[s])[0].subarray(s==="enca"?28:78);J(c,["sinf"]).forEach(u=>{const d=J(u,["schm"])[0];if(d){const f=Ze(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=J(u,["frma"])[0];g&&(i=Ze(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const l=J(t,["avcC"])[0];l&&l.length>3&&(i+="."+ms(l[1])+ms(l[2])+ms(l[3]),r=gs(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=J(e,[s])[0],c=J(l.subarray(28),["esds"])[0];if(c&&c.length>7){let h=4;if(c[h++]!==3)break;h=ii(c,h),h+=2;const u=c[h++];if(u&128&&(h+=2),u&64&&(h+=c[h++]),c[h++]!==4)break;h=ii(c,h);const d=c[h++];if(d===64)i+="."+ms(d);else break;if(h+=12,c[h++]!==5)break;h=ii(c,h);const f=c[h++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((c[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const l=J(t,["hvcC"])[0];if(l&&l.length>12){const c=l[1],h=["","A","B","C"][c>>6],u=c&31,d=K(l,2),f=(c&32)>>5?"H":"L",g=l[12],m=l.subarray(6,12);i+="."+h+u,i+="."+ql(d).toString(16).toUpperCase(),i+="."+f+g;let y="";for(let E=m.length;E--;){const S=m[E];(S||y)&&(y="."+S.toString(16).toUpperCase()+y)}i+=y}r=gs(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=gs(i,t)||i;break}case"vp09":{const l=J(t,["vpcC"])[0];if(l&&l.length>6){const c=l[4],h=l[5],u=l[6]>>4&15;i+="."+it(c)+"."+it(h)+"."+it(u)}break}case"av01":{const l=J(t,["av1C"])[0];if(l&&l.length>2){const c=l[1]>>>5,h=l[1]&31,u=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,f=(l[2]&32)>>5,g=c===2&&d?f?12:10:d?10:8,m=(l[2]&16)>>4,y=(l[2]&8)>>3,E=(l[2]&4)>>2,S=l[2]&3;i+="."+c+"."+it(h)+u+"."+it(g)+"."+m+"."+y+E+S+"."+it(1)+"."+it(1)+"."+it(1)+"."+0,r=gs("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:r}}function gs(n,e){const t=J(e,["dvvC"]),s=t.length?t[0]:J(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+it(i)+"."+it(r)}}function ql(n){let e=0;for(let t=0;t<32;t++)e|=(n>>t&1)<<31-t;return e>>>0}function ii(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function ms(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function it(n){return(n<10?"0":"")+n}function jl(n,e){if(!n||!e)return;const t=e.keyId;t?.byteLength===16&&e.isCommonEncryption&&Aa(n,(s,i)=>{const r=s.subarray(8,24);r.some(a=>a!==0)||(le.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Ie(r)} -> ${Ie(t)}`),s.set(t,8))})}function zl(n){const e=[];return Aa(n,t=>e.push(t.subarray(8,24))),e}function Aa(n,e){J(n,["moov","trak"]).forEach(s=>{const i=J(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let a=J(r,["enca"]);const o=a.length>0;o||(a=J(r,["encv"])),a.forEach(l=>{const c=o?l.subarray(28):l.subarray(78);J(c,["sinf"]).forEach(u=>{const d=Ia(u);d&&e(d,o)})})})}function Ia(n){const e=J(n,["schm"])[0];if(e){const t=Ze(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=J(n,["schi","tenc"])[0];if(s)return s}}}let Nr;function Xl(n){return typeof TextDecoder>"u"?Ue(n):(Nr||(Nr=new TextDecoder("utf-8"))).decode(n).replace(/\0/g,"")}function Ql(n){const e=n.byteLength,t=[];for(let s=0;s<e;){const i=s+8<=e,r=s+4<=e?n[s]*16777216+(n[s+1]<<16|n[s+2]<<8|n[s+3]):K(n,s),a=r>1?s+r:e;if(i&&n[s+4]===109&&n[s+5]===111&&n[s+6]===111&&n[s+7]===102){const o=Math.min(a,e);for(let l=s+8;l<o;){const c=l+8<=o,h=l+4<=o?n[l]*16777216+(n[l+1]<<16|n[l+2]<<8|n[l+3]):K(n,l),u=h>1?l+h:o;if(c&&n[l+4]===116&&n[l+5]===114&&n[l+6]===97&&n[l+7]===102){const d=Math.min(u,o);let f,g;const m=[];for(let y=l+8;y<d;){const E=y+8<=d,S=y+4<=d?n[y]*16777216+(n[y+1]<<16|n[y+2]<<8|n[y+3]):K(n,y),T=S>1?y+S:d;if(E&&n[y+4]===116){const v=Math.min(T,d);n[y+5]===102&&n[y+6]===104&&n[y+7]===100?g||(g=n.subarray(y+8,v)):n[y+5]===102&&n[y+6]===100&&n[y+7]===116?f||(f=n.subarray(y+8,v)):n[y+5]===114&&n[y+6]===117&&n[y+7]===110&&m.push(n.subarray(y+8,v))}y=T}t.push({moofOffset:n.byteOffset+s,tfdt:f,tfhd:g,truns:m})}l=u}}s=a}return t}function Zl(n,e,t,s,i=!0){return La(n,e,s,i)}function Jl(n,e,t,s,i=!1){const r=[],a=e.samples,o=La(a,t,s,i,{isHEVCFlavor:hs(e.codec),samples:r,timeOffset:n,timescale:e.timescale,trackId:e.id});return{samples:r,sampleData:{includeSampleDetails:i,tracks:o}}}function La(n,e,t,s,i){const r={};let a=!1;const o=Ql(n),l=n.byteLength;for(let u=0;u<o.length;u++){const{moofOffset:d,tfdt:f,tfhd:g,truns:m}=o[u],y=K(g,4),E=e[y];if(!E)continue;const S=r[y]||(r[y]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:E.timescale,type:E.type});let T;if(f){const w=f[0];T=K(f,4),w===1&&(T===st?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=st+1,T+=K(f,8))),B(T)&&(!B(S.start)||T<S.start)&&(S.start=T),i&&B(T)&&(i.timeOffset=T/i.timescale)}const v=i?.trackId===y&&E.type===de.VIDEO,x=E.default,A=K(g,0)&16777215;let I=x?.duration||0,b,_=x?.sampleSize||0,L=8;A&1&&(L+=8),A&2&&(L+=4),A&8&&(I=K(g,L),b=g.byteOffset-n.byteOffset+L,L+=4),A&16&&(_=K(g,L));let P=0;const C=(A&1)!==0,F=!C&&(A&131072)!==0;C?(P=K(g,8),P*=Math.pow(2,32),P+=K(g,12)):F&&(P=d);let V=T||0,$=0,k=I;for(let w=0;w<m.length;w++){const O=m[w],N=K(O,4),Y=S.sampleCount;S.sampleCount+=N;const M=O[3]&1;let U=0;const ee=O[3]&4,z=O[2]&1,ie=O[2]&2,Q=O[2]&4,ne=O[2]&8;let te=8;M&&(U=Ci(O,te),te+=4),ee&&(!(O[te+1]&1)&&S.keyFrameIndex===void 0&&(S.keyFrameIndex=Y),te+=4);let oe=P+U;if(!s&&O[1]===0&&O[2]===6&&O[3]===1){var c,h;const ge=V,Ve=oe,Je=te;let W=-1,re=0,ae=0,xe=(c=i?.timeOffset)!=null?c:0;const Te=I/((h=i?.timescale)!=null?h:1),Ce=i?.isHEVCFlavor===!0,Ye=Ce?2:1;for(let be=0;be<N;be++){const ke=O[te]===0?O[te+1]<<16|O[te+2]<<8|O[te+3]:K(O,te),Ke=W===-1&&S.keyFrameIndex===void 0&&(O[te+5]&1)===0;te+=8;const Ne=oe+ke;if(v){if(ke>0){let Pe=oe;do{const mt=n[Pe]===0?n[Pe+1]<<16|n[Pe+2]<<8|n[Pe+3]:K(n,Pe);Pe+=4;const ht=n[Pe],We=Ce?ht>>1&63:ht&31;(Ce?We===39||We===40:We===6)&&ts(n.subarray(Pe,Pe+mt),Ye,xe,i.samples),Pe+=mt}while(Pe<Ne)}xe+=Te}oe=Ne,Ke&&(W=be,re=oe)}if(oe<=l)ae=N;else{let be=Ve,ke=Je;for(let Ke=0;Ke<N;Ke++){const Ne=O[ke]===0?O[ke+1]<<16|O[ke+2]<<8|O[ke+3]:K(O,ke);if(be+=Ne,be>l)break;ae=Ke+1,ke+=8}}if(v&&(i.timeOffset=xe),W!==-1&&re<=l&&S.keyFrameIndex===void 0&&(S.keyFrameIndex=W,S.keyFrameStart=ge+W*I),ae){(!B(S.ptsMin)||ge<S.ptsMin)&&(S.ptsMin=ge);const be=ge+ae*I;(!B(S.ptsMax)||be>S.ptsMax)&&(S.ptsMax=be)}const It=I*N;V=ge+It,$+=It;continue}let ve,we;s&&(ve=[],we={sampleOffset:oe,samples:ve,defaultSampleDurationOffset:b},oe<=l&&S.trun.push(we));let ct;for(let ge=0;ge<N;ge++){let Ve;z?(s&&(Ve=O.byteOffset-n.byteOffset+te),k=K(O,te),te+=4):k=I,ie?(ct=K(O,te),te+=4):ct=_;let Je,W;Q&&(W=O[te+1]&1?1:0,s&&(Je={isNonSync:W,dependsOn:(O[te]&3)===1?1:2}),te+=4);let re=0;if(ne&&(re=O[0]===0?K(O,te):Ci(O,te),te+=4),v){let ae=oe,xe=0;for(;xe<ct;){const Te=K(n,ae);ae+=4,Ra(i.isHEVCFlavor,n[ae])&&ts(n.subarray(ae,ae+Te),i.isHEVCFlavor?2:1,i.timeOffset+re/i.timescale,i.samples),ae+=Te,xe+=Te+4}i.timeOffset+=k/i.timescale}if(oe+=ct,oe<=l){we&&Ve!==void 0&&(we.lastSampleDurationOffset=Ve),W===0&&S.keyFrameIndex===void 0&&(S.keyFrameIndex=ge,S.keyFrameStart=V);const ae=V+re;(!B(S.ptsMin)||ae<S.ptsMin)&&(S.ptsMin=ae),(!B(S.ptsMax)||ae+k>S.ptsMax)&&(S.ptsMax=ae+k),ve&&(ve[ge]={cts:re,duration:k,flags:Je,size:ct})}V+=k,$+=k}!$&&I&&($+=I*N)}S.duration+=$,S.duration&&(a=!0)}if(!a){let u=1/0,d=0;const f=J(n,["sidx"]);for(let g=0;g<f.length;g++){const m=Yl(f[g]);if(m!=null&&m.references){u=Math.min(u,m.earliestPresentationTime/m.timescale);const y=m.references.reduce((E,S)=>E+S.info.duration||0,0);d=Math.max(d,y+m.earliestPresentationTime/m.timescale)}}d&&B(d)&&Object.keys(r).forEach(g=>{r[g].duration||(r[g].duration=d*r[g].timescale-r[g].start)})}return r}function ec(n){const e={valid:null,remainder:null},t=J(n,["moof"]);if(t.length<2)return e.remainder=n,e;const s=t[t.length-1];return e.valid=n.slice(0,s.byteOffset-8),e.remainder=n.slice(s.byteOffset-8),e}function He(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function tc(n,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let a=!1;return J(s,["moof"]).map(l=>{const c=l.byteOffset-8;J(l,["traf"]).map(u=>{const d=J(u,["tfdt"]).map(f=>{const g=f[0];let m=K(f,4);return g===1&&(m*=Math.pow(2,32),m+=K(f,8)),m/i})[0];return d!==void 0&&(n=d),J(u,["tfhd"]).map(f=>{const g=K(f,4),m=K(f,0)&16777215,y=(m&1)!==0;let E=0;const S=(m&2)!==0,T=(m&8)!==0;let v=0;const x=(m&16)!==0;let A=0;const I=(m&32)!==0,b=!y&&(m&131072)!==0;let _=8;g===r&&(y?(E=K(f,_),_+=4,E*=Math.pow(2,32),E+=K(f,_),_+=4):b&&(E=c),S&&(_+=4),T&&(v=K(f,_),_+=4),x&&(A=K(f,_),_+=4),I&&(_+=4),e.type==="video"&&(a=hs(e.codec)),J(u,["trun"]).map(L=>{const P=L[0],C=K(L,0)&16777215,F=(C&1)!==0;let V=0;const $=(C&4)!==0,k=(C&256)!==0;let w=0;const O=(C&512)!==0;let N=0;const Y=(C&1024)!==0,M=(C&2048)!==0;let U=0;const ee=K(L,4);let z=8;F&&(V=K(L,z),z+=4),$&&(z+=4);let ie=E+V;for(let Q=0;Q<ee;Q++){if(k?(w=K(L,z),z+=4):w=v,O?(N=K(L,z),z+=4):N=A,Y&&(z+=4),M&&(P===0?U=K(L,z):U=Ci(L,z),z+=4),e.type===de.VIDEO){let ne=0;for(;ne<N;){const te=K(s,ie);if(ie+=4,Ra(a,s[ie])){const oe=s.subarray(ie,ie+te);ts(oe,a?2:1,n+U/i,t)}ie+=te,ne+=te+4}}n+=w/i}}))})})}),t}function hs(n){if(!n)return!1;const e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Ra(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ts(n,e,t,s){const i=ba(n);let r=0;r+=e;let a=0,o=0,l=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;l=i[r++],a+=l}while(l===255);o=0;do{if(r>=i.length)break;l=i[r++],o+=l}while(l===255);const c=i.length-r;let h=r;if(o<c)r+=o;else if(o>c){le.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(i[h++]===181){const d=Ta(i,h);if(h+=2,d===49){const f=K(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const m=i[h++],y=31&m,E=64&m,S=E?2+y*3:0,T=new Uint8Array(S);if(E){T[0]=m;for(let v=1;v<S;v++)T[v]=i[h++]}s.push({type:g,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){const u=[];for(let g=0;g<16;g++){const m=i[h++].toString(16);u.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:Xl(f),userDataBytes:f})}}}function ba(n){const e=n.byteLength;let t,s=n.indexOf(3,3);for(;s!==-1;)n[s-1]===0&&n[s-2]===0&&(t||(t=[])).push(s),s=n.indexOf(3,s+1);if(!t)return n;const i=e-t.length,r=new Uint8Array(i);let a=0,o=0;for(let l=0;l<i;o++,l++)o===t[a]&&(o++,a++),r[l]=n[o];return r}function sc(n){const e=n[0];let t="",s="",i=0,r=0,a,o=0,l=0,c=4;if(e===0){const u=fs(n,c),d=u!==null?fs(n,c+u.length):null;u!==null&&d!==null?(t=u,s=d,c+=u.length+d.length,i=K(n,c),c+=4,r=K(n,c),c+=4,o=K(n,c),c+=4,l=K(n,c),c+=4):(le.warn(`Unterminated ${u===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),c=n.length)}else if(e===1){i=K(n,c),c+=4;const u=K(n,c);c+=4;const d=K(n,c);c+=4,a=2**32*u+d,ll(a)||(a=Number.MAX_SAFE_INTEGER,le.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(n,c),c+=4,l=K(n,c),c+=4;const f=fs(n,c),g=f!==null?fs(n,c+f.length):null;f!==null&&(t=f,c+=f.length),g!==null?(s=g,c+=g.length):(le.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"}`),c=n.length)}const h=n.subarray(c,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function ic(n,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function rc(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),ic([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t)}function _a(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let s=0;for(;s+32<t;){const i=new DataView(n,s),r=ac(i);e.push(r),s+=r.size}}return e}function nc(n){const e=[];for(let t=0;t<n.length;){const s=n[t++],i=s&7;if(i===0){for(;n[t++]&128;);continue}if(i!==2){t+=i===1?8:4;continue}let r=0;for(let a=0,o=128;o&128;a+=7)r|=((o=n[t++])&127)<<a;if(s>>3===2)if(r===32){const a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(n[t+o*2],n[t+o*2+1]),16);e.push(a)}else r===16&&e.push(n.subarray(t,t+16));t+=r}return e}function ac(n){const e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=n.buffer,o=Ie(new Uint8Array(a,t+12,16));let l=null,c=null,h=0;if(r===0)h=28;else{const d=n.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};l=[];for(let f=0;f<d;f++)l.push(new Uint8Array(a,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=n.getUint32(h);return e-32<u?{offset:t,size:e}:(c=new Uint8Array(a,t+h+4,u),r===0&&(l=nc(c)),{version:r,systemId:o,kids:l,data:c,offset:t,size:e})}const Ut=Da("userAgent"),oc=Da("vendor");let ri,ni,ai;function Da(n){try{return navigator[n]||""}catch{}return""}function lc(){if(ai===void 0){const n=Ut.match(/Safari\/(\d+)/i);ai=n?parseInt(n[1]):0}return ai}function qt(){if(ri===void 0){const n=Ut.match(/Chrome\/(\d+)/i);ri=n?parseInt(n[1]):0}return ri}function cc(){if(ni===void 0){const n=Ut.match(/Firefox\/(\d+)/i);ni=n?parseInt(n[1]):0}return ni}function Pa(){return/\(Windows.+Firefox\//i.test(Ut)}function hc(){return oc.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Ut)}function uc(){return/Android/.test(Ut)}const Nt={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 rr(n,e){const t=Nt[e];return!!t&&!!t[n.slice(0,4)]}function ss(n,e,t=!0){return!n.split(",").some(s=>!nr(s,e,t))}function nr(n,e,t=!0){var s;const i=xt(t);return(s=i?.isTypeSupported(is(n,e)))!=null?s:!1}function is(n,e){return`${e}/mp4;codecs=${n}`}function Br(n){if(n){const e=n.substring(0,4);return Nt.video[e]}return 2}function Fs(n){const e=Pa();return n.split(",").reduce((t,s)=>{const r=e&&hs(s)?9:Nt.video[s];return r?(r*2+t)/(t?3:2):(Nt.audio[s]+t)/(t?2:1)},0)}const oi={};function dc(n,e=!0){if(oi[n])return oi[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let i=0;i<t.length;i++){var s;if(nr(t[i],"audio",e))return oi[n]=t[i],t[i];if(t[i]==="mp3"&&(s=xt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}const fc=/flac|opus|mp4a\.40\.34/i;function Ns(n,e=!0){return n.replace(fc,t=>dc(t.toLowerCase(),e))}function gc(n,e){const t=[];if(n){const s=n.split(",");for(let i=0;i<s.length;i++)rr(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function Ds(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&($r(n,"audio")||$r(n,"video")))return n;if(e){const t=e.split(",");if(t.length>1){if(n){for(let s=t.length;s--;)if(t[s].substring(0,4)===n.substring(0,4))return t[s]}return t[0]}}return e||n}function $r(n,e){return rr(n,e)&&nr(n,e)}function mc(n){const e=n.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function pc(n){if(n.startsWith("av01.")){const e=n.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return n}function Ur(n){const e=xt(n)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Oi(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const yc={supported:!0,powerEfficient:!0,smooth:!0},Ec={supported:!1,smooth:!1,powerEfficient:!1},Ca={supported:!0,configurations:[],decodingInfoResults:[yc]};function ka(n,e){return{supported:!1,configurations:e,decodingInfoResults:[Ec],error:n}}function Tc(n,e,t,s,i,r){const a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,l=r?.audioCodec,c=r?.channels,h=c?parseInt(c):l?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(m=>{d[m]=(d[m]||0)+g.channels[m]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>hs(d))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!u&&B(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Oa(n,e,t,s={}){const i=n.videoCodec;if(!i&&!n.audioCodec||!t)return Promise.resolve(Ca);const r=[],a=Sc(n),o=a.length,l=vc(n,e,o>0),c=l.length;for(let h=o||1*c||1;h--;){const u={type:"media-source"};if(o&&(u.video=a[h%o]),c){u.audio=l[h%c];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>hs(u))&&Pa())return Promise.resolve(ka(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=xc(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function Sc(n){var e;const t=(e=n.videoCodec)==null?void 0:e.split(","),s=Ma(n),i=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return t?t.map(l=>{const c={contentType:is(pc(l),"video"),width:i,height:r,bitrate:s,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function vc(n,e,t){var s;const i=(s=n.audioCodec)==null?void 0:s.split(","),r=Ma(n);return i&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var l;const c=o?(l=e.groups[o])==null?void 0:l.tracks:null;return c?c.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(f=>{const g={contentType:is(f,"audio"),bitrate:t?wa(f,r):r};d&&(g.channels=""+d),h.push(g)})}return h},a):a},[]):[]}function wa(n,e){if(e<=1)return 1;let t=128e3;return n==="ec-3"?t=768e3:n==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Ma(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function xc(n){let e="";const{audio:t,video:s}=n;if(s){const i=Oi(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=Oi(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}function St(n,e,t){const s=encodeURIComponent(e),i=`${s}=${encodeURIComponent(t)}`;let r=!1;const a=[];n.search.substring(1).split("&").forEach(o=>{o===s||o.startsWith(s+"=")?r||(a.push(i),r=!0):o&&a.push(o)}),r||a.push(i),n.search=a.join("&")}const wi=["NONE","TYPE-0","TYPE-1",null];function Ac(n){return wi.indexOf(n)>-1}const Bs=["SDR","PQ","HLG"];function Ic(n){return!!n&&Bs.indexOf(n)>-1}var Ps={No:"",Yes:"YES",v2:"v2"};function Gr(n){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?Ps.v2:Ps.Yes:Ps.No}class Vr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&St(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&St(t,"_HLS_part",this.part.toString()),this.skip&&St(t,"_HLS_skip",this.skip),t.href}}class rs{constructor(e){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=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.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(e){return Kr(this._audioGroups,e)}hasSubtitleGroup(e){return Kr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Kr(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function Lc(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function Rc(n,e){let t=!1,s=[];if(n&&(t=n!=="SDR",s=[n]),e){s=e.allowedVideoRanges||Bs.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Lc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const bc=n=>{const e=new WeakSet;return(t,s)=>{if(n&&(s=n(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},fe=(n,e)=>JSON.stringify(n,bc(e));function _c(n,e,t,s,i){const r=Object.keys(n),a=s?.channels,o=s?.audioCodec,l=i?.videoCodec,c=a&&parseInt(a)===2;let h=!1,u=!1,d=1/0,f=1/0,g=1/0,m=1/0,y=0,E=[];const{preferHDR:S,allowedVideoRanges:T}=Rc(e,i);for(let b=r.length;b--;){const _=n[r[b]];h||(h=_.channels[2]>0),d=Math.min(d,_.minHeight),f=Math.min(f,_.minFramerate),g=Math.min(g,_.minBitrate),T.filter(P=>_.videoRanges[P]>0).length>0&&(u=!0)}d=B(d)?d:0,f=B(f)?f:0;const v=Math.max(1080,d),x=Math.max(30,f);g=B(g)?g:t,t=Math.max(g,t),u||(e=void 0);const A=r.length>1;return{codecSet:r.reduce((b,_)=>{const L=n[_];if(_===b)return b;if(E=u?T.filter(P=>L.videoRanges[P]>0):[],A){if(L.minBitrate>t)return et(_,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),b;if(!L.hasDefaultAudio)return et(_,"no renditions with default or auto-select sound found"),b;if(o&&_.indexOf(o.substring(0,4))%5!==0)return et(_,`audio codec preference "${o}" not found`),b;if(a&&!c){if(!L.channels[a])return et(_,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),b}else if((!o||c)&&h&&L.channels[2]===0)return et(_,"no renditions with stereo sound found"),b;if(L.minHeight>v)return et(_,`min resolution of ${L.minHeight} > maximum of ${v}`),b;if(L.minFramerate>x)return et(_,`min framerate of ${L.minFramerate} > maximum of ${x}`),b;if(!E.some(P=>L.videoRanges[P]>0))return et(_,`no variants with VIDEO-RANGE of ${fe(E)} found`),b;if(l&&_.indexOf(l.substring(0,4))%5!==0)return et(_,`video codec preference "${l}" not found`),b;if(L.maxScore<y)return et(_,`max score of ${L.maxScore} < selected max of ${y}`),b}return b&&(Fs(_)>=Fs(b)||L.fragmentError>n[b].fragmentError)?b:(m=L.minIndex,y=L.maxScore,_)},void 0),videoRanges:E,preferHDR:S,minFramerate:f,minBitrate:g,minIndex:m}}function et(n,e){le.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Fa(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Dc(n,e,t,s){return n.slice(t,s+1).reduce((i,r,a)=>{if(!r.codecSet)return i;const o=r.audioGroups;let l=i[r.codecSet];l||(i[r.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,r.bitrate);const c=Math.min(r.height,r.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,r.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,r.score),l.fragmentError+=r.fragmentError,l.videoRanges[r.videoRange]=(l.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+u.channels[d]}))}),i},{})}function Hr(n){if(!n)return n;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=n;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function at(n,e,t){if("attrs"in n){const s=e.indexOf(n);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(Dt(n,i,t))return s}return-1}function Dt(n,e,t){const{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,l=n.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||Pc(r,e.lang))&&(r===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in n)||Cc(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function Pc(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function Cc(n,e=""){const t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function _t(n,e){const{audioCodec:t,channels:s}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function kc(n,e,t,s,i){const r=e[s],o=e.reduce((d,f,g)=>{const m=f.uri;return(d[m]||(d[m]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=Yr(e,s,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,g=t.filter(m=>ns(m.groupId,f));return at(n,g,i)>-1});return u>-1?u:Yr(e,s,d=>{const f=d.audioGroups,g=t.filter(m=>ns(m.groupId,f));return at(n,g,i)>-1})}function Yr(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}function $s(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}function ns(n,e){return e?e.indexOf(n)!==-1:!0}function Na(n,e){if(e||n){const t=ue({},e);return n&&(n.videoCodec&&(t.videoCodec=n.videoCodec),n.videoRange&&(t.allowedVideoRanges=[n.videoRange])),t}}class Oc extends Ge{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:a}=this;if(!a)return;const{autoLevelEnabled:o,media:l}=a;if(!i||!l)return;const c=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=c-h.loading.start,f=a.minAutoLevel,g=i.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=m>-1&&m!==g,E=!!t||y;if(!E&&(l.paused||!l.playbackRate||!l.readyState))return;const S=a.mainForwardBufferInfo;if(!E&&S===null)return;const T=this.bwEstimator.getEstimateTTFB(),v=Math.abs(l.playbackRate);if(d<=Math.max(T,1e3*(u/(v*2))))return;const x=S?S.len/v:0,A=h.loading.first?h.loading.first-h.loading.start:-1,I=h.loaded&&A>-1,b=this.getBwEstimate(),_=a.levels,L=_[g],P=Math.max(h.loaded,Math.round(u*(i.bitrate||L.averageBitrate)/8));let C=I?d-A:d;C<1&&I&&(C=Math.min(d,h.loaded*8/b));const F=I?h.loaded*1e3/C:0,V=T/1e3,$=F?(P-h.loaded)/F:P*8/b+V;if($<=x)return;const k=F?F*8:b,w=((s=t?.details||a.latestLevelDetails)==null?void 0:s.live)===!0,O=a.config.abrBandWidthUpFactor;let N=Number.POSITIVE_INFINITY,Y;for(Y=g-1;Y>f;Y--){const z=_[Y].maxBitrate,ie=!_[Y].details||w;if(N=this.getTimeToLoadFrag(V,k,u*z,ie),N<Math.min(x,u+V))break}if(N>=$||N>u*10)return;I?this.bwEstimator.sample(d-Math.min(T,A),h.loaded):this.bwEstimator.sampleTTFB(d);const M=_[Y].maxBitrate;this.getBwEstimate()*O>M&&(this.firstAutoFloor=Math.min(Y,a.firstLevel),this.resetEstimator(M));const U=this.findBestLevel(M,f,Y,0,x,1,1);U>-1&&(Y=U),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
|
|
2
|
+
Fragment duration: ${i.duration.toFixed(3)}
|
|
3
|
+
Time to underbuffer: ${x.toFixed(3)} s
|
|
4
|
+
Estimated load time for current fragment: ${$.toFixed(3)} s
|
|
5
|
+
Estimated load time for down switch fragment: ${N.toFixed(3)} s
|
|
6
|
+
TTFB estimate: ${A|0} ms
|
|
7
|
+
Current BW estimate: ${B(b)?b|0:"Unknown"} bps
|
|
8
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
9
|
+
Switching to level ${Y} @ ${M|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Y,this.clearTimer();const ee=()=>{this.clearTimer();const z=this.hls;if(this.fragCurrent===i&&z.loadLevel===Y&&Y>0){const ie=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Y>0?"and switching down":""}
|
|
10
|
+
Fragment duration: ${i.duration.toFixed(3)} s
|
|
11
|
+
Time to underbuffer: ${ie.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,Y>f){let Q=this.findBestLevel(z.levels[f].bitrate,f,Y,0,ie,1,1);Q===-1&&(Q=f),z.nextLoadLevel=z.nextAutoLevel=Q,this.firstAutoFloor=Math.min(Q,z.firstLevel),this.resetEstimator(z.levels[Q].bitrate)}}};y||$>N*2?ee():this.timer=self.setInterval(ee,N*1e3),a.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const e=this.hls.config;return new Tl(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.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(e,t){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(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&_i(s,i)){const a=performance.now(),o=r?r.stats:s.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,a=i?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;B(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var s;const{frag:i,part:r}=t,a=r?r.stats:i.stats;if(i.type===H.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(s=this.hls)!=null&&s.config.abrMaxWithRealBitrate){const o=r?r.duration:i.duration,l=this.hls.levels[i.level],c=(l.loaded?l.loaded.bytes:0)+a.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:c,duration:h},l.realBitrate=Math.round(8*c/h)}if(i.bitrateTest){const o={stats:a,frag:i,part:r,id:i.type};this.onFragBuffered(p.FRAG_BUFFERED,o),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const o=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==H.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:e}=this;if(!e)return 0;const{maxAutoLevel:t,minAutoLevel:s}=e,i=this.getBwEstimate(),r=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(i,s,t,r/2,a,1,1);if(o>-1)return o;const l=e.firstLevel,c=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,h=Math.min(Math.max(l,s),t,c);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const y=this.findBestLevel(l,a,i,c,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const f=this.findBestLevel(l,a,i,c,d,h,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],m=s.loadLevelObj;return m&&g?.bitrate<m.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e?.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,s,i,r,a,o){const{hls:l,lastLoadedFragLevel:c,fragCurrent:h,partCurrent:u}=this;if(!l)return-1;const d=i+r,f=c===-1?l.firstLevel:c,{levels:g,allAudioTracks:m,loadLevel:y,latestLevelDetails:E,config:S}=l;if(g.length===1)return 0;const T=g[f],v=!!(E!=null&&E.live),x=y===-1||c===-1;let A,I="SDR",b=T?.frameRate||0;const{audioPreference:_,videoPreference:L}=S,P=this.audioTracksByGroup||(this.audioTracksByGroup=Fa(m));let C=-1;if(x){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=Dc(g,P,t,s)),O=_c(w,I,e,_,L),{codecSet:N,videoRanges:Y,minFramerate:M,minBitrate:U,minIndex:ee,preferHDR:z}=O;C=ee,A=N,I=z?Y[Y.length-1]:Y[0],b=M,e=Math.max(e,U),this.log(`picked start tier ${fe(O)}`)}else A=T?.codecSet,I=T?.videoRange;const F=u?u.duration:h?h.duration:0,V=this.bwEstimator.getEstimateTTFB()/1e3,$=[];for(let w=s;w>=t;w--){var k;const O=g[w],N=w>f;if(!O)continue;if(S.useMediaCapabilities&&!O.supportedResult&&!O.supportedPromise){const Q=navigator.mediaCapabilities;typeof Q?.decodingInfo=="function"&&Tc(O,P,I,b,e,_)?(O.supportedPromise=Oa(O,P,Q,this.supportedCache),O.supportedPromise.then(ne=>{if(!this.hls)return;O.supportedResult=ne;const te=this.hls.levels,oe=te.indexOf(O);ne.error?this.warn(`MediaCapabilities decodingInfo error: "${ne.error}" for level ${oe} ${fe(ne)}`):ne.supported?ne.decodingInfoResults.some(ve=>ve.smooth===!1||ve.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${oe} not smooth or powerEfficient: ${fe(ne)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${oe} ${fe(ne)}`),oe>-1&&te.length>1&&(this.log(`Removing unsupported level ${oe}`),this.hls.removeLevel(oe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ne=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ne}`)})):O.supportedResult=Ca}if((A&&O.codecSet!==A||I&&O.videoRange!==I||N&&b>O.frameRate||!N&&b>0&&b<O.frameRate||(k=O.supportedResult)!=null&&(k=k.decodingInfoResults)!=null&&k.some(Q=>Q.smooth===!1))&&(!x||w!==C)){$.push(w);continue}const Y=O.details,M=(u?Y?.partTarget:Y?.averagetargetduration)||F||1;let U;N?U=o*e:U=a*e;const ee=F&&i>=F*2&&r===0?O.averageBitrate:O.maxBitrate,z=this.getTimeToLoadFrag(V,U,ee*M,!Y||Y.live);if(U>=ee&&(w===c||O.loadError===0&&O.fragmentError===0||ha(O,S.errorPenaltyExpireMs))&&(z<=V||!B(z)||v&&!this.bitrateTestDelay||z<d)){const Q=this.forcedAutoLevel;return w!==y&&(Q===-1||Q!==y)&&($.length&&this.trace(`Skipped level(s) ${$.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[$[0]].codecs}" ${g[$[0]].videoRange}; not compatible with "${A}" ${I}`),this.info(`switch candidate:${f}->${w} adjustedbw(${Math.round(U)})-bitrate=${Math.round(U-ee)} ttfb:${V.toFixed(1)} avgDuration:${M.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${z.toFixed(1)} firstSelection:${x} codecSet:${O.codecSet} videoRange:${O.videoRange} hls.loadLevel:${y}`)),x&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Ba={search:function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];const a=e(r);if(a>0)t=i+1;else if(a<0)s=i-1;else return r}return null}};function wc(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!B(e))return null;const s=n[0].programDateTime;if(e<(s||0))return null;const i=n[n.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<n.length;++r){const a=n[r];if(Fc(e,t,a))return a}return null}function Bt(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[1+n.sn-e[0].sn]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=e[2+n.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&Wr(t,s,r)===0||Mc(r,n,Math.min(i,s))))return r;const a=Ba.search(e,Wr.bind(null,t,s));return a&&(a!==n||!r)?a:r}function Mc(n,e,t){if(e?.start===0&&e.level<n.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}function Wr(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function Fc(n,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function $a(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){let s=n.fragments;const{fragmentHint:i}=n;i&&(s=s.concat(i));let r;return Ba.search(s,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function Ua(n,e){return e===n.endSN&&n.fragmentHint?n.fragmentHint:n.fragments[1+e-n.startSN]||null}var Re={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Le={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class Nc extends Ge{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===H.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=jt();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Re.SendAlternateToPenaltyBox;return}case R.PLAYLIST_UNCHANGED_ERROR:case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a;const o=t.parent===H.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=i.loadLevelObj;if(o&&(r.type===se.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===se.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Re.SendAlternateToPenaltyBox,t.errorAction.flags=Le.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case R.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Le.ResetMediaSource|Le.SwitchToSDR;return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_APPEND_NO_PROGRESS:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=jt();return}t.type===q.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=jt())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Cr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Zt(i,r,Ms(e),e.response))return{action:Re.RetryRequest,flags:Le.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Cr(la(e)?a:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,!ca(e)&&Zt(o,l,Ms(e),e.response)))return{action:Re.RetryRequest,flags:Le.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,s);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,a;const c=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),c===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const m=(r=e.frag)==null?void 0:r.type,E=(m===H.AUDIO&&c===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&qr(e))&&u.some(({audioCodec:A})=>i.audioCodec!==A),T=e.sourceBufferName==="video"&&qr(e)&&u.some(({codecSet:A,audioCodec:I})=>i.codecSet!==A&&i.audioCodec===I),{type:v,groupId:x}=(a=e.context)!=null?a:{};for(let A=u.length;A--;){const I=(A+d)%u.length;if(I!==d&&I>=f&&I<=g&&(u[I].loadError===0||ha(u[I],s.config.errorPenaltyExpireMs))){var o,l;const b=u[I];if(c===R.FRAG_GAP&&m===H.MAIN&&e.frag){const _=u[I].details;if(_){const L=Bt(e.frag,_.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(v===se.AUDIO_TRACK&&b.hasAudioGroup(x)||v===se.SUBTITLE_TRACK&&b.hasSubtitleGroup(x))continue;if(m===H.AUDIO&&(o=i.audioGroups)!=null&&o.some(_=>b.hasAudioGroup(_))||m===H.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(_=>b.hasSubtitleGroup(_))||E&&i.audioCodec===b.audioCodec||T&&i.codecSet===b.codecSet||!E&&i.audioCodec!==b.audioCodec)continue}h=I;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Re.SendAlternateToPenaltyBox,flags:Le.None,nextAutoLevel:h}}return{action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s,i;switch((s=t.errorAction)==null?void 0:s.action){case Re.DoNothing:break;case Re.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP&&t.details!==R.PLAYLIST_UNCHANGED_ERROR&&!Ga(t)&&(t.fatal=!0);break;case Re.RetryRequest:break}if((((i=t.errorAction)==null?void 0:i.flags)||0)&Le.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===Le.None)this.switchLevel(e,i);else if(s.flags&Le.SwitchToSDR){const o=this.hls.levels,l=o.length;for(let c=l;c--;)o[c].videoRange!=="SDR"?(o[c].fragmentError++,o[c].loadError++):i===void 0&&(i=c)}else if(s.flags&Le.MoveAllAlternatesMatchingHDCP){const o=this.getVariantLevelIndex(e.frag),l=t.levels[o],c=l?.attrs["HDCP-LEVEL"];s.hdcpLevel=c;const h=c==="NONE";c&&!h?(t.maxHdcpLevel=wi[wi.indexOf(c)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(h&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=Le.MoveAllAlternatesMatchingKey)}if(s.flags&Le.MoveAllAlternatesMatchingKey){const o=e.decryptdata;if(o){const l=this.hls.levels,c=l.length;for(let u=c;u--;)if(this.variantHasKey(l[u],o)){var r,a;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(r=l[u].audioGroups)==null?void 0:r.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${Ie(o.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${e.error})`),this.hls.removeLevel(u)}const h=e.frag;if(this.hls.levels.length<c)s.resolved=!0;else if(h&&h.type!==H.MAIN){const u=h.decryptdata;u&&!o.matches(u)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Oi(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function qr(n){const e=n.details;return e===R.BUFFER_ADD_CODEC_ERROR||e===R.MEDIA_SOURCE_REQUIRES_RESET||e===R.BUFFER_APPEND_ERROR&&!Ga(n)}function Ga(n){return n.details===R.BUFFER_APPEND_ERROR&&(n.error.name==="QuotaExceededError"||n.error.name==="InvalidStateError")}function jt(n){const e={action:Re.DoNothing,flags:Le.None};return n&&(e.resolved=!0),e}var ye={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Bc{constructor(e){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=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let a=r.length;a--;){const o=i[r[a]];if(o?.body.type===t&&(!s||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,i,r,a){this.timeRanges&&(this.timeRanges[e]=t);const o=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{const c=this.fragments[l];if(!c||!this.hls)return;const h=c.body;if(o>=h.sn)return;if(!c.buffered&&(!c.loaded||a)){h.type===s&&this.removeFragment(h);return}const u=c.range[e];if(u){if(u.time.length===0){this.removeFragment(h);return}if(u.time.some(d=>{const f=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return f&&this.removeFragment(h),f}),i&&i!==h&&qt()){const d=i.endPTS,f=h.startPTS;if(d&&f&&c.range.video){const g=f-d;g<0&&g>-.1&&(this.removeFragment(h),this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i,id:r}=e;if(!t||!Ee(s))return;const a=Ct(s),o=this.fragments[a];if(!o||o.buffered&&s.gap)return;const l=!s.relurl;Object.keys(t).forEach(h=>{const u=s.elementaryStreams[h];if(!u)return;const d=t[h],f=l||u.partial===!0;o.range[h]=this.getBufferedTimes(s,i,f,d),this.detectEvictedFragments(h,d,r,s,i)}),o.loaded=null;const c=Object.keys(o.range);if(c.length){if(this.bufferedEnd(o,s),ps(o)||this.removeParts(s.sn-1,s.type),!i){const h=Math.min(.004,s.duration);c.some(u=>{var d;const f=(d=o.range[u])==null?void 0:d.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<h;return g&&this.addAsGap(s),g})}}else this.removeFragment(s)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=jr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Ct(e);let i=this.fragments[s];return!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(a<d&&o>u){const f=Math.max(a,i.start(h)),g=Math.min(o,i.end(h));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&ps(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||ps(t))}getState(e){const t=Ct(e),s=this.fragments[t];return s?s.buffered?ps(s)?ye.PARTIAL:ye.OK:ye.APPENDING:ye.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Ee(t.frag)||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=Ct(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if(!Ee(s))return;const a=s.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=r}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ct(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,s){const{fragments:i}=this;let r=0,a=0;const o=Object.keys(i);for(let l=0;l<o.length;l++){const c=i[o[l]];if(!c||!c.buffered||c.body.type!==t)continue;const h=c.body;if(h.gap)return 0;const u=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&h.bitrate*8*h.duration;if(h.end<=e&&u&&(r+=u,a=Math.max(a,h.end),r>=s))return a}return a>0?a:0}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==s||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Ct(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=jr(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function ps(n){var e,t,s,i;return n.buffered&&!!(n.body.gap||(e=n.range.video)!=null&&e.partial||(t=n.range.audio)!=null&&t.partial||(s=n.range.audiovideo)!=null&&s.partial||(i=n.range.subs)!=null&&i.partial)}function Ct(n){return`${n.type}_${n.level}_${n.sn}`}function jr(n,e){return n.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var At={cbc:0,ctr:1};class $c{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case At.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case At.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Uc(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}class Gc{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_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],f=new Uint32Array(256);let g=0,m=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let E=m^m<<1^m<<2^m<<3^m<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;const S=f[g],T=f[S],v=f[T];let x=f[E]*257^E*16843008;i[g]=x<<24|x>>>8,r[g]=x<<16|x>>>16,a[g]=x<<8|x>>>24,o[g]=x,x=v*16843009^T*65537^S*257^g*16843008,c[E]=x<<24|x>>>8,h[E]=x<<16|x>>>16,u[E]=x<<8|x>>>24,d[E]=x,g?(g=S^f[f[f[v^S]]],m^=f[f[m]]):g=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],m=f[1],y=f[2],E=f[3];let S,T;for(o=0;o<a;o++){if(o<r){S=c[o]=t[o];continue}T=S,o%r===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255],T^=d[o/r|0]<<24):r>6&&o%r===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255]),c[o]=S=(c[o-r]^T)>>>0}for(l=0;l<a;l++)o=a-l,l&3?T=c[o]:T=c[o-4],l<4||o<=4?h[l]=T:h[l]=g[u[T>>>24]]^m[u[T>>>16&255]]^y[u[T>>>8&255]]^E[u[T&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let f=d[0],g=d[1],m=d[2],y=d[3];const E=new Int32Array(e),S=new Int32Array(E.length);let T,v,x,A,I,b,_,L,P,C,F,V,$,k;const w=this.networkToHostOrderSwap;for(;t<E.length;){for(P=w(E[t]),C=w(E[t+1]),F=w(E[t+2]),V=w(E[t+3]),I=P^r[0],b=V^r[1],_=F^r[2],L=C^r[3],$=4,k=1;k<i;k++)T=l[I>>>24]^c[b>>16&255]^h[_>>8&255]^u[L&255]^r[$],v=l[b>>>24]^c[_>>16&255]^h[L>>8&255]^u[I&255]^r[$+1],x=l[_>>>24]^c[L>>16&255]^h[I>>8&255]^u[b&255]^r[$+2],A=l[L>>>24]^c[I>>16&255]^h[b>>8&255]^u[_&255]^r[$+3],I=T,b=v,_=x,L=A,$=$+4;T=a[I>>>24]<<24^a[b>>16&255]<<16^a[_>>8&255]<<8^a[L&255]^r[$],v=a[b>>>24]<<24^a[_>>16&255]<<16^a[L>>8&255]<<8^a[I&255]^r[$+1],x=a[_>>>24]<<24^a[L>>16&255]<<16^a[I>>8&255]<<8^a[b&255]^r[$+2],A=a[L>>>24]<<24^a[I>>16&255]<<16^a[b>>8&255]<<8^a[_&255]^r[$+3],S[t]=w(T^f),S[t+1]=w(A^g),S[t+2]=w(x^m),S[t+3]=w(v^y),f=P,g=C,m=F,y=V,t=t+4}return S.buffer}}class Vc{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Kc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Kc(n){switch(n){case At.cbc:return"AES-CBC";case At.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const Hc=16;class ar{constructor(e,t){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=e.enableSoftwareAES,t!==!0)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.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:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);this.reset();const i=this.decryptRange;return i?i.start===0&&i.end>=s.length?s:s.slice(i.start,i.end):Uc(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((a,o)=>{const l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,s,i);const c=this.flush();c?a(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:a,remainderData:o}=this;if(i!==At.cbc||t.byteLength!==16)return le.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=He(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;r&&(s=r);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new Gc),c.expandKey(t);const h=a;return this.currentResult=c.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Vc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new $c(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(le.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%Hc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(le.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const zr=Math.pow(2,17);class Xr{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,s,i){const r=e.url;if(!r)return Promise.reject(new rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,o=a.fLoader,l=a.loader;return new Promise((c,h)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(y=>y[0]==="GAP")){h(Zr(e));return}else e.gap=!1;const u=this.loader=o?new o(a):new l(a),d=Qr(e,null,t);e.loader=u;const f=kr(a.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:zr};u.stats.retry=e.stats.retry,e.stats=u.stats;const m={onSuccess:(y,E,S,T)=>{this.resetLoader(e,u);let v=y.data;S.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),c({frag:e,part:null,payload:v,networkDetails:T})},onError:(y,E,S,T)=>{this.resetLoader(e,u),h(new rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:j({url:r,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:S,stats:T}))},onAbort:(y,E,S)=>{this.resetLoader(e,u),h(new rt({type:q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:S,stats:y}))},onTimeout:(y,E,S)=>{this.resetLoader(e,u),h(new rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:S,stats:y}))}};if(s){const y=this.gateProgress(s,i);m.onProgress=(E,S,T,v)=>y({frag:e,part:null,payload:T,networkDetails:v})}u.load(d,g,m)})}gateProgress(e,t){let s=e;if(t){const i=[];let r=!1;t.then(()=>{r=!0,i.forEach(a=>e(a)),i.length=0}).catch(()=>{}),s=a=>{r?e(a):i.push(a)}}return s}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Zr(e,t));return}const c=this.loader=r?new r(i):new a(i),h=Qr(e,t);e.loader=c;const u=kr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zr};t.stats=c.stats,c.load(h,d,{onSuccess:(f,g,m,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:f.data,networkDetails:y};s(E),o(E)},onError:(f,g,m,y)=>{this.resetLoader(e,c),l(new rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:j({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:y}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new rt({type:q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,c),l(new rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(s.loaded/r),l),u=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qr(n,e=null,t){const s=e||n,i={type:se.MEDIA_FRAGMENT,frag:n,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=Us(n,e,t);return r.resetIV&&(i.resetIV=!0),r.byteRange&&(i.rangeStart=r.byteRange.start,i.rangeEnd=r.byteRange.end),i}function Us(n,e=null,t){const s={},i=e||n,r=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if(B(r)&&B(a)){var o;if((n.sn==="initSegment"||t)&&Yc((o=n.decryptdata)==null?void 0:o.method)){let l=Math.floor(r/16)*16;const c=Math.ceil(a/16)*16;s.decryptRange={start:r-l,end:a-l},l>=16&&(s.resetIV=!0,l=l-16),s.byteRange={start:l,end:c}}else s.byteRange={start:r,end:a}}return s}function Zr(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:q.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new rt(s)}function Yc(n){return n==="AES-128"||n==="AES-256"}class rt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Va extends Ge{constructor(e,t){super(e,t),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(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!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 or{constructor(e,t,s,i=0,r=-1,a=!1,o,l,c){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=ys(),this.buffering={audio:ys(),video:ys(),audiovideo:ys()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a,this.duration=o||0,this.decryptRange=c,this.iframe=l||!1}}function ys(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Jr={length:0,start:()=>0,end:()=>0};class X{static isBuffered(e,t){if(e){const s=X.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=X.getBuffered(e);return X.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=X.bufferedRanges(e);if(i.length)return X.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,l=t,c=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)l=u,c=d,a=c-t;else if(t+s<u){o=u;break}}return{len:a,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Jr}catch(t){return le.log("failed to get media.buffered",t),Jr}}}const Mi=/\{\$([a-zA-Z0-9-_]+)\}/g;function en(n){return Mi.lastIndex=0,Mi.test(n)}function lr(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(Mi,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function tn(n,e,t){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function Wc(n,e,t){const s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const qc=/^(\d+)x(\d+)$/,sn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class pe{constructor(e,t){typeof e=="string"&&(e=pe.parseAttrList(e,t)),ue(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=qc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(sn.lastIndex=0;(s=sn.exec(e))!==null;){const a=s[1].trim();let o=s[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let c=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))o=lr(t,o);else if(!c&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="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":le.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const jc="com.apple.hls.interstitial";function zc(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function Xc(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class Ka{constructor(e,t,s=0){var i;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=t?.tagAnchor||null,this.tagOrder=(i=t?.tagOrder)!=null?i:s,t){const r=t.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){le.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ue(new pe({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const r=t?.endDate||new Date(e["END-DATE"]);B(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(le.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(B(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===jc}get isValid(){return!!this.id&&!this._badValueForSameId&&B(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`:B(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 Ha=10;class Qc{constructor(e){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=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?B(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Ha}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.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 e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Gs(n,e){return n.length===e.length?!n.some((t,s)=>t!==e[s]):!1}function rn(n,e){return!n&&!e?!0:!n||!e?!1:Gs(n,e)}function Mt(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function cr(n){switch(n){case"AES-128":case"AES-256":return At.cbc;case"AES-256-CTR":return At.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function Fi(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function Zc(n){const e=Fi(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Ya(n){const e=function(s,i,r){const a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function Wa(n){const e=n.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),t=ir(a)):t=Zc(a)}}return t}const Vs=typeof self<"u"?self:void 0;var me={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},De={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Es(n){switch(n){case De.FAIRPLAY:return me.FAIRPLAY;case De.PLAYREADY:return me.PLAYREADY;case De.WIDEVINE:return me.WIDEVINE;case De.CLEARKEY:return me.CLEARKEY}}var qa={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function li(n){switch(n){case me.FAIRPLAY:return De.FAIRPLAY;case me.PLAYREADY:return De.PLAYREADY;case me.WIDEVINE:return De.WIDEVINE;case me.CLEARKEY:return De.CLEARKEY}}function Gt(n){const{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[me.FAIRPLAY,me.WIDEVINE,me.PLAYREADY,me.CLEARKEY].filter(i=>!!e[i]):[];return!s[me.WIDEVINE]&&t&&s.push(me.WIDEVINE),s}const ja=(function(n){return Vs!=null&&(n=Vs.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Jc(n,e,t,s){let i;switch(n){case me.FAIRPLAY:i=["cenc","sinf"];break;case me.WIDEVINE:case me.PLAYREADY:i=["cenc"];break;case me.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return eh(i,e,t,s)}function eh(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function th(n){var e;return!!n&&(n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function hr(n){const e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=Ze(e),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=ir(o).subarray(0,16);return Ya(l),l}}return null}let kt={};class gt{static clearKeyUriToKeyIdMap(){kt={}}static setKeyIdForUri(e,t){kt[e]=t}static addKeyIdForUri(e){const t=Object.keys(kt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),kt[e]=s,s}constructor(e,t,s,i=[1],r=null,a){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=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Mt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(ya(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Gs(e.keyFormatVersions,this.keyFormatVersions)&&rn(e.iv,this.iv)&&rn(e.keyId,this.keyId)}isSupported(){if(this.method){if(Mt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case De.FAIRPLAY:case De.WIDEVINE:case De.PLAYREADY:case De.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var s;if(!this.encrypted||!this.uri)return null;if(Mt(this.method)){let a=this.iv;return a||(typeof e!="number"&&(le.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=ih(e)),new gt(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=kt[this.uri];if(a&&!Gs(this.keyId,a)&>.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Wa(this.uri);if(i)switch(this.keyFormat){case De.WIDEVINE:if(this.pssh=i,!this.keyId){const a=_a(i.buffer).filter(o=>o.systemId===qa.WIDEVINE);if(a.length){var r;const o=a[0];this.keyId=(r=o.kids)!=null&&r.length?o.kids[0]:null}}this.keyId||(this.keyId=nn(t));break;case De.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=rc(a,null,i),this.keyId=hr(i);break}default:{let a=i.subarray(0,16);if(a.length!==16){const o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((s=this.keyId)==null?void 0:s.byteLength)!==16){let a;a=sh(t),a||(a=nn(t),a||(a=kt[this.uri])),a&&(this.keyId=a,gt.setKeyIdForUri(this.uri,a))}return this}}function sh(n){const e=n?.[De.WIDEVINE];return e?e.keyId:null}function nn(n){const e=n?.[De.PLAYREADY];if(e){const t=Wa(e.uri);if(t)return hr(t)}return null}function ih(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const an=/#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,on=/#EXT-X-MEDIA:(.*)/g,rh=/^#EXT(?:INF|-X-TARGETDURATION):/m,ci=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),nh=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 ot{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Zi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return rh.test(e)}static parseMasterPlaylist(e,t){const s=en(e),i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(an.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=an.exec(e))!=null;)if(a[1]){const l=new pe(a[1],i),c=ln(l,a[2],t,i,r);c&&i.levels.push(c)}else if(a[3]){const l=a[3],c=a[4];switch(l){case"I-FRAME-STREAM-INF":{const h=new pe(c,i),u=ln(h,h.URI,t,i,r,!0);u&&i.iframeVariants.push(u)}break;case"SESSION-DATA":{const h=new pe(c,i),u=h["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=h);break}case"SESSION-KEY":{const h=cn(c,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):le.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const h=new pe(c,i);tn(i,h,t)}break}case"CONTENT-STEERING":{const h=new pe(c,i);i.contentSteering={uri:ot.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=hn(c);break}}}const o=r.length>0&&r.length<i.levels.length;return i.levels=o?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},a=s.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(on.lastIndex=0;(i=on.exec(e))!==null;){const c=new pe(i[1],s),h=c.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const f=c.LANGUAGE,g=c["ASSOC-LANGUAGE"],m=c.CHANNELS,y=c.CHARACTERISTICS,E=c["INSTREAM-ID"],S={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?ot.resolve(c.URI,t):""};if(g&&(S.assocLang=g),m&&(S.channels=m),y&&(S.characteristics=y),E&&(S.instreamId=E),u!=null&&u.length){const T=ot.findGroup(u,S.groupId)||u[0];dn(S,T,"audioCodec"),dn(S,T,"textCodec")}d.push(S)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){var o;const l={url:t},c=new Qc(t),h=c.fragments,u=[];let d=null,f=0,g=0,m=0,y=0,E=0,S=null,T=new us(i,l),v,x,A,I=-1,b=!1,_=null,L;if(ci.lastIndex=0,c.m3u8=e,c.hasVariableRefs=en(e),((o=ci.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(v=ci.exec(e))!==null;){b&&(b=!1,T=new us(i,l),T.playlistOffset=m,T.setStart(m),T.sn=f,T.cc=y,E&&(T.bitrate=E),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),_&&(T.setByteRange(_),_=null)));const $=v[1];if($){T.duration=parseFloat($);const k=(" "+v[2]).slice(1);T.title=k||null,T.tagList.push(k?["INF",$,k]:["INF",$])}else if(v[3]){if(B(T.duration)){var P;T.playlistOffset=m,T.setStart(m),A&&gn(T,A,c),T.sn=f,T.level=s,T.cc=y;const k=(" "+v[3]).slice(1);T.relurl=lr(c,k),Ni(T,S,u),S=T,m+=T.duration,f++,g=0;const w=T.byteRange;if(w.length===2&&(T.bitrate=(w[1]-w[0])*8/T.duration|0),c.iframesOnly&&w[0]&&((P=d)==null?void 0:P.cc)!==y){const O=new us(i,l);O.relurl=T.relurl,O.setByteRange(`${Math.min(w[0],1316)}@0`),O.level=s,O.sn="initSegment",A&&(O.levelkeys=A,A.identity&&(O._decryptdata=A.identity.getDecryptData(0))),d=O,T.initSegment=d}h.push(T),b=!0}}else{if(v=v[0].match(nh),!v){le.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<v.length&&v[x]===void 0;x++);const k=(" "+v[x]).slice(1),w=(" "+v[x+1]).slice(1),O=v[x+2]?(" "+v[x+2]).slice(1):null;switch(k){case"BYTERANGE":S?T.setByteRange(w,S):T.setByteRange(w);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=w,T.tagList.push(["PROGRAM-DATE-TIME",w]),I===-1&&(I=h.length);break;case"PLAYLIST-TYPE":c.type&&ut(c,k,v),c.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?ut(c,k,v):S!==null&&lh(c,k,v),c.startSN=parseInt(w),f=c.startSN+c.skippedSegments;break;case"SKIP":{c.skippedSegments&&ut(c,k,v);const N=new pe(w,c),Y=N.decimalInteger("SKIPPED-SEGMENTS");if(B(Y)){c.skippedSegments+=Y;for(let U=Y;U--;)h.push(null);f+=Y}const M=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");M&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(M.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&ut(c,k,v),c.targetduration=Math.max(parseInt(w),1);break;case"VERSION":c.version!==null&&ut(c,k,v),c.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":c.iframesOnly=!0;break;case"ENDLIST":c.live||ut(c,k,v),c.live=!1;break;case"#":(w||O)&&T.tagList.push(O?[w,O]:[w]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([k]);break;case"BITRATE":T.tagList.push([k,w]),E=parseInt(w)*1e3,B(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const N=new pe(w,c),Y=new Ka(N,c.dateRanges[N.ID],c.dateRangeTagCount);c.dateRangeTagCount++,Y.isValid||c.skippedSegments?c.dateRanges[Y.id]=Y:le.log(`Ignoring invalid DATERANGE tag: ${Y.invalidReason}: ${w}`),T.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const N=new pe(w,c);"IMPORT"in N?Wc(c,N,a):tn(c,N,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0&&ut(c,k,v),c.startCC=y=parseInt(w),h.forEach(N=>N&&(N.cc=y));break;case"KEY":{const N=cn(w,t,c);if(N.isSupported()){if(N.method==="NONE"){A=void 0;break}A||(A={});const Y=A[N.keyFormat];Y!=null&&Y.matches(N)||(Y&&(A=ue({},A)),A[N.keyFormat]=N)}else le.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":c.startTimeOffset=hn(w);break;case"MAP":{const N=new pe(w,c);if(T.duration){const Y=new us(i,l);fn(Y,N,s,A),d=Y,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const Y=T.byteRangeEndOffset;if(Y){const M=T.byteRangeStartOffset;_=`${Y-M}@${M}`}else _=null;fn(T,N,s,A),d=T,b=!0}d.cc=y;break}case"SERVER-CONTROL":{L&&ut(c,k,v),L=new pe(w),c.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),c.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&ut(c,k,v);const N=new pe(w);c.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=c.partList;N||(N=c.partList=[]);const Y=g>0?N[N.length-1]:void 0,M=g++,U=new pe(w,c),ee=new dl(U,T,l,M,Y);N.push(ee),T.duration+=ee.duration;break}case"PRELOAD-HINT":{const N=new pe(w,c);c.preloadHint=N;break}case"RENDITION-REPORT":{const N=new pe(w,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(N);break}default:le.warn(`line parsed but not handled: ${v}`);break}}}S&&!S.relurl?(h.pop(),m-=S.duration,c.partList&&(c.fragmentHint=S)):c.partList&&(Ni(T,S,u),T.cc=y,c.fragmentHint=T,A&&gn(T,A,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const C=h.length,F=h[0],V=h[C-1];if(m+=c.skippedSegments*c.targetduration,m>0&&C&&V){c.averagetargetduration=m/C;const $=V.sn;c.endSN=$!=="initSegment"?$:0,c.live||(V.endList=!0),I>0&&(oh(h,I,I>C-1?T:null),F&&u.unshift(F))}return c.fragmentHint&&(m+=c.fragmentHint.duration),c.totalduration=m,u.length&&c.dateRangeTagCount&&F&&za(u,c),c.endCC=y,c}}function ln(n,e,t,s,i,r){var a;if(e===void 0)return null;const o=lr(s,e),l={attrs:n,bitrate:n.decimalInteger("BANDWIDTH")||n.decimalInteger("AVERAGE-BANDWIDTH"),name:n.NAME,url:ot.resolve(o,t)},c=n.decimalResolution("RESOLUTION");c&&(l.width=c.width,l.height=c.height),un(n.CODECS,l);const h=n["SUPPLEMENTAL-CODECS"];return h&&(l.supplemental={},un(h,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||i.push(l),r&&(l.iframes=!0),l}function za(n,e){let t=n.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];n.push(o),t++}else return;const s=n[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const l=e.dateRanges[r[o]],c=l.startDate.getTime();l.tagAnchor=s.ref;for(let h=t;h--;){var a;if(((a=n[h])==null?void 0:a.sn)<e.startSN)break;const u=ah(e,c,n,h,i);if(u){l.tagAnchor=u.ref;break}}}}function ah(n,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var a;const l=(((a=t[s+1])==null?void 0:a.start)||i)-r.start;if(e<=o+l*1e3){const c=r.sn-n.startSN,h=n.fragments;if(c>=0&&c<h.length){if(h.length>t.length){const u=t[s+1]||h[h.length-1],d=Math.min(u.sn-n.startSN,h.length-1);for(let f=d;f>c;f--){const g=h[f].programDateTime;if(e>=g&&e<g+h[f].duration*1e3)return h[f]}}return h[c]}}}}return null}function cn(n,e,t){var s,i;const r=new pe(n,t),a=(s=r.METHOD)!=null?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!l&&le.error(`Invalid IV: ${r.IV}`);const u=o?ot.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new gt(a,u,h,d,l,r.KEYID)}function hn(n){const t=new pe(n).decimalFloatingPoint("TIME-OFFSET");return B(t)?t:null}function un(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text","image"].forEach(s=>{const i=t.filter(r=>rr(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function dn(n,e,t){const s=e[t];s&&(n[t]=s)}function oh(n,e,t){if(t||(t=n[e]),!!t)for(let s=e;s--;){const i=n[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Ni(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function fn(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function gn(n,e,t){n.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}function ut(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function lh(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function hi(n,e){const t=e.startPTS;if(B(t)){let s=0,i;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.setStart(n.start+(n.minEndPTS-n.start)):e.setStart(n.start+n.duration):e.setStart(Math.max(n.start-e.duration,0))}function Xa(n,e,t,s,i,r,a,o){s-t<=0&&(o.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,h=s;const u=e.startPTS,d=e.endPTS;if(B(u)){const S=Math.abs(u-t);n&&S>n.totalduration?o.warn(`media timestamps and playlist times differ by ${S}s for level ${e.level} ${n.url}`):B(e.deltaPTS)?e.deltaPTS=Math.max(S,e.deltaPTS):e.deltaPTS=S,c=Math.max(t,u),t=Math.min(t,u),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,h=Math.min(s,d),s=Math.max(s,d),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const f=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=h,e.endDTS=r;const g=e.sn;if(!n||g<n.startSN||g>n.endSN)return 0;let m;const y=g-n.startSN,E=n.fragments;for(E[y]=e,m=y;m>0;m--)hi(E[m],E[m-1]);for(m=y;m<E.length-1;m++)hi(E[m],E[m+1]);return n.fragmentHint&&hi(E[E.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,f}function ch(n,e,t){if(n===e)return;let s=null;const i=n.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;dh(n,e,(h,u,d,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const g=h.cc-u.cc;for(let m=d;m<f.length;m++)f[m].cc+=g;e.endCC=f[f.length-1].cc}B(h.startPTS)&&B(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=hh(n.dateRanges,e,t));const h=n.fragments.filter(u=>u.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Ni(o[u],o[u-1],h);za(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const h=Ja(n,e.startSN-1);e.startCC=(l=h?.cc)!=null?l:a[0].cc}if(uh(n.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats,u.gap=h.gap||u.gap}),r){const h=e.iframesOnly&&r.type===H.MAIN;Xa(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,h,t)}else Qa(n,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const h=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=h),e.driftEndTime=c,e.driftEnd=h}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function hh(n,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ue({},n);i&&i.forEach(l=>{delete r[l]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(l=>{const c=r[l],h=new Ka(s[l].attr,c);h.isValid?(r[l]=h,c||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${fe(s[l].attr)}"`)}),r):s}function uh(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<r;i++){const a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function dh(n,e,t){var s;const i=e.skippedSegments,r=Math.max(n.startSN,e.startSN)-e.startSN,a=(n.fragmentHint?1:0)+(i?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,o=e.startSN-n.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=(s=n.fragmentHint)!=null&&s.duration?n.fragments.concat(n.fragmentHint):n.fragments;for(let h=r;h<=a;h++){const u=c[o+h];let d=l[h];if(i&&!d&&u&&(d=e.fragments[h]=u),u&&d){t(u,d,h,l);const f=u.relurl,g=d.relurl;if(f&&gh(f,g)){e.playlistParsingError=mn(`media sequence mismatch ${d.sn}:`,n,e,u,d);return}else if(u.cc!==d.cc){e.playlistParsingError=mn(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,n,e,u,d);return}}}}function mn(n,e,t,s,i){return new Error(`${n} ${i.url}
|
|
12
|
+
Playlist starting @${e.startSN}
|
|
13
|
+
${e.m3u8}
|
|
14
|
+
|
|
15
|
+
Playlist starting @${t.startSN}
|
|
16
|
+
${t.m3u8}`)}function Qa(n,e,t=!0,s){const i=e.startSN+e.skippedSegments-n.startSN,r=n.fragments,a=i>=0;let o=0;if(a&&i<r.length)o=r[i].start,s?.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===n.endSN+1)o=n.fragmentEnd,s?.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=n.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=n.fragmentStart,s?.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return fh(e,o),o}function fh(n,e){if(e){const t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].addStart(e);n.fragmentHint&&n.fragmentHint.addStart(e)}}function Za(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const s=n.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ja(n,e,t){var s;if(!n)return null;let i=n.fragments[e-n.startSN];return i||(i=n.fragmentHint,((s=i)==null?void 0:s.sn)===e)?i:t&&e<n.startSN&&t.sn===e?t:null}function pn(n,e,t){return n?eo(n.partList,e,t):null}function eo(n,e,t){if(n)for(let s=n.length;s--;){const i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function to(n){n.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function gh(n,e){return n!==e&&e?yn(n)!==yn(e):!1}function yn(n){return n.replace(/\?[^?]*$/,"")}function zt(n,e){for(let s=0,i=n.length;s<i;s++){var t;if(((t=n[s])==null?void 0:t.cc)===e)return n[s]}return null}function mh(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function En(n,e){const t=n.start+e;n.setStart(t)}function so(n,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)En(t[s],n);e.fragmentHint&&En(e.fragmentHint,n),e.alignedSliding=!0}function Ks(n,e,t){n&&(ph(e,n,t),e.alignedSliding||yh(e,n,t),!e.alignedSliding&&!e.skippedSegments&&Qa(n,e,!1,t))}function ph(n,e,t){if(!mh(e,n))return;const s=Math.min(e.endCC,n.endCC),i=zt(e.fragments,s),r=zt(n.fragments,s);if(!i||!r)return;const a=i.start-r.start;t.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),so(a,n)}function yh(n,e,t){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const s=n.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,a;const o=Math.min(e.endCC,n.endCC);e.startCC<o&&n.startCC<o&&(r=zt(i,o),a=zt(s,o)),(!r||!a)&&(r=i[Math.floor(i.length/2)]||i.filter(d=>!!d)[0],a=zt(s,r.cc)||s[Math.floor(s.length/2)]);const l=r.programDateTime,c=a.programDateTime;if(!l||!c)return;const h=(c-l)/1e3;if(Math.abs(h)>Math.max(60,n.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(h)} > ${n.totalduration})`);return}const u=h-(a.start-r.start);t.log(`Aligning playlists using PDT (diff: ${u})`),so(u,n)}function he(n,e,t){ce(n,e,t),n.addEventListener(e,t)}function ce(n,e,t){n.removeEventListener(e,t)}function Hs(n){let e="";const t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}const D={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ur extends Va{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=D.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:a,fragCurrent:o,media:l,mediaBuffer:c,state:h}=this,u=l?l.currentTime:0,d=X.bufferInfo(c||l,u,a.maxBufferHole),f=d.len;if(this.log(`Media seeking to ${u}, state: ${h}, ${f?"in":"out of"} buffer`),this.state===D.ENDED)this.resetLoadingState();else if(o){const m=a.maxFragLookUpTolerance,y=o.start-m,E=o.start+o.duration+m;if(!f||E<d.start||y>d.end){const S=u<y,T=u>E;(S||T)&&(o.loader&&(T||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${S?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const m=this.lastCurrentTime;if(u>m&&(this.lastCurrentTime=u),!this.loadingParts){const y=Math.max(d.end,u),E=this.shouldLoadParts(this.getLevelDetails(),y);E&&(this.log(`LL-Part loading ON after seeking to ${u} with buffer @${y}`),this.loadingParts=E)}}const g=!X.isBuffered(l,u);(!this.hls.hasEnoughToStart||g)&&(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,g&&(this.startPosition=u)),f<1&&this.state===D.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Xr(e.config),this.initFragmentLoader=new Xr(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ar(e.config)}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===D.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=D.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){const s=this.getLevelDetails();return s!=null&&s.live?(this.hls.liveSyncPosition||s.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=X.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const h=l[l.length-1];return X.isBuffered(this.media,h.start+h.duration/2)}const c=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(c.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;he(s,"seeking",this.onMediaSeeking),he(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===D.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ce(i,"seeking",this.onMediaSeeking),ce(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=D.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(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}const o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} chunk: ${o}`),this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===D.FRAG_LOADING||!this.fragCurrent&&a===D.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=D.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(p.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===D.STOPPED||this.state===D.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===ye.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===ye.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=this.fragmentTracker,s=e.fragments[e.fragments.length-1];if(s.endList&&!t.isEndListAppended(this.playlistType)){const i=t.getPartialFragment(s.end);i&&(t.removeFragment(i),t.fragBuffered(s,!0))}t.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(p.BUFFER_FLUSHING,i)}_loadInitSegment(e){const{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(s=>{var i;const r=s.frag;if(!this.levels||!_i(r,(i=this.fragCurrent)==null?void 0:i.initSegment))throw new rt({type:q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return s}).then(s=>{const{frag:i,payload:r}=s,a=i.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&Mt(a.method)){const o=self.performance.now(),{decryptRange:l}=Us(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,cr(a.method),l).catch(c=>{throw t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:i}),this.fragmentLoader.abort(),c}).then(c=>{const h=self.performance.now();return t.trigger(p.FRAG_DECRYPTED,{frag:i,part:null,payload:c,stats:{tstart:o,tdecrypt:h}}),s.payload=c,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)})}completeInitSegmentLoad(e){const t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){const{initSegment:t}=e;if(!this.bitrateTest&&Ee(e)&&t&&!t.data){var s;return(t.encrypted&&!((s=t.decryptdata)!=null&&s.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(r=>{throw this.state===D.STOPPED||this.state===D.ERROR||("data"in r&&(r.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(r)),this.resetFragmentLoading(e)),r})}}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(p.ERROR,{type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!_i(e,t)}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Hs(X.getBuffered(s)):"(detached)"})`),Ee(e)){var i;if(e.type!==H.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=D.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(t||this.fragmentTracker.getState(e)!==ye.PARTIAL)&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,e.stats.retry=0)}this.state=D.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const s=e.frag,{part:i,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),{decryptRange:o}=Us(s,i),l=new or(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a,s.duration,this.iframesOnly,o);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,s){var i;let r=null;return e.encrypted&&!((i=e.decryptdata)!=null&&i.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=D.KEY_LOADING,r=this.keyLoader.load(e,s).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(p.KEY_LOADED,a),this.state===D.KEY_LOADING&&(this.state=D.IDLE),a}),this.hls.trigger(p.KEY_LOADING,{frag:e})):e.encrypted||(r=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),r}_doFragLoad(e,t,s=null,i){this.fragCurrent=e;const r=t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const a=this.fragPrevious;if(!Yt(e,a)){const f=this.shouldLoadParts(t.details,e.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=f)}if(s=Math.max(e.start,s||0),this.loadingParts){const f=r.partList;if(f&&i){s>r.fragmentEnd&&r.fragmentHint&&(e=r.fragmentHint);const g=this.getNextPart(f,e,s);if(g>-1){const m=f[g];if(e=this.fragCurrent=m.fragment,!Yt(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,m)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(m,t.details))return Promise.resolve(null);const y=this.loadKeyFor(e,r);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${f.length-1}) of ${this.fragInfo(e,!1,m)} cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${s}${m.byteRange.length?` range:${m.byteRange.join("-")}`:""}`),this.nextLoadPosition=m.start+m.duration,this.state=D.FRAG_LOADING;let E;const S=this.loadInitSegmentIfNeeded(e);if(y||S){const T=!!y;E=Promise.all([y,S]).then(([v])=>T&&(!v||this.fragContextChanged(v.frag))?null:this.doFragPartsLoad(e,m,t,i)).catch(v=>this.handleFragLoadError(v))}else E=this.doFragPartsLoad(e,m,t,i).catch(T=>this.handleFragLoadError(T));return this.hls.trigger(p.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):E}else if(!e.url||this.loadedEndOfParts(f,s))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${e.sn} loaded parts: ${(o=r.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);const l=this.loadInitSegmentIfNeeded(e),c=this.loadKeyFor(e,r,l);if(this.fragContextChanged(e)){var h;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(h=this.fragCurrent)==null?void 0:h.relurl}`),l?.catch(()=>null),c?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),B(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=D.FRAG_LOADING;const u=this.config.progressive&&e.type!==H.SUBTITLE;let d;return u&&c?d=c.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,i,l)).catch(f=>this.handleFragLoadError(f)):d=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,u?i:void 0,u?l:void 0),c,l]).then(([f])=>(!u&&i&&i(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([d,l]).then(([f])=>f)}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;const l=[],c=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{l[u.index]=d;const f=d.part;this.hls.trigger(p.FRAG_LOADED,d);const g=pn(s.details,e.sn,u.index+1)||eo(c,e.sn,u.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:l})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===q.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==D.PARSING){!this.fragCurrent&&this.state!==D.STOPPED&&this.state!==D.ERROR&&(this.state=D.IDLE);return}const{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);const o=this.getLevelDetails(),c=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=c),this.updateLevelTiming(s,i,r,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var s;const i=e.partList[0],r=i.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=r&&this.playhead>i.start-i.fragment.duration)return!0}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],l=o.details,c=a>-1?pn(l,r,a):null,h=c?c.fragment:Ja(l,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:c,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==D.PARSING)return;Ee(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);const{data1:a,data2:o}=e;let l=a;if(o&&(l=He(a,o)),!l.length)return;const c=this.initPTS[t.cc],h=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:l};if(this.hls.trigger(p.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!X.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=X.bufferInfo(t,s,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.playhead,a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){const r=X.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-t,i);return X.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){const i=e.nextStart;if(i&&s.start>i){const r=e.buffered;if(r){let a=e.len;const o=e.bufferedIndex;for(let l=r.length-1;l>o;l--)r[l].start<s.start&&(a+=r[l].end-r[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t/2),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e){const t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,a=t.fragmentStart,o=r.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var c;l=this.getInitialLiveFragment(t);const d=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,m=((c=l)==null?void 0:c.start)||0;let y,E;if(f!==-1&&f>=a?(y=f,E=f===d?"config":"next load start"):g?(y=g,E="live edge"):(y=e,E="buffer pos"),y<m&&(y=m,E="live frag start"),y<a&&(y=a,E="playlist start"),this.startPosition!=y||this.nextLoadPosition!=y){const T=t.live&&!this.filterReplacedPrimary(l,t)?-1:y;this.log(`Setting startPosition to ${T} next load ${y} ${f===-1?"":`(from ${d}) `}based on ${E}. live edge: ${g} live frag start: ${m} playlist start: ${a} buffer pos: ${e}`),this.startPosition=T,this.nextLoadPosition=y}}}else e<=a&&(l=s[0]);if(!l){const u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(l,t);return!h&&l&&(h=Ua(t,l.sn),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const s=this.fragmentTracker.getState(e);return!!(s===ye.OK||s===ye.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,s,i,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Ys(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Ys(this.config)&&("type"in e?e:e.fragment).type!==H.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const r=i.event;if(r){if(!r.appendInPlace&&(Math.abs(e.start-i.start)>1||i.start===0))return null}else if(e.end<=i.start&&t?.live===!1||e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}if(io(e,s?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let l=0,c=e.length;l<c;l++){const h=e[l];if(a=a&&!h.independent,i>-1&&s<h.start)break;const u=h.loaded||h.gap;u?i=-1:(r||(h.independent||a)&&h.fragment===t)&&(i=l),r=u&&!h.gap}const o=e[i];return o&&o.fragment!==t&&this.log(`Need buffer at ${s} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(i=wc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=$a(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:c}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&l);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),r&&this.fragmentTracker.getState(r)===ye.NOT_LOADED&&(r=null);let d;if(e<t){var f;const m=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;d=Bt(r,a,e,m)}else d=a[a.length-1];if(d){const g=d.sn-s.startSN,m=this.fragmentTracker.getState(d);if((m===ye.OK||m===ye.PARTIAL&&d.gap)&&(r=d),Yt(d,r)&&(!u||h[0].fragment.sn>d.sn||!s.live)){const y=a[g+1];d.sn<o&&this.fragmentTracker.getState(y)!==ye.OK?d=y:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,a=!t,o=e.alignedSliding&&B(r);if(a||!o&&!r){Ks(s,e,this);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),l}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;if(a!==null&&B(a))s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(e.live){const o=this.hls.liveSyncPosition;s=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;const s=(t=this.media)==null?void 0:t.currentTime;return B(s)?s:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==H.MAIN)return!1;const t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ee(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==D.FRAG_LOADING_WAITING_RETRY)&&(this.state=D.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const S=this.getCurrentContext(t.chunkMeta);S&&(t.frag=S.frag)}const{frag:s,part:i}=t;if(!s||!this.levels||s.type!==e)return;if(this.fragContextChanged(s)){var r;this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${(r=this.fragCurrent)==null?void 0:r.relurl}`);return}const a=t.details===R.FRAG_GAP;a&&this.fragmentTracker.addAsGap(s);const o=t.errorAction;if(!o){this.state=D.ERROR;return}const{action:l,flags:c,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&l===Re.RetryRequest,g=d&&!o.resolved&&c&Le.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,y=m?.live;if(!f&&g&&Ee(s)&&y&&s.sn<m.endSN&&!ca(t))this.resetFragmentErrors(e),i?i.gap=!0:this.treatAsGap(s),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var E;const S=Jt((E=t.response)==null?void 0:E.code),T=er(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=D.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,S){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${T}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!a&&l!==Re.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else l===Re.SendAlternateToPenaltyBox?this.state=D.WAITING_LEVEL:this.state=D.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Jt(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=D.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===D.PARSING||this.state===D.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const a=!r;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===H.AUDIO?s:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===H.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==D.STOPPED&&(this.state=D.IDLE)}afterBufferFlushed(e,t){if(!e)return;const s=X.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,this.playlistType),this.state===D.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==D.STOPPED&&(this.state=D.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((u,d)=>{const f=e.elementaryStreams[d];if(f){const g=f.endPTS-f.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${g})`),u||!1;const m=i.partial?0:Xa(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:r,level:s,drift:m,type:d,frag:e,start:f.startPTS,end:f.endPTS}),!0}return u},!1)){var o,l,c,h;const u=((o=this.transmuxer)==null?void 0:o.error)===null,d=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((c=(h=this.levels)==null?void 0:h.length)!=null?c:0)>1;if((s.fragmentError===0||u&&(s.fragmentError<2||e.endList)||d&&f)&&this.treatAsGap(e,s),u){const g=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=D.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN}-${(r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;const s=(t=e.loader)==null?void 0:t.stats;if(!s)return!1;const i=s.loading.first>0,a=(s.total-s.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let s=0;const{hls:i,media:r,config:a,levels:o,playlistType:l}=this,c=this.getLevelDetails();if(r&&!r.paused&&o){var h;const f=l===H.AUDIO?wa(e.audioCodec,128e3):e.maxBitrate,g=1+i.ttfbEstimate/1e3,m=i.bandwidthEstimate*a.abrBandWidthUpFactor,y=c&&(this.loadingParts?c.partTarget:c.averagetargetduration)||((h=this.fragCurrent)==null?void 0:h.duration)||6;s=g+f*y/m,e.details||(s+=g)}const u=this.playhead,d=!(c!=null&&c.live)||t.end-u>s*1.5;return{fetchdelay:s,okToFlushForwardBuffer:d}}scheduleTrackSwitch(e,t,s){const{media:i,playlistType:r}=this;if(!i||!e)return;const a=s?this.getBufferedFrag(this.playhead+t):null;if(a){const l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();const c=l.maxStartPTS?l.maxStartPTS:l.start,h=l.duration,u=Math.max(a.end,c+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>u)return;const f=r===H.MAIN?null:"audio";this.flushMainBuffer(u,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:e,playlistType:t}=this;if(!e)return;const s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){const i=t===H.AUDIO;this.flushMainBuffer(0,s.start-(i?0:1),i?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case D.KEY_LOADING:case D.FRAG_LOADING:case D.FRAG_LOADING_WAITING_RETRY:case D.PARSING:case D.PARSED:this.state=D.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(X.isBuffered(e,s)?t=this.getAppendedFrag(s):X.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t&&(this.backtrackFragment=void 0,!Yt(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:e,media:t,hls:s,config:i,playlistType:r}=this;if(t!=null&&t.readyState&&e&&s&&i){const a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,r);if(!o)return;const l=r===H.AUDIO?s.nextAudioTrack:s.nextLoadLevel,c=e[l],{fetchdelay:h,okToFlushForwardBuffer:u}=this.calculateOptimalSwitchPoint(c,o);this.scheduleTrackSwitch(o,h,u)}this.tickImmediate()}}function io(n,e,t){if(e)for(let s=e.length;s--;){const i=e[s].interstitial,r=i.startTime,a=Math.min(r+i.duration,i.resumeTime);if(i.appendInPlace&&(n.start>=r&&n.end<=a||t>n.start&&n.end>r&&n.start<a))return!0}return!1}function Ys(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}class ro{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Eh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Eh(n,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<n.length;i++){const r=n[i];t.set(r,s),s+=r.length}return t}var ui={exports:{}},Tn;function Th(){return Tn||(Tn=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||l,d),g=t?t+c:c;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 a(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},o.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,f,g){var m=t?t+c:c;if(!this._events[m])return!1;var y=this._events[m],E=arguments.length,S,T;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,f),!0;case 6:return y.fn.call(y.context,h,u,d,f,g),!0}for(T=1,S=new Array(E-1);T<E;T++)S[T-1]=arguments[T];y.fn.apply(y.context,S)}else{var v=y.length,x;for(T=0;T<v;T++)switch(y[T].once&&this.removeListener(c,y[T].fn,void 0,!0),E){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,u);break;case 4:y[T].fn.call(y[T].context,h,u,d);break;default:if(!S)for(x=1,S=new Array(E-1);x<E;x++)S[x-1]=arguments[x];y[T].fn.apply(y[T].context,S)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&a(this,f);else{for(var m=0,y=[],E=g.length;m<E;m++)(g[m].fn!==h||d&&!g[m].once||u&&g[m].context!==u)&&y.push(g[m]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(ui)),ui.exports}var Sh=Th(),dr=hl(Sh);const as="1.7.2",$t={};function vh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function xh(){const n=$t[as];if(n)return n.clientCount++,n;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return $t[as]=i,i}function Ah(n){const e=$t[n];if(e)return e.clientCount++,e;const t=new self.URL(n,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return $t[n]=i,i}function Ih(n){const e=$t[n||as];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete $t[n||as],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Lh(n,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const y=new Error(`invalid ADTS sampling index:${a}`);n.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:y,reason:y.message});return}const o=(r>>6&3)+1,l=e[t+3]>>6&3|(r&1)<<2,c=i[a];let h=a;(o===5||o===29)&&(h-=3);let u;const d=(h&14)>>1,f=(h&1)<<7|l<<3;let g=0;if(o===1&&a>=6){g=5;const y=a-3;u=[g<<3|d,f|(y&14)>>1,(y&1)<<7|8,0]}else u=[o<<3|d,f];const m="mp4a.40."+(g||o);return le.log(`manifest codec:${s}, parsed codec:${m}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a} esds config:[${u.join(",")}])`),{config:u,samplerate:c,channelCount:l,codec:m,parsedCodec:m,manifestCodec:s}}function no(n,e){return n[e]===255&&(n[e+1]&246)===240}function ao(n,e){return n[e+1]&1?7:9}function fr(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function Rh(n,e){return e+5<n.length}function Ws(n,e){return e+1<n.length&&no(n,e)}function bh(n,e){return Rh(n,e)&&no(n,e)&&fr(n,e)<=n.length-e}function _h(n,e){if(Ws(n,e)){const t=ao(n,e);if(e+t>=n.length)return!1;const s=fr(n,e);if(s<=t)return!1;const i=e+s;return i===n.length||Ws(n,i)}return!1}function oo(n,e,t,s,i){if(!n.samplerate){const r=Lh(e,t,s,i);if(!r)return;ue(n,r)}}function lo(n){return 1024*9e4/n}function Dh(n,e){const t=ao(n,e);if(e+t<=n.length){const s=fr(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function co(n,e,t,s,i){const r=lo(n.samplerate),a=s+i*r,o=Dh(e,t);let l;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const m={unit:l,pts:a};return g||n.samples.push(m),{sample:m,length:f,missing:g}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let Oe=(function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n})({});function nt(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class gr{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(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=He(this.cachedData,e),this.cachedData=null);let s=es(e,0),i=s?s.length:0,r;const a=this._audioTrack,o=this._id3Track,l=s?sr(s):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&B(l))&&(this.basePTS=Ph(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Oe.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=c}else Dl(e,i)?(s=es(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Oe.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===c&&r!==c){const h=e.slice(r);this.cachedData?this.cachedData=He(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:nt(),id3Track:o,textTrack:nt()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:nt(),id3Track:this._id3Track,textTrack:nt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Ph=(n,e,t)=>{if(B(n))return n*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},Ch=[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],kh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Oh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],wh=[0,1,1,4];function ho(n,e,t,s,i){if(t+24>e.length)return;const r=uo(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function uo(n,e){const t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const a=n[e+2]>>1&1,o=n[e+3]>>6,l=t===3?3-s:s===3?3:4,c=Ch[l*14+i-1]*1e3,u=kh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Oh[t][s],g=wh[s],m=f*8*g,y=Math.floor(f*c/u+a)*g,E=qt();return E&&E<=87&&s===2&&c>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:m}}}function mr(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function fo(n,e){return e+1<n.length&&mr(n,e)}function Mh(n,e){return mr(n,e)&&4<=n.length-e}function go(n,e){if(e+1<n.length&&mr(n,e)){const s=uo(n,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===n.length||fo(n,r)}return!1}class mo{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new ar(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,At.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const a=ba(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}}class Fh extends gr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=es(e,0);let i=s?.length||0;if(go(e,i))return!1;for(let r=e.length;i<r;i++)if(_h(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return bh(e,t)}appendFrame(e,t,s){oo(e,this.observer,t,s,e.manifestCodec);const i=co(e,t,s,this.basePTS,this.frameIndex);if(i?.missing===0)return i}demuxSampleAes(e,t,s){const i=this.demux(e,s),r=this.sampleAes=new mo(this.observer,this.config,t);return new Promise(a=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{a(i)})})}}const po=(n,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,i[0]=(a[0]&r[0])>>l,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Nh extends gr{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=yo(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=es(e,0);if(!t)return!1;const s=t.length;if(e[s]===11&&e[s+1]===119&&sr(t)!==void 0){if(po(e,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function yo(n,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,m=[2,1,2,3,3,4,4,5][u]+f,y=e[t+5]>>3,E=e[t+5]&7,S=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),T=1536/o*9e4,v=s+i*T,x=e.subarray(t,t+h);return n.config=S,n.channelCount=m,n.samplerate=o,n.samples.push({unit:x,pts:v}),h}class Bh extends gr{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=es(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&sr(t)!==void 0&&po(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(go(e,s))return le.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Mh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return ho(e,t,s,this.basePTS,this.frameIndex)}}const $h=/\/emsg[-/]ID3/i;class Uh{constructor(e,t,s,i=le){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=t,this.logger=i}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=nt("video",1),a=this.audioTrack=nt("audio",1),o=this.txtTrack=nt("text",1);if(this.id3Track=nt("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=this.initData=xa(e);if(l.video){const{id:c,timescale:h,codec:u,supplemental:d}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=Ea.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Hl(e,"moof")}demux(e,t,s){this.timeOffset=t;let i=e;const r=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=He(this.remainderData,e));const c=ec(i);this.remainderData=c.remainder,r.samples=c.valid||new Uint8Array}else r.samples=i;const o=this.extractID3Track(r,t),l=this.parseFragment(r,a,t,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){const s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const a=this.extractID3Track(i,this.timeOffset),o=this.parseFragment(i,r,s,t);return{videoTrack:i,audioTrack:nt(),id3Track:a,textTrack:nt(),initData:this.initData,sampleData:o}}parseFragment(e,t,s,i){const r=this.initData;if(r&&i){const{samples:a,sampleData:o}=Jl(s,e,r,this.logger,i.iframe);return t.samples=a,o}t.samples=tc(s,e)}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=J(e.samples,["emsg"]);i&&i.forEach(r=>{const a=sc(r);if($h.test(a.schemeIdUri)){const o=Sn(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;s.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Oe.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){const o=this.config.emsgKLVSchemaUri||Oe.misbklv;if(a.schemeIdUri.startsWith(o)){const l=Sn(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:Oe.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(e,t,s){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 Sn(n,e){return B(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}const Gh=1,Vh=2,Vt=-1;class Eo{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;if(i===0)return[];const r=e.naluState||0,a=r===Vt?0:r,o=[];let l=0,c=0,h=-1,u=0;for(r===Vt&&(h=0,u=this.getNALuType(t,0),c=1);c<i;){const d=t.indexOf(Gh,c);if(d===-1)break;c=d+1;let f=d;for(;f>0&&t[f-1]===0;)f--;if(!(d-f+(f===0?a:0)<Vh)){if(h>=0)o.push({data:t.subarray(h,f),type:u});else{const m=this.getLastNalUnit(e.samples);m&&(f>0?m.data=He(m.data,t.subarray(0,f)):a>0&&(m.data=m.data.subarray(0,m.data.byteLength-a)),m.state=0)}if(c<i)h=c,u=this.getNALuType(t,c);else{l=Vt,h=-1;break}}}if(l!==Vt){let d=i;for(;d>0&&t[d-1]===0;)d--;l=i-d+(d===0?a:0)}if(h>=0)o.push({data:t.subarray(h),type:u,state:l});else if(o.length===0&&l!==Vt){const d=this.getLastNalUnit(e.samples);d&&(d.data=He(d.data,t),d.state=l)}return e.naluState=l,o}}class Xt{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&le.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class Kh extends Eo{parsePES(e,t,s,i,r){const a=r.iframe,o=this.parseNALu(e,s.data,i);let l=this.VideoSample,c,h=!1;s.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.forEach(u=>{var d,f;switch(u.type){case 1:{if(a)break;let E=!1;c=!0;const S=u.data;if(h&&S.length>4){const T=this.readSliceType(S);(T===2||T===4||T===7||T===9)&&(E=!0)}if(E){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=E;break}case 5:c=!0,(d=l)!=null&&d.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;c=!0,ts(u.data,1,s.pts,t.samples);break}case 7:{var m,y;c=!0,h=!0;const E=u.data,S=this.readSPS(E);if(!e.sps||e.width!==S.width||e.height!==S.height||((m=e.pixelRatio)==null?void 0:m[0])!==S.pixelRatio[0]||((y=e.pixelRatio)==null?void 0:y[1])!==S.pixelRatio[1]){e.width=S.width,e.height=S.height,e.pixelRatio=S.pixelRatio,e.sps=[E];const T=E.subarray(1,4);let v="avc1.";for(let x=0;x<3;x++){let A=T[x].toString(16);A.length<2&&(A="0"+A),v+=A}e.codec=v}break}case 8:c=!0,e.pps=[u.data];break;case 9:c=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:c=!0;break;default:c=!1;break}l&&c&&l.units.push(u)}),i&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Xt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let a=0;a<e;a++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new Xt(e);let s=0,i=0,r=0,a=0,o,l,c;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),m=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const S=h();if(u(5),g(3),h(),y(),S===100||S===110||S===122||S===244||S===44||S===83||S===86||S===118||S===128){const b=d();if(b===3&&g(1),y(),y(),g(1),f())for(l=b!==3?8:12,c=0;c<l;c++)f()&&(c<6?E(16,t):E(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(g(1),m(),m(),o=d(),c=0;c<o;c++)m();y(),g(1);const v=d(),x=d(),A=u(1);A===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),a=d());let I=[1,1];if(f()&&f())switch(h()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-A)*(x+1)*16-(A?2:4)*(r+a),pixelRatio:I}}}class Hh extends Eo{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,l=!1;s.data=null;const c=h=>(a=this.VideoSample=this.createVideoSample(h,s.pts,s.dts),a);r.forEach((h,u)=>{var d,f;if(this.startsNewAccessUnit(a,e,h,u)){this.pushAccessUnit(a,e);const m=h.type>=16&&h.type<=23;a=c(m),l=!1}switch(h.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=c(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var g;(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=c(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=c(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,ts(h.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ue(e.params,this.readVPS(h.data)),this.initVPS=h.data),e.vps=[h.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],h.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const m=this.readSPS(h.data);e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.codec=m.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const y in m.params)e.params[y]=m.params[y]}this.pushParameterSet(e.sps,h.data,e.vps),a||(a=c(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const m=this.readPPS(h.data);for(const y in m)e.params[y]=m[y]}this.pushParameterSet(e.pps,h.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=c(!1));break;default:o=!1;break}a&&o&&a.units.push(h)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,i){if(!e)return!1;if(!t.audFound&&i===0)return!0;if(!e.frame)return!1;const{type:r,data:a}=s;return r>=32&&r<=35||r===39||r>=41&&r<=44||r>=48&&r<=55?!0:r<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Xt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new Xt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),y=t.readUByte(),E=t.readUByte(),S=[],T=[];for(let W=0;W<s;W++)S.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let W=s;W<8;W++)t.readBits(2);for(let W=0;W<s;W++)S[W]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[W]&&t.readUByte();t.readUEG();const v=t.readUEG();v==3&&t.skipBits(1);const x=t.readUEG(),A=t.readUEG(),I=t.readBoolean();let b=0,_=0,L=0,P=0;I&&(b+=t.readUEG(),_+=t.readUEG(),L+=t.readUEG(),P+=t.readUEG());const C=t.readUEG(),F=t.readUEG(),V=t.readUEG(),$=t.readBoolean();for(let W=$?0:s;W<=s;W++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let re=0;re<4;re++)for(let ae=0;ae<(re===3?2:6);ae++)if(!t.readBoolean())t.readUEG();else{const Te=Math.min(64,1<<4+(re<<1));re>1&&t.readEG();for(let Ce=0;Ce<Te;Ce++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const O=t.readUEG();let N=0;for(let W=0;W<O;W++){let re=!1;if(W!==0&&(re=t.readBoolean()),re){W===O&&t.readUEG(),t.readBoolean(),t.readUEG();let ae=0;for(let xe=0;xe<=N;xe++){const Te=t.readBoolean();let Ce=!1;Te||(Ce=t.readBoolean()),(Te||Ce)&&ae++}N=ae}else{const ae=t.readUEG(),xe=t.readUEG();N=ae+xe;for(let Te=0;Te<ae;Te++)t.readUEG(),t.readBoolean();for(let Te=0;Te<xe;Te++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const W=t.readUEG();for(let re=0;re<W;re++){for(let ae=0;ae<V+4;ae++)t.readBits(1);t.readBits(1)}}let M=0,U=1,ee=1,z=!0,ie=1,Q=0;t.readBoolean(),t.readBoolean();let ne=!1;if(t.readBoolean()){if(t.readBoolean()){const Ye=t.readUByte(),It=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],be=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Ye>0&&Ye<16?(U=It[Ye-1],ee=be[Ye-1]):Ye===255&&(U=t.readBits(16),ee=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ne=t.readBoolean(),ne&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),Q=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const be=t.readBoolean(),ke=t.readBoolean();let Ke=!1;(be||ke)&&(Ke=t.readBoolean(),Ke&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ke&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Ne=0;Ne<=s;Ne++){z=t.readBoolean();const Pe=z||t.readBoolean();let mt=!1;Pe?t.readEG():mt=t.readBoolean();const ht=mt?1:t.readUEG()+1;if(be)for(let We=0;We<ht;We++)t.readUEG(),t.readUEG(),Ke&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ke)for(let We=0;We<ht;We++)t.readUEG(),t.readUEG(),Ke&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let oe=x,ve=A;if(I){let W=1,re=1;v===1?W=re=2:v==2&&(W=2),oe=x-W*_-W*b,ve=A-re*P-re*L}const we=i?["A","B","C"][i]:"",ct=o<<24|l<<16|c<<8|h;let ge=0;for(let W=0;W<32;W++)ge=(ge|(ct>>W&1)<<31-W)>>>0;let Ve=ge.toString(16);return a===1&&Ve==="2"&&(Ve="6"),{codecString:`hvc1.${we}${a}.${Ve}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,l,c,h],general_constraint_indicator_flags:[u,d,f,g,m,y],general_level_idc:E,bit_depth:C+8,bit_depth_luma_minus8:C,bit_depth_chroma_minus8:F,min_spatial_segmentation_idc:M,chroma_format_idc:v,frame_rate:{fixed:z,fps:Q/ie}},width:oe,height:ve,pixelRatio:[U,ee]}}readPPS(e){const t=new Xt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let a=1;return r&&i?a=0:r?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return Ze(e).substring(3)===Ze(t).substring(3)}}const Ae=188;class ft{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=ft.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Ae*5,t-Ae)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let l=i;l<t;l+=Ae)if(e[l]===71&&(t-l===Ae||e[l+Ae]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Ae*99,e.length-Ae)+1)),r||(r=qs(e,l)===0),r&&o>1&&(a===0&&o>2||l+Ae>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Ea[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ft.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new qh(this.logger):null,this._audioTrack=ft.createTrack("audio",i),this._id3Track=ft.createTrack("id3"),this._txtTrack=ft.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,e&&this.demux(e,0,a,r?.method==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s,i=!1,r=!1){i||(this.sampleAes=null);let a;const o=this._videoTrack,l=this.videoIntegrityChecker,c=this._audioTrack,h=this._id3Track,u=this._txtTrack,d=s.iframe;let f=o.pid,g=o.pesData,m=c.pid,y=h.pid,E=this._klvPid,S=c.pesData,T=h.pesData,v=null,x=null,A=this.pmtParsed,I=this._pmtId,b=e.length;if(this.remainderData&&(e=He(this.remainderData,e),b=e.length,this.remainderData=null),b<Ae&&!r)return this.remainderData=e,{audioTrack:c,videoTrack:o,id3Track:h,textTrack:u};const _=Math.max(0,ft.syncOffset(e));b-=(b-_)%Ae,b<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,b,e.buffer.byteLength-b));let L=0;for(let C=_;C<b;C+=Ae)if(e[C]===71){const F=!!(e[C+1]&64),V=qs(e,C),$=(e[C+3]&48)>>4;let k;if($>1){if(k=C+5+e[C+4],k===C+Ae)continue}else k=C+4;switch(V){case f:F&&(g&&!(l!=null&&l.isCorrupted)&&(a=Lt(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,u,a,!1,s)),g={data:[],size:0},l?.reset(f)),l?.handlePacket(e.subarray(C)),g&&(g.data.push(e.subarray(k,C+Ae)),g.size+=C+Ae-k);break;case m:if(d)break;if(F){if(S&&(a=Lt(S,this.logger)))switch(c.segmentCodec){case"aac":this.parseAACPES(c,a,s);break;case"mp3":this.parseMPEGPES(c,a);break;case"ac3":this.parseAC3PES(c,a);break}S={data:[],size:0}}S&&(S.data.push(e.subarray(k,C+Ae)),S.size+=C+Ae-k);break;case y:if(d)break;F&&(T&&(a=Lt(T,this.logger))&&this.parseID3PES(h,a),T={data:[],size:0}),T&&(T.data.push(e.subarray(k,C+Ae)),T.size+=C+Ae-k);break;case E:if(d)break;F&&(v&&(a=Lt(v,this.logger))&&this.parseKlvPES(h,a),v={data:[],size:0}),v&&(v.data.push(e.subarray(k,C+Ae)),v.size+=C+Ae-k);break;case 0:F&&(k+=e[k]+1),I=this._pmtId=Yh(e,k);break;case I:{F&&(k+=e[k]+1);const w=Wh(e,k,this.typeSupported,i,this.observer,this.logger,this.config,s);f=w.videoPid,f>0&&(o.pid=f,o.segmentCodec=w.segmentVideoCodec),m=w.audioPid,m>0&&(c.pid=m,c.segmentCodec=w.segmentAudioCodec),y=w.id3Pid,y>0&&(h.pid=y),E=w.klvPid,E>0&&(this._klvPid=E),x!==null&&!A&&(this.logger.warn(`MPEG-TS PMT found at ${C} after unknown PID '${x}'. Backtracking to sync byte @${_} to parse all TS packets.`),x=null,C=_-188),A=this.pmtParsed=!0;break}case 17:case 8191:break;default:x=V;break}}else L++;L>0&&Bi(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),s,void 0,this.logger),o.pesData=g,c.pesData=S,h.pesData=T;const P={audioTrack:c,videoTrack:o,id3Track:h,textTrack:u};return r&&this.extractRemainingSamples(P,s),P}flush(e,t){const{remainderData:s}=this;this.remainderData=null;let i;return s?i=this.demux(s,0,t,!1,!0):i={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,t),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(e,t){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:a}=e,o=i.pesData,l=s.pesData,c=r.pesData,h=this.videoIntegrityChecker;let u;if(o&&!(h!=null&&h.isCorrupted)&&(u=Lt(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,a,u,!0,t),i.pesData=null)):i.pesData=o,l&&(u=Lt(l,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,u,t);break;case"mp3":this.parseMPEGPES(s,u);break;case"ac3":this.parseAC3PES(s,u);break}s.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=l;c&&(u=Lt(c,this.logger))?(this.parseID3PES(r,u),r.pesData=null):r.pesData=c}demuxSampleAes(e,t,s,i){const r=this.demux(e,s,i,!0,!this.config.progressive),a=this.sampleAes=new mo(this.observer,this.config,t);return this.decrypt(r,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Kh:e==="hevc"&&(this.videoParser=new Hh))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}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(e,t,s){let i=0;const r=this.aacOverFlow;let a=t.data;if(r){this.aacOverFlow=null;const d=r.missing,f=r.sample.unit.byteLength;if(d===-1)a=He(r.sample.unit,a);else{const g=f-d;r.sample.unit.set(a.subarray(0,d),g),e.samples.push(r.sample),i=r.missing}}let o,l;for(o=i,l=a.length;o<l-1&&!Ws(a,o);o++);if(o!==i){let d;const f=o<l-1;if(f?d=`AAC PES did not start with ADTS header,offset:${o}`:d="No ADTS header found in AAC PES",Bi(this.observer,new Error(d),s,f,this.logger),!f)return}oo(e,this.observer,a,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(r){const d=lo(e.samplerate);c=r.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,u;for(;o<l;)if(u=co(e,a,o,c,h),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(h++;o<l-1&&!Ws(a,o);o++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(fo(s,a)){const l=ho(e,s,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let a=0,o=0,l;for(;o<r&&(l=yo(e,s,o,i,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ue({},t,{type:this._videoTrack?Oe.emsg:Oe.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}parseKlvPES(e,t){var s;const i=(s=t.pts)!=null?s:t.dts;if(i===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const r=t.data;if(r.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<r.length;){var o;if(a+16>r.length)break;const l=a;if(a+=16,a>=r.length)break;const c=r[a];a+=1;let h=0;if(c&128){const g=c&127;if(g===0||g>4||a+g>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let m=0;m<g;m++)h=h<<8|r[a+m];a+=g}else h=c;if(a+h>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const u=a+h,d=r.subarray(l,u),f={data:d,len:d.byteLength,pts:i,dts:(o=t.dts)!=null?o:i,type:Oe.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=u}}}function qs(n,e){return((n[e+1]&31)<<8)+n[e+2]}function Yh(n,e){return(n[e+10]&31)<<8|n[e+11]}function Wh(n,e,t,s,i,r,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},c=(n[e+1]&15)<<8|n[e+2],h=e+3+c-4,u=(n[e+10]&15)<<8|n[e+11];for(e+=12+u;e<h;){const d=qs(n,e),f=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){di("ADTS AAC",r);break}case 15:l.audioPid===-1&&(l.audioPid=d);break;case 21:l.id3Pid===-1&&(l.id3Pid=d);break;case 219:if(!s){di("H.264",r);break}case 27:l.videoPid===-1&&(l.videoPid=d);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="mp3");break;case 193:if(!s){di("AC-3",r);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(f>0){let g=e+5,m=f;for(;m>2;){switch(n[g]){case 106:l.audioPid===-1&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=d,r.log(`KLV metadata PID found: ${d}`));break}const E=n[g+1]+2;g+=E,m-=E}}break;case 194:case 135:return Bi(i,new Error("Unsupported EC-3 in M2TS found"),o,void 0,r),l;case 36:l.videoPid===-1&&(l.videoPid=d,l.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=f+5}return l}function Bi(n,e,t,s,i){i.warn(`parsing error: ${e.message}`),n.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:t,error:e,reason:e.message})}function di(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function Lt(n,e){let t=0,s,i,r,a,o;const l=n.data;if(!n||n.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=He(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>n.size-6)return null;const h=s[7];h&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=s[8];let u=r+9;if(n.size<=u)return null;n.size-=u;const d=new Uint8Array(n.size);for(let f=0,g=l.length;f<g;f++){s=l[f];let m=s.byteLength;if(u)if(u>m){u-=m;continue}else s=s.subarray(u),m-=u,u=0;d.set(s,t),t+=m}return i&&(i-=r+3),{data:d,pts:a,dts:o,len:i}}return null}class qh{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;const t=qs(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}const s=(e[3]&48)>>4;if(s===0)return;const i=e[3]&15,r=this.lastContinuityCounter;this.lastContinuityCounter=i;const a=(s&1)!=0;if((s&2)!=0&&e[4]!=0&&(e[5]&128)!=0||r<0)return;const c=a?r+1&15:r;if(i!==c){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${i}, Expected-CC=${c} Last-CC=${r}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}}class jh{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===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(t===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(t===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(t===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(t===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 js;const zh={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])},fi=new Uint8Array([0,0,0,0,0,0,0,0]),Xh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Qh=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Zh=new Uint8Array([0,0,0,0,0,0,0,0]),Kt=new Uint8Array([0,0,0,0,0,0,0,1]),vn=new Uint8Array([105,115,111,109]),Jh=new Uint8Array([97,118,99,49]),eu=new Uint8Array([0,0,0,1]);class G{static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const a=new Uint8Array(s);for(Se(a,0,s),Se(a,4,e),i=0,s=8;i<r;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return G.box(Z.hdlr,zh[e])}static mdat(e){return G.box(Z.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(st+1)),i=Math.floor(t%(st+1));return G.box(Z.mdhd,new Uint8Array([1,0,0,0,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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return G.box(Z.mdia,G.mdhd(e.timescale||0,e.duration||0),G.hdlr(e.type),G.minf(e))}static mfhd(e){return G.box(Z.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?G.box(Z.minf,G.box(Z.smhd,Zh),G.DINF,G.stbl(e)):G.box(Z.minf,G.box(Z.vmhd,Qh),G.DINF,G.stbl(e))}static moof(e,t,s){return G.box(Z.moof,G.mfhd(e),G.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=G.trak(e[t]);return G.box.apply(null,[Z.moov,G.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(G.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=G.trex(e[t]);return G.box.apply(null,[Z.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(st+1)),i=Math.floor(t%(st+1)),r=new Uint8Array([1,0,0,0,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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&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 G.box(Z.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return G.box(Z.sdtp,s)}static stbl(e){return G.box(Z.stbl,G.stsd(e),G.box(Z.stts,fi),G.box(Z.stsc,fi),G.box(Z.stsz,Xh),G.box(Z.stco,fi))}static avc1(e){let t=[],s=[],i,r,a;for(i=0;i<e.sps.length;i++)r=e.sps[i],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));const o=G.box(Z.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,c=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return G.box(Z.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,c>>8&255,c&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,G.box(Z.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(Z.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return G.box(Z.mp4a,G.audioStsd(e),G.box(Z.esds,G.esds(e)))}static mp3(e){return G.box(Z[".mp3"],G.audioStsd(e))}static ac3(e){return G.box(Z["ac-3"],G.audioStsd(e),G.box(Z.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return G.box(Z.stsd,Kt,G.mp4a(e));if(t==="ac3"&&e.config)return G.box(Z.stsd,Kt,G.ac3(e));if(t==="mp3"&&e.codec==="mp3")return G.box(Z.stsd,Kt,G.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return G.box(Z.stsd,Kt,G.avc1(e));if(t==="hevc"&&e.vps)return G.box(Z.stsd,Kt,G.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,a=Math.floor(s/(st+1)),o=Math.floor(s%(st+1));return G.box(Z.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&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,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=G.sdtp(e),i=e.id,r=Math.floor(t/(st+1)),a=Math.floor(t%(st+1));return G.box(Z.traf,G.box(Z.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),G.box(Z.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),G.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,G.box(Z.trak,G.tkhd(e),G.mdia(e))}static trex(e){const t=e.id;return G.box(Z.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r);let o,l,c,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)l=s[o],c=l.duration,h=l.size,u=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return G.box(Z.trun,a)}static initSegment(e){const t=G.moov(e);return He(G.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let a=r.length;for(let g=0;g<s.length;g+=1){a+=3;for(let m=0;m<s[g].length;m+=1)a+=2+s[g][m].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const l=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===l?128:0),0,s[g].length]),a),a+=3;for(let m=0;m<s[g].length;m+=1)o.set(new Uint8Array([s[g][m].length>>8,s[g][m].length&255]),a),a+=2,o.set(s[g][m],a),a+=s[g][m].length}const c=G.box(Z.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return G.box(Z.hvc1,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,h>>8&255,h&255,u>>8&255,u&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]),c,G.box(Z.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(Z.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}js=G;G.FTYP=js.box(Z.ftyp,vn,eu,vn,Jh);G.DINF=js.box(Z.dinf,js.box(Z.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const To=9e4;function pr(n,e,t=1,s=!1){const i=n*e*t;return s?Math.round(i):i}function tu(n,e,t=1,s=!1){return pr(n,e,1/t,s)}function Ht(n,e=!1){return pr(n,1e3,1/To,e)}function su(n,e=1){return pr(n,To,1/e)}function xn(n){const{baseTime:e,timescale:t,trackId:s}=n;return`${e/t} (${e}/${t}) trackId: ${s}`}const iu=10*1e3,ru=1024,nu=1152,au=1536,$i=8589934592;function An(n,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1,paddingValue:0}}}class Cs extends Ge{constructor(e,t,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&xn(t)} > ${e&&xn(e)}`),this._initPTS=this._initDTS=e}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(e){let t=!1;const s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=$e(o,s),l=o-r),l>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,l,c){let h,u,d,f,g,m,y=r,E=r;const T=!c.iframe&&e.pid>-1,v=t.pid>-1,x=t.samples.length,A=e.samples.length>0,I=o&&x>0||x>1;if((!T||A)&&(!v||I)||this.ISGenerated||o){if(this.ISGenerated){var _,L,P,C;const k=this.videoTrackConfig;(k&&(t.width!==k.width||t.height!==k.height||((_=t.pixelRatio)==null?void 0:_[0])!==((L=k.pixelRatio)==null?void 0:L[0])||((P=t.pixelRatio)==null?void 0:P[1])!==((C=k.pixelRatio)==null?void 0:C[1]))||!k&&I||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,a));const F=this.isVideoContiguous;let V=-1,$;if(I&&(V=ou(t.samples),!F&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,V>0){this.warn(`Dropped ${V} out of ${x} video samples due to a missing keyframe`);const k=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(V),t.dropped+=V,E+=(t.samples[0].pts-k)/t.inputTimeScale,$=E}else V===-1&&(this.warn(`No keyframe found out of ${x} video samples`),m=!1);if(this.ISGenerated){if(A&&I&&r){const k=this.getVideoStartPts(t.samples),O=($e(e.samples[0].pts,k)-k)/t.inputTimeScale;y+=Math.max(0,O),E+=Math.max(0,-O)}if(A){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,a)),u=this.remuxAudio(e,y,this.isAudioContiguous,a,v||I||l===H.AUDIO?E:void 0,c),I){const k=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,a)),h=this.remuxVideo(t,E,F,k,c)}}else I&&(h=this.remuxVideo(t,E,F,0,c));h&&(h.firstKeyFrame=V,h.independent=V!==-1,h.firstKeyFramePTS=$)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=So(s,r,this._initPTS,this._initDTS)),i.samples.length&&(f=vo(i,r,this._initPTS))),{audio:u,video:h,initSegment:d,independent:m,text:f,id3:g}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let a=$e(e,r);if(a<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${i}`);a<r;)a+=$i;return a-r}generateIS(e,t,s,i){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS,h=!c||i;let u="audio/mp4",d,f,g,m=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):G.initSegment([e]),metadata:{channelCount:e.channelCount}},h){m=e.id,g=e.inputTimeScale;const y=this.computeInitPts(r[0].pts,g,s,"audio");(!c||g!==c.timescale||s===0&&y<c.baseTime)&&(d=f=y)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:G.initSegment([t]),metadata:{width:t.width,height:t.height}},h){m=t.id,g=t.inputTimeScale;const y=this.getVideoStartPts(a),E=$e(a[0].dts,y),S=this.computeInitPts(E,g,s,"video"),T=this.computeInitPts(y,g,s,"video");(!c||g!==c.timescale||B(d)||s===0&&T<c.baseTime)&&(f=Math.min(f,S),d=Math.min(d,S))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h&&B(d)?(c&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/g} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${m}`),this._initPTS={baseTime:d,timescale:g,trackId:m},this._initDTS={baseTime:f,timescale:g,trackId:m}):d=g=void 0,{tracks:l,initPTS:d,timescale:g,trackId:m}}remuxVideo(e,t,s,i,r){const a=e.inputTimeScale,o=e.samples,l=[],c=o.length,h=this._initPTS,u=h.baseTime*a/h.timescale;let d=this.nextVideoTs,f=8,g=this.videoSampleDuration,m,y,E=Number.POSITIVE_INFINITY,S=Number.NEGATIVE_INFINITY,T=!1;if(!s||d===null){const M=u+t*a,U=o[0].pts-$e(o[0].dts,o[0].pts);qt()&&d!==null&&Math.abs(M-U-(d+u))<15e3?s=!0:d=M-U-u}const v=d+u;for(let M=0;M<c;M++){const U=o[M];U.pts=$e(U.pts,v),U.dts=$e(U.dts,v),U.dts<o[M>0?M-1:M].dts&&(T=!0)}T&&o.sort(function(M,U){const ee=M.dts-U.dts,z=M.pts-U.pts;return ee||z}),m=o[0].dts,y=o[o.length-1].dts;const x=y-m,A=x?Math.round(x/(c-1)):g||e.inputTimeScale/30;if(s){const M=m-v,U=M>A,ee=M<-1;if((U||ee)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ht(M,!0)} ms (${M}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ht(-M,!0)} ms (${M}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ee||v>=o[0].pts||qt())){m=v;const z=o[0].pts-M;if(U)o[0].dts=m,o[0].pts=z;else{let ie=!0;for(let Q=0;Q<o.length&&!(o[Q].dts>z&&ie);Q++){const ne=o[Q].pts;if(o[Q].dts-=M,o[Q].pts-=M,Q<o.length-1){const te=o[Q+1].pts,oe=o[Q].pts,ve=te<=oe,we=te<=ne;ie=ve==we}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ht(z,!0)}/${Ht(m,!0)}, delta: ${Ht(M,!0)} ms`)}}m=Math.max(0,m);let I=0,b=0,_=m;for(let M=0;M<c;M++){const U=o[M],ee=U.units,z=ee.length;let ie=0;for(let Q=0;Q<z;Q++)ie+=ee[Q].data.length;b+=ie,I+=z,U.length=ie,U.dts<_?(U.dts=_,_+=A/4|0||1):_=U.dts,E=Math.min(U.pts,E),S=Math.max(U.pts,S)}y=o[c-1].dts;const L=b+4*I+8;let P;try{P=new Uint8Array(L)}catch(M){this.observer.emit(p.ERROR,p.ERROR,{type:q.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:M,bytes:L,reason:`fail allocating video mdat ${L}`});return}Se(P,0,L),Se(P,4,Z.mdat);let C=!1,F=Number.POSITIVE_INFINITY,V=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let M=0;M<c;M++){const U=o[M],ee=U.units;let z=0;for(let ne=0,te=ee.length;ne<te;ne++){const oe=ee[ne],ve=oe.data,we=oe.data.byteLength;Se(P,f,we),f+=4,P.set(ve,f),f+=we,z+=4+we}let ie;if(M<c-1)g=o[M+1].dts-U.dts,ie=o[M+1].pts-U.pts;else{const ne=this.config,te=M>0?U.dts-o[M-1].dts:A;if(ie=M>0?U.pts-o[M-1].pts:A,ne.stretchShortVideoTrack&&this.nextAudioTs!==null){const oe=Math.floor(ne.maxBufferHole*a),ve=(i?E+i*a:this.nextAudioTs+u)-U.pts;ve>oe?(g=ve-te,g<0?g=te:C=!0,this.log(`It is approximately ${ve/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=te}else g=te}let Q=Math.round(U.pts-U.dts);if(F=Math.min(F,g),$=Math.max($,g),V=Math.min(V,ie),k=Math.max(k,ie),!s&&M===0&&Q>g){const ne=Math.round(Q/A)*A;ne-Q===1&&(this.log(`pad first CTS ${Q} -> ${ne} of sn: ${r.sn}`),Q=ne)}l.push(An(U.key,g,z,Q))}if(l.length){const M=qt();if(M){if(M<70){const U=l[0].flags;U.dependsOn=2,U.isNonSync=0}}else if(lc()&&k-V<$-F&&A/$<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let U=m;for(let ee=0,z=l.length;ee<z;ee++){const ie=U+l[ee].duration,Q=U+l[ee].cts;if(ee<z-1){const ne=ie+l[ee+1].cts;l[ee].duration=ne-Q}else l[ee].duration=ee?l[ee-1].duration:A;l[ee].cts=0,U=ie}}}g=C||!g?A:g;const w=y+g;this.nextVideoTs=d=w-u,this.videoSampleDuration=g,this.isVideoContiguous=!0,r.iframe&&(l.length===1?(l[0].duration=g=r.duration*a,this.nextVideoTs=d=m+g-u):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));const Y={data1:G.moof(r.sn,m,ue(e,{samples:l})),data2:P,startPTS:(E-u)/a,endPTS:(S+g-u)/a,startDTS:(m-u)/a,endDTS:d/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return nu;case"ac3":return au;default:return ru}}remuxAudio(e,t,s,i,r,a){const o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,c=o/l,h=this.getSamplesPerFrame(e),u=h*c,d=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],m=r!==void 0;let y=e.samples,E=f?0:8,S=this.nextAudioTs||-1;const T=d.baseTime*o/d.timescale,v=T+t*o;if(this.isAudioContiguous=s=s||y.length&&S>0&&(i&&Math.abs(v-(S+T))<9e3||Math.abs($e(y[0].pts,v)-(S+T))<20*u),y.forEach(function(w){w.pts=$e(w.pts,v)}),!s||S<0){const w=y.length;if(y=y.filter(O=>O.pts>=0),w!==y.length&&this.warn(`Removed ${y.length-w} of ${w} samples (initPTS ${T} / ${o})`),!y.length)return;r===0?S=0:i&&!m?S=Math.max(0,v-T):S=y[0].pts-T}if(e.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let O=0,N=S+T;O<y.length;O++){const Y=y[O],M=Y.pts,U=M-N,ee=Math.abs(1e3*U/o);if(U<=-w*u&&m)O===0&&(this.warn(`Audio frame @ ${(M/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*U/o)} ms.`),this.nextAudioTs=S=M-T,N=M);else if(U>=w*u&&ee<iu&&m){let z=Math.round(U/u);for(N=M-z*u;N<0&&z&&u;)z--,N+=u;O===0&&(this.nextAudioTs=S=N-T),this.warn(`Injecting ${z} audio frames @ ${((N-T)/o).toFixed(3)}s due to ${Math.round(1e3*U/o)} ms gap.`);for(let ie=0;ie<z;ie++){let Q=jh.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);Q||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Q=Y.unit.subarray()),y.splice(O,0,{unit:Q,pts:N}),N+=u,O++}}Y.pts=N,N+=u}}let x=null,A=null,I,b=0,_=y.length;for(;_--;)b+=y[_].unit.byteLength;for(let w=0,O=y.length;w<O;w++){const N=y[w],Y=N.unit;let M=N.pts;if(A!==null){const ee=g[w-1];ee.duration=Math.round((M-A)/c)}else if(s&&e.segmentCodec==="aac"&&(M=S+T),x=M,b>0){b+=E;try{I=new Uint8Array(b)}catch(ee){this.observer.emit(p.ERROR,p.ERROR,{type:q.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:ee,bytes:b,reason:`fail allocating audio mdat ${b}`});return}f||(Se(I,0,b),Se(I,4,Z.mdat))}else return;I&&I.set(Y,E);const U=Y.byteLength;E+=U,g.push(An(!0,h,U,0)),A=M}const L=g.length;if(!L)return;const P=g[g.length-1];S=A-T,this.nextAudioTs=S+c*P.duration;const C=f?new Uint8Array(0):G.moof(e.sequenceNumber++,x/c,ue({},e,{samples:g}));e.samples=[];const F=(x-T)/o,V=this.nextAudioTs/o,k={data1:C,data2:I,startPTS:F,endPTS:V,startDTS:F,endDTS:V,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,k}}function $e(n,e){let t;if(e===null)return n;for(e<n?t=-$i:t=$i;Math.abs(n-e)>4294967296;)n+=t;return n}function ou(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function So(n,e,t,s){const i=n.samples.length;if(!i)return;const r=n.inputTimeScale;for(let o=0;o<i;o++){const l=n.samples[o];l.pts=$e(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=$e(l.dts-s.baseTime*r/s.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function vo(n,e,t){const s=n.samples.length;if(!s)return;const i=n.inputTimeScale;for(let a=0;a<s;a++){const o=n.samples[a];o.pts=$e(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class lu extends Ge{constructor(e,t,s,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:a,video:o}=this.initData=s||xa(e);if(t)jl(e,t);else{const c=a||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}a&&(i=In(a,de.AUDIO,this)),o&&(r=In(o,de.VIDEO,this));const l={};a&&o?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:i,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,s,i,r,a,o,l,c,h,u){var d,f;let{initPTS:g,lastEndTime:m}=this;const y={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};B(m)||(m=this.lastEndTime=r||0);const E=t.samples;if(!E.length)return y;const S=this.pendingInitSegment;S&&(this.pendingInitSegment=void 0,this.generateInitSegment(S,this.decryptdata,h));const T={initPTS:void 0,timescale:void 0,trackId:void 0};let v=this.initData;if((d=v)!=null&&d.length||(this.generateInitSegment(E),v=this.initData),!((f=v)!=null&&f.length))return this.warn("Failed to generate initSegment."),y;if(c.iframe&&v.audio&&v.video){var x;const W=(x=this.initTracks)==null||(x=x.audiovideo)==null?void 0:x.initSegment,re=W?Vl(W):null;if(re){var A;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(re,this.decryptdata),(A=this.initData)!=null&&A.length&&(v=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(T.tracks=this.initTracks,y.initSegment=T,this.emitInitSegment=!1);const I=c.iframe,b=u&&(!I||u.includeSampleDetails)?u.tracks:Zl(E,v,c,this,I),_=v.audio?b[v.audio.id]:null,L=v.video?b[v.video.id]:null,P=!!v.audio,C=!!v.video;let F="";P&&(F+="audio"),C&&(F+="video");const V=Ts(L,1/0),$=Ts(_,1/0),k=Ts(L,0,!0),w=Ts(_,0,!0);let O=r,N=0;L&&_&&v.audio&&($>k||V>w)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${V}-${k} a: ${$}-${w}}`,L,_);const Y=!!_&&(!L||!g&&$<V||!!g&&g.trackId===v.audio.id),M=Y?_:L;if(!M)return this.log(`No media samples found in ${l} ${c.level} ${c.part===-1?"":`part: ${c.part} of`} sn: ${c.sn} at playlist time: ${r}`),y;let U=E,ee,z;if(L&&L.sampleCount>=1&&v.video&&c.iframe){const{trun:W,start:re}=L,ae=W.length===1,xe=W.length?ae?W[0].samples:W[0].samples.concat(...W.slice(1).map(Te=>Te.samples)):[];if(xe.length){const Te=W[0];let Ce=Te;for(let Ne=W.length;Ne--;)if(W[Ne].samples.length){Ce=W[Ne];break}const Ye=Ce.lastSampleDurationOffset,{defaultSampleDurationOffset:It}=Te,be=Math.abs(c.duration-(k-V))>.05,ke=xe.length<L.sampleCount;if(!(be||ke||this.videoOnlyRemux||!ae))N=k-V;else{const Ne=ke?Ce.sampleOffset+Ce.samples.reduce((We,_r)=>We+_r.size,0):void 0,Pe=be?c.duration:k-V,mt=hu(xe,Pe*v.video.timescale,Ye,It),ht=Kl(E,v.video.id,xe.length,Ne,mt);ht?(U=ht,z=cu(re,xe)):this.warn(`IFrame remux skipped (sn ${c.sn}); using native sample duration`),N=ht&&mt?Pe:k-V}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${W.length})`),N=k-V}else N=Y?w-$:k-V;if(this.videoOnlyRemux&&U===E)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${c.sn})`),y;const ie=M.timescale,Q=M.start-r*ie,ne=Y?v.audio.id:v.video.id;if(O=M.start/ie,(a||!g)&&(uu(g,O,r,N)||ie!==g.timescale)){let W=!1;const re=Y?"audio":"video";if(g){const ae=r!==0?O/r:1+O/1;W=O>=0&&Math.abs(1-ae)<.001,this.log(`${re} timestamps in track ${ne} at playlist time: ${a?"":"~"}${r} maps to ${O} with initPTS: ${g.baseTime/g.timescale} (${Q/ie-g.baseTime/g.timescale}s diff) (${F}) drift estimate: ${ae} ${W?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}W||(this.log(`Found initPTS in ${re} track ${ne} at playlist time: ${r} offset: ${O-r} (${Q}/${ie})`),g=null,T.initPTS=Q,T.timescale=ie,T.trackId=ne)}g?(T.initPTS=g.baseTime,T.timescale=g.timescale,T.trackId=g.trackId):((!T.timescale||T.trackId===void 0||T.initPTS===void 0)&&(this.warn("Could not set initPTS"),T.initPTS=O,T.timescale=1,T.trackId=-1),this.initPTS=g={baseTime:T.initPTS,timescale:T.timescale,trackId:T.trackId});const te=O-g.baseTime/g.timescale,oe=te+N,ve=C&&M?.ptsMin!==void 0?M.ptsMin/M.timescale-g.baseTime/g.timescale:te,we=z!==void 0&&L?z/L.timescale-g.baseTime/g.timescale:C&&M!=null&&M.ptsMax?M.ptsMax/M.timescale-g.baseTime/g.timescale:oe;N>0?this.lastEndTime=oe:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const ct=(v.audio?v.audio.encrypted:!1)||(v.video?v.video.encrypted:!1),ge={data1:U,data2:ee,startPTS:ve,startDTS:te,endPTS:we,endDTS:oe,type:F,hasAudio:P,hasVideo:C,nb:1,dropped:0,encrypted:ct};y.audio=P&&!C?ge:void 0,y.video=C?ge:void 0;const Ve=this.isVideoContiguous,Je=L?.sampleCount;if(Je){const W=L.keyFrameIndex,re=W!==-1;ge.nb=Je,ge.dropped=W===0||Ve?0:re?W:Je,ge.independent=re,ge.firstKeyFrame=W,re&&L.keyFrameStart&&(ge.firstKeyFramePTS=(L.keyFrameStart-g.baseTime)/g.timescale),Ve||(y.independent=re),this.isVideoContiguous||(this.isVideoContiguous=re),ge.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${W}/${Je} dropped: ${ge.dropped} start: ${ge.firstKeyFramePTS||"NA"}`)}return y.initSegment=T,y.id3=So(s,r,g,g),i.samples.length&&(y.text=vo(i,r,g)),y}}function Ts(n,e,t=!1){return n?.start!==void 0?(n.start+(t?n.duration:0))/n.timescale:e}function cu(n,e){let t=n,s=n;for(let i=0;i<e.length;i++){const{cts:r,duration:a}=e[i];s=Math.max(s,t+(r||0)+a),t+=a}return s}function hu(n,e,t,s){if(t!==void 0){const r=n[n.length-1];let a=e;for(let o=0;o<n.length-1;o++)a-=n[o].duration;return a<=0&&(a=r.duration),r.duration=a,{durationOffset:t,value:a}}if(s===void 0)return;const i=Math.round(e/n.length);for(let r=0;r<n.length;r++)n[r].duration=i;return{durationOffset:s,value:i}}function uu(n,e,t,s){if(n===null)return!0;const i=Math.max(s,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>=i}function In(n,e,t){const s=n.codec;return s&&s.length>4?s:e===de.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Ns(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):s==="mjpg"?s:(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let Et;try{Et=self.performance.now.bind(self.performance)}catch{Et=Date.now}const ks=[{demux:Uh,remux:lu},{demux:ft,remux:Cs},{demux:Fh,remux:Cs},{demux:Bh,remux:Cs}];ks.splice(2,0,{demux:Nh,remux:Cs});class Ln{constructor(e,t,s,i,r,a){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=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){if(!this.observer)return Ss(s);const r=s.transmuxing;r.executeStart=Et();const a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:m,videoCodec:y,defaultInitPts:E,duration:S,initSegmentData:T}=l,v=du(a,t);if(v&&Mt(v.method)){const b=this.getDecrypter(),_=cr(v.method);return this.asyncResult=!0,this.decryptionPromise=b.decrypt(a,v.key.buffer,v.iv.buffer,_,s.decryptRange).then(L=>{const P=this.push(L,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const b=s.iframe&&T&&ft.probe(T,this.logger)?T:a,_=this.configureTransmuxer(b);if(_)return this.logger.warn(`[transmuxer] ${_.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:_,reason:_.message}),r.executeEnd=Et(),Ss(s)}(h||u||g||x)&&this.resetInitSegment(T,m,y,S,t,s),(h||g||x)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const A=this.transmux(a,v,f,d,s);this.asyncResult=os(A);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,r.executeEnd=Et(),A}flush(e){const t=e.transmuxing;t.executeStart=Et();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=Et();const u=[Ss(e)];return this.asyncResult?Promise.resolve(u):u}const h=l.flush(o,e);return os(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){if(!this.remuxer)return;const{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);const h=this.remuxer.remux(i,r,a,o,c,l,!0,this.id,s,t.initData,t.sampleData);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Et()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r,a){const{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,s,i,r,a),l.resetInitSegment(e,t,s,r))}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(e,t,s,i,r){let a;return t?.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,r):a=this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){const{demuxer:r,remuxer:a}=this;if(!r||!a)return Ss(i);const o=r.demux(e,t,i,!1,!this.config.progressive),{audioTrack:l,videoTrack:c,id3Track:h,textTrack:u}=o;return{remuxResult:a.remux(l,c,h,u,t,s,!1,this.id,i,o.initData,o.sampleData),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(e,t,s,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id,r,a.initData,a.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let u=0,d=ks.length;u<d;u++){var a;if((a=ks[u].demux)!=null&&a.probe(e,this.logger)){r=ks[u];break}}}catch(u){return u}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=r.demux,h=r.remux;(!o||!(o instanceof c))&&(this.logger.log(`Using ${c.name}`),this.demuxer=new c(s,t,i,this.logger),this.probe=c.probe),(!l||!(l instanceof h))&&(this.logger.log(`Using ${h.name}`),this.remuxer=new h(s,t,i,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ar(this.config)),e}}function du(n,e){let t=null;return n.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ss=n=>({remuxResult:{},chunkMeta:n});function os(n){return"then"in n&&n.then instanceof Function}class fu{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class gu{constructor(e,t,s,i,r,a){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=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}}let Rn=0;class xo{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Rn++,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 c=l.data,h=this.hls;if(!(!h||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{h.logger[c.data.logType]&&h.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,h.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const c=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(p.ERROR,{type:q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===p.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new dr,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);const o=Ur(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(r.workerPath||vh()){try{r.workerPath?(l.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Ah(r.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=xh());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:t,config:fe(r)})}catch(h){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Rn++;const t=this.hls.config,s=Ur(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:fe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Ih(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,a,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,m=a?a.start:r.start,y=r.decryptdata,E=this.frag,S=E?r.cc!==E.cc:!0,T=E?c.level!==E.level:!0,v=E?c.sn-E.sn:-1,x=this.part?c.part-this.part.index:-1,A=v===0&&c.id>1&&c.id===E?.stats.chunkCount,I=!T&&(v===1||v===0&&(x===1||A&&x<=0)),b=self.performance.now();(T||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),a&&(x||!I)&&(a.stats.parsing.start=b);const _=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),L=new gu(S,I,l,T,m,_);if(!I||S||_){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id} playlist: ${c.level} id: ${c.id}
|
|
17
|
+
discontinuity: ${S}
|
|
18
|
+
trackSwitch: ${T}
|
|
19
|
+
contiguous: ${I}
|
|
20
|
+
accurateTimeOffset: ${l}
|
|
21
|
+
timeOffset: ${m}
|
|
22
|
+
initSegmentChange: ${_}`);const P=new fu(s,i,t,o,h);this.configureTransmuxer(P)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:c,state:L},e instanceof ArrayBuffer?[e]:[]);else if(g){const P=g.push(e,y,c,L);os(P)?P.then(C=>{this.handleTransmuxComplete(C)}).catch(C=>{this.transmuxerError(C,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);os(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const bn=100;class mu extends ur{constructor(e,t,s){super(e,t,s,"audio-stream-controller",H.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){const{frag:s,id:i,initPTS:r,timescale:a,trackId:o,timestampOffsets:l}=t;if(i===H.MAIN){const c=s.cc,h=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${c} found from main: ${r/a} (${r}/${a}) trackId: ${o}`),this.mainAnchor=s,this.state===D.WAITING_INIT_PTS){const u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==c)&&this.syncWithAnchor(s,u?.frag)}else!this.hls.hasEnoughToStart&&h&&h.cc!==c?(h.abortRequests(),this.syncWithAnchor(s,h)):this.state===D.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const r=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=$a(a,r,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===D.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=D.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(bn),s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=D.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case D.IDLE:this.doTickIdle();break;case D.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=D.WAITING_INIT_PTS}break}case D.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case D.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=D.FRAG_LOADING;const o=i.flush().buffer,l={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=D.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=D.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.getBufferOutput();this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,de.AUDIO));const h=this.getFwdBufferInfo();if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=D.ENDED;return}const u=h.len,d=t.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),y=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?m:h.end;if(this.switchingTrack&&i){const T=m;l.PTSKnown&&T<g&&T>=this.timelineOffset&&(h.end>g||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${T} -> ${g} + 0.05`),i.currentTime=g+.05)}if(u>=d&&!this.switchingTrack&&y<f[f.length-1].start)return;let E=this.getNextFragment(y,l);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,l,h,H.MAIN,d)),!E){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,d,E))return;let S=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&S&&Ee(E)&&!E.endList&&(!l.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(S)===ye.OK&&(this.mainFragLoading=S=null),S&&Ee(S))){if(E.start>S.end){const v=this.fragmentTracker.getFragAtPos(y,H.MAIN);v&&v.end>S.end&&(S=v,this.mainFragLoading={frag:v,targetBufferTime:null})}if(E.start>S.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new rs(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==D.STOPPED&&(this.setInterval(bn),this.state=D.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(p.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:a,groupId:o,track:l}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const c=this.mainDetails;if(!c||r.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==D.STOPPED&&(this.state=D.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[a];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(Ks(c,r,this),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(p.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===D.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=D.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new xo(this.hls,H.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const y=i?i.index:-1,E=y!==-1,S=new or(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E,s.duration);d.push(r,g,u,"",s,i,h.totalduration,!1,S,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:m}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new ro,complete:!1};m.push(new Uint8Array(r)),this.state!==D.STOPPED&&(this.state=D.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===H.MAIN&&Ee(t.frag)&&(this.mainFragLoading=t,this.state===D.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==H.AUDIO){!this.audioOnly&&s.type===H.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ee(s)){const r=this.switchingTrack;r&&(this.bufferedTrack=r)}this.fragBufferedComplete(s,i),this.media&&this.tick()}getFwdBufferInfo(){const e=this.getBufferOutput();return super.getFwdBufferInfo(e,H.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const s=this.fragPlaying,i=e?.level;return(!s||s.level!==i)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var s;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===se.AUDIO_TRACK&&(this.state=D.IDLE);break;case R.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==de.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==de.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===D.ENDED&&(this.state=D.IDLE);const s=this.getBufferOutput();s&&(this.afterBufferFlushed(s,t),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:f,id3:g,initSegment:m}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=D.PARSING,d&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:y}=this,E=y.nextAudioTrackBufferFlushForwardOffset,S=Math.max(this.getLoadPosition()+E,l.start);super.flushMainBuffer(S,Number.POSITIVE_INFINITY,H.AUDIO)}if(m!=null&&m.tracks){const y=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(h,m.tracks,y,a),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:m.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:S,endDTS:T}=d;c&&(c.elementaryStreams[de.AUDIO]={startPTS:y,endPTS:E,startDTS:S,endDTS:T}),l.setElementaryStreamInfo(de.AUDIO,y,E,S,T),this.bufferFragmentData(d,l,c,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const y=ue({id:s,frag:l,details:u},g);i.trigger(p.FRAG_PARSING_METADATA,y)}if(f){const y=ue({id:s,frag:l,details:u},f);i.trigger(p.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==D.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=H.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a?.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(p.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===ye.NOT_LOADED||i===ye.PARTIAL){var r;if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=D.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ks(a,t.details,this)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;Dt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,_t)||($s(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,j({},e))}get nextAudioTrack(){return this.nextTrackId}}class yr extends Ge{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}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(e,t,s){const i=t?.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){const o=i[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){const a=i[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const c=s&&Gr(s);return new Vr(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,a=i.fragments,o=self.performance.now(),l=r.loading.first?Math.max(0,Math.floor(o-r.loading.first)):0;i.advancedDateTime=Date.now()-l;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const u=Math.max(c||0,0);i.appliedTimelineOffset=u,a.forEach(d=>{d?.setStart(d.playlistOffset+u)})}if(i.live||s!=null&&s.live){var h;const u="levelInfo"in t?t.levelInfo:t.track;i.reloaded(s);const d=(h=a[a.length-1])==null?void 0:h.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const x=new Error(`${d} playlist ${u.id} hit max allowed unchanged reloads.`);this.warn(x);const{networkDetails:A,context:I}=t;this.hls.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:R.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:x,reason:x.message,level:t.level,parent:d,context:I,networkDetails:A,stats:r});return}if(s){ch(s,i,this);const x=i.playlistParsingError;if(x){this.warn(x);const A=this.hls;if(!A.config.ignorePlaylistParsingErrors){const{networkDetails:I}=t;A.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:x,reason:x.message,level:t.level,parent:d,networkDetails:I,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,m=(i.edge-g)*1e3,y=Za(i,m);i.requestScheduled+y<o?i.requestScheduled=o:i.requestScheduled<=o&&(i.requestScheduled+=y);const E=t.deliveryDirectives;if(this.log(`live playlist ${e} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${E?` | requested ${E.msn} - ${E.part}`:""})`}`),!this.canLoad||!i.live)return;let S,T,v;if(i.canBlockReload&&i.advanced){const x=this.hls.config.lowLatencyMode,A=i.lastPartSn,I=i.endSN,b=i.lastPartIndex,_=b!==-1,L=A===I;_?L?(T=I+1,v=x?0:b):(T=A,v=x?b+1:i.maxPartIndex):T=I+1;const P=i.age,C=P+i.ageHeader;let F=Math.min(C-i.partTarget,i.targetduration*1.5);if(F>0){if(C>i.targetduration*3)this.log(`Playlist last advanced ${P.toFixed(2)}s ago. Omitting segment and part directives.`),T=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&C-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${F} with playlist age: ${i.age}`),F=0;else{const V=Math.floor(F/i.targetduration);if(T+=V,v!==void 0){const $=Math.round(F%i.targetduration/i.partTarget);v+=$}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${P.toFixed(2)}s goal: ${F} skip sn ${V} to part ${v}`)}i.tuneInGoal=F}if(S=this.getDeliveryDirectives(i,t.deliveryDirectives,T,v),x||!L){i.requestScheduled=o,this.loadingPlaylist(u,S);return}}else(i.canBlockReload||i.canSkipUntil)&&(S=this.getDeliveryDirectives(i,t.deliveryDirectives,T,v));S&&T!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(y-l*2,y/2)),this.scheduleLoading(u,S,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),a=i.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const o=a-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Gr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Ps.No),new Vr(s,i,r)}checkRetry(e){const t=e.details,s=Ms(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(r===Re.RetryRequest||!i.resolved&&r===Re.SendAlternateToPenaltyBox);if(l){var c;if(a>=o.maxNumRetry)return!1;if(s&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var h;const u=Jt((h=e.response)==null?void 0:h.code);if(this.clearTimer(),u)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const d=er(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),d)}}e.levelRetry=!0,i.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),Jt(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function Ao(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!ls(n[t].attrs,e[t].attrs))return!1;return!0}function ls(n,e,t){const s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}class pu extends yr{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>ns(d.groupId,s));if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=at(l,o,_t);if(d>-1)r=o[d];else{const f=at(l,this.tracks);r=this.tracks[f]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===se.AUDIO_TRACK&&t.context.id===this.trackId&&ns(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Dt(e,i,_t))return i;const r=at(e,this.tracksInGroup,_t);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in e&&e.flushImmediate),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=kc(e,t.levels,s,a,_t);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=at(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e,t=!0){const s=this.tracksInGroup;if(e<0||e>=s.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,r=s[e],a=r.details&&!r.details.live;if(e===this.trackId&&r===i&&a||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,j(j({},r),{},{flushImmediate:t})),a))return;const o=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||Dt(e,i,_t)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const h=t[c];if(Dt({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,_t))return c}for(let c=0;c<t.length;c++){const h=t[c];if(ls(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const h=t[c];if(ls(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&$s(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class yu{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;s==="async-blocker"||s==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):s==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
23
|
+
${this.list("video")}
|
|
24
|
+
${this.list("audio")}
|
|
25
|
+
${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const _n=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Io="HlsJsTrackRemovedError",Eu=.25,Tu=.001;class Su extends Error{constructor(e){super(e),this.name=Io}}class vu extends Ge{constructor(e,t){super("buffer-controller",e.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=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(ce(r,"sourceopen",this._onMediaSourceOpen),ce(i,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const s=this.media.error,{appendError:i,appendErrors:r}=this;let a=!1;!i&&s&&(a=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry);const o=new Error(`MediaSource closed while media attached${Pn(a,s)}`);this.warn(o),this.hls.trigger(p.ERROR,ue({fatal:a},i,{type:q.MEDIA_ERROR,details:R.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this._onMediaError=()=>{const{media:s}=this;if(s){var i,r;this.log(`Media error (code: ${(i=s.error)==null?void 0:i.code}): ${(r=s.error)==null?void 0:r.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=Al(xt(e.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:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this),e.off(p.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===t?ue(s,i.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(s[a]=ue({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=xt(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,Dn(s),xu(s,o),s.load()}catch{s.src=o}else s.src=o}he(s,"emptied",this._onMediaEmptied),he(s,"error",this._onMediaError),this.appendSource&&he(s,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),he(e,"sourceopen",this._onMediaSourceOpen),he(e,"sourceended",this._onMediaSourceEnded),he(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(he(e,"startstreaming",this._onStartStreaming),he(e,"endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
26
|
+
required tracks: ${fe(s,(l,c)=>l==="initSegment"?void 0:c)};
|
|
27
|
+
transfer tracks: ${fe(i,(l,c)=>l==="initSegment"?void 0:c)}}`),!ua(i,s)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,c=this.details,h=Math.max(l,c?.fragments[0].start||0);if(h-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${l}`),this.onMediaDetaching(p.MEDIA_DETACHING,{}),this.onMediaAttaching(p.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(l=>{const c=l,h=i[c];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const y=X.getBuffered(u);d.detectEvictedFragments(c,y,f,null,null,!0)}const g=gi(c),m=[c,u];this.sourceBuffers[g]=m,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const l=r.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),r.removeSourceBuffer(l[c]);o&&r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}ce(r,"sourceopen",this._onMediaSourceOpen),ce(r,"sourceended",this._onMediaSourceEnded),ce(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ce(r,"startstreaming",this._onStartStreaming),ce(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(ce(i,"emptied",this._onMediaEmptied),ce(i,"error",this._onMediaError),ce(i,"seeking",this._onStartStreaming),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&Dn(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[gi(e)]=[null,null];const t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new yu(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(l=>!i[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(l=>{var c,h;const u=t[l],{id:d,codec:f,levelCodec:g,container:m,metadata:y,supplemental:E}=u;let S=i[l];const T=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],v=T!=null&&T.buffer?T:S,x=v?.pendingCodec||v?.codec,A=v?.levelCodec;S||(S=i[l]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:m,levelCodec:g,metadata:y,id:d});const I=Ds(x,A),b=I?.replace(_n,"$1");let _=Ds(f,g);const L=(h=_)==null?void 0:h.replace(_n,"$1");_&&I&&b!==L&&(l.slice(0,5)==="audio"&&(_=Ns(_,this.appendSource)),this.log(`switching codec ${x} to ${_}`),_!==(S.pendingCodec||S.codec)&&(S.pendingCodec=_),S.container=m,this.appendChangeType(l,m,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,H.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>i||X.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,i)||((l=this.fragmentTracker.getAppendedFrag(i,H.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:a,frag:o,part:l,chunkMeta:c,offset:h}=t,u=c.buffering[r],d=Ee(o)&&!l&&!o.gap&&!c.partial&&!c.iframe;let f=null,g=!1;const{sn:m,cc:y}=o,E=self.performance.now();u.start=E;const S=o.stats.buffering,T=l?l.stats.buffering:null;S.start===0&&(S.start=E),T?.start===0&&(T.start=E);const v=s.audio;let x=!1;r==="audio"&&v?.container==="audio/mpeg"&&(x=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const A=s.video,I=A?.buffer;if(I&&m!=="initSegment"&&h!==void 0){const L=v?.buffer,P=l||o;if(r==="audio"&&a!=="main"&&!(A.ending||A.ended)&&L&&X.getBuffered(L).length){const F=P.start+P.duration*.05,V=X.getBuffered(I),$=this.currentOp("video");!V.length&&!$?this.blockAudio(P):!X.isBuffered(I,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(P)}else if(r==="video"){const C=P.end,F=this.lastVideoAppendEnd-C;this.lastVideoAppendEnd=C,F<0||F>P.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const b=(l||o).start,_={label:`append-${r}`,execute:()=>{var L;u.executeStart=self.performance.now();const P=(L=this.tracks[r])==null?void 0:L.buffer;P&&(d&&(f=X.timeRangesToArray(X.getBuffered(P)),g=kn(mi(f,o),o)),x?this.updateTimestampOffset(P,b,.1,r,m,y):h!==void 0&&B(h)&&this.updateTimestampOffset(P,h,1e-6,r,m,y)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const L=self.performance.now();u.executeEnd=u.end=L,S.first===0&&(S.first=L),T?.first===0&&(T.first=L);const P={};if(this.sourceBuffers.forEach(([C,F])=>{C&&(P[C]=X.getBuffered(F))}),d){const C=this.getFragmentAppendProgress(o),F=P[r];if(F&&f){const V=X.timeRangesToArray(F),$=mi(V,o);C.progressed||(C.progressed=$-mi(f,o)>Tu);const k=g&&kn($,o);C.fullyBuffered[r]=(C.fullyBuffered[r]===void 0||C.fullyBuffered[r])&&k}}this.hls.trigger(p.BUFFER_APPENDED,{type:r,frag:o,part:l,chunkMeta:c,parent:a,timeRanges:P})},onError:L=>{var P;this.clearBufferAppendTimeoutId(this.tracks[r]);const C=L.code===DOMException.QUOTA_EXCEEDED_ERR||L.name=="QuotaExceededError"||"quota"in L;if(C&&!this._quotaEvictionPending[r]){const k=this.getBackBufferEvictionTarget(r,i.byteLength,o.type);if(k>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${m} - evicting back buffer to ${k.toFixed(3)}s and retrying`);const w=this.getFlushOp(r,0,k),O=this.getClearEvictionPendingOp(r);this.insertNext([w,_,O],r);return}this.warn(`QuotaExceededError on "${r}" sn: ${m} - no back buffer available to evict`)}d&&(this.getFragmentAppendProgress(o).errored=!0);const F={type:q.MEDIA_ERROR,parent:a,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:l,chunkMeta:c,error:L,err:L,fatal:!1},V=(P=this.media)==null?void 0:P.error;if(L.name===Io&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))F.errorAction=jt(!0);else{var $;C&&(F.details=R.BUFFER_FULL_ERROR);const k=++this.appendErrors[r],w=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${k}/${w+1} times to append segment in "${r}" sourceBuffer with error: ${L.message}`),k>=w&&(F.fatal=!C);const O=($=this.mediaSource)==null?void 0:$.readyState;(O==="ended"||O==="closed"||V)&&(this.warn(`MediaSource readyState "${O}" during SourceBuffer${Pn(F.fatal,V)}`),F.details=R.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=F,this.hls.trigger(p.ERROR,F),C&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${r}" append sn: ${m}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${y} offset: ${h} bytes: ${i.byteLength}`),this.append(_,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{var i;const r=(i=this.tracks[e])==null?void 0:i.buffer;this.log(`Remove request ${t}-${s} from ${e} Source Buffer complete > buffer: ${r?Hs(X.getBuffered(r)):"(detached)"}`),this.hls.trigger(p.BUFFER_FLUSHED,{type:e,start:t,end:s})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i),this.hls.trigger(p.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;(!s||s==="audio")&&this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,r),a)})}onFragParsed(e,t){const{frag:s,part:i,chunkMeta:r}=t,a=[],o=i?i.elementaryStreams:s.elementaryStreams;o[de.AUDIOVIDEO]?a.push("audiovideo"):(o[de.AUDIO]&&a.push("audio"),o[de.VIDEO]&&a.push("video"));const l=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const h=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,a),this.hls&&(this.hls.trigger(p.FRAG_BUFFERED,{frag:s,part:i,stats:h,id:s.type,chunkMeta:r}),!i&&s.gap&&h.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${h.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(l,a).catch(c=>{this.warn(`Fragment buffered callback ${c.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const{backBufferLength:a,frontBufferFlushThreshold:o}=r;this.trimBuffers(o,a,t.frag,t.previousFrag);const l=t.frag.elementaryStreams,{appendErrors:c}=this,h=(i=this.appendError)==null?void 0:i.sourceBufferName;Object.keys(l).forEach(u=>{l[u]&&(c[u]=0,u===h&&(this.appendError=void 0),u==="audio"||u==="video"?(c.audiovideo=0,h==="audiovideo"&&(this.appendError=void 0)):(c.audio=0,c.video=0,h!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(a?.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(p.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(p.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;B(i)&&i!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,s){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,t):0}getFragmentAppendProgress(e){var t;const s=Cn(e);let i=this.fragmentAppendProgress[s];return((t=i)==null?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(e,t,s,i){if(t||!Ee(e)||e.gap||s.iframe||s.partial)return;const r=Cn(e),a=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const o=e.stats.buffering;if(o.start&&!o.first)return;const l=a?.stats===e.stats?a:void 0;if(l!=null&&l.errored)return;const c=i.length>0&&i.every(f=>l?.fullyBuffered[f]===!0);if(l!=null&&l.progressed||c){delete this.appendsWithoutProgress[r];return}if(!l&&i.length===0)return;const h=(this.appendsWithoutProgress[r]||0)+1,u=this.hls;h>=u.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=h,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${h} time${h>1?"s":""} without buffered range growth`),u.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:s,parent:e.type,appendsWithoutProgress:h,error:new Error(`Fragment append did not increase buffered coverage (${h})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,s,i){const{hls:r,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;const l=r.config,c=o.currentTime,h=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let u=-1/0;if(B(t)&&t>=0){const d=Math.max(t,h);u=Math.floor(c/h)*h-d}if(s){const d=this.getLoopBackBufferFlushEnd(s,i??null);d>0&&(u=Math.max(u,d))}if(u>0&&this.flushBackBuffer(c,h,u),B(e)&&e>0){const d=Math.max(l.maxBufferLength,e),f=Math.max(d,h),g=Math.floor(c/h)*h+f;this.flushFrontBuffer(c,h,g)}}getLoopBackBufferFlushEnd(e,t){var s;const{media:i}=this;if(((s=this.hls)==null?void 0:s.config.loopBackBufferFlush)===!1||!(i!=null&&i.loop)||!t||e.level<=t.level)return 0;const{video:r,audiovideo:a}=e.elementaryStreams;if(r!=null&&r.partial||a!=null&&a.partial)return 0;const o=this.getEarliestElementaryStreamStart(e)-Eu;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){const{audio:t,video:s,audiovideo:i}=e.elementaryStreams;let r=e.start;return i?r=Math.min(r,i.startDTS):(t&&(r=Math.min(r,t.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const c=X.getBuffered(r);if(c.length>0&&s>c.start(0)){var a,o,l;this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:s});const h=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(h!=null&&h.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const a=X.getBuffered(r),o=a.length;if(o<2)return;const l=a.start(o-1),c=a.end(o-1);if(s>l||e>=l&&e<=c)return;this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart),h=Math.max(c,i);return{duration:1/0,start:c,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return B(r)?{duration:r}:null;const a=this.media.duration,o=B(s.duration)?s.duration:0;return i>o&&i>a||!B(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!i||!this.media||i.readyState!=="open"||(i.duration!==e&&(B(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${fe(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(p.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const a=r,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(a)?" Queued":""} ${fe(o)}`);try{const h=s.addSourceBuffer(c),u=gi(a),d=[a,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:c,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&ss(s,"video")&&(i=gc(i,s));const r=Ds(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Ns(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&(this.log(`${r} buffer removed ${Hs(o)}`),this.hls.trigger(p.BUFFER_FLUSHED,{type:r,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,s;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);if(!i)return;if(i.onComplete(),(s=this.tracks[e])==null||(s=s.buffer)==null?void 0:s.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var s;const i=(s=this.mediaSource)==null?void 0:s.readyState,r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${i}`);this.error(`${r.message}`,t),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const a=this.currentOp(e);a&&a.onError(r)}updateTimestampOffset(e,t,s,i,r,a){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,a=this.tracks[e],o=a?.buffer;if(!i||!r||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const l=B(i.duration)?i.duration:1/0,c=B(r.duration)?r.duration:1/0,h=Math.max(0,t);if(h>=c){var u;(u=this.currentOp(e))==null||u.onComplete(),this.shiftAndExecuteNext(e);return}const d=Math.min(s,l,c);if(d>h&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),o.remove(h,d);else throw new Error(`Cannot remove ${d<=h?`invalid range (${h} >= ${d}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Su(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){const r=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,i,r),r)}i.appendBuffer(e)}appendTimeoutHandler(e,t,s){this.log(`Received timeout after ${s}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}const i=this.currentOp(e);i&&i.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Ha;this.details&&(t=this.details.levelTargetDuration);let s=2*t*1e3;if(this.media===null)return s;const i=X.bufferInfo(e,this.media.currentTime,0);return i.len?(s=Math.max(i.len*1e3,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,r=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(r).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const a=s.bind(this,e);i.listeners.push({event:t,listener:a}),he(r,t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{ce(s,i.event,i.listener)}),t.listeners.length=0)}}function Dn(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function xu(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function gi(n){return n==="audio"?1:0}function Pn(n,e){return`${n?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function Cn(n){return`${n.type}_${n.sn}_${n.level}`}function mi(n,e){const{start:t,end:s}=e;let i=0;for(let r=0;r<n.length;r++){const a=n[r];if(a.start>=s)break;const o=Math.max(t,a.start),l=Math.min(s,a.end);l>o&&(i+=l-o)}return i}function kn(n,e){return e.duration-n<=.05}class Er{constructor(e){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=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}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:e}=this;e&&(e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:e}=this;e&&(e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){const s=t.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&(B(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){const e=this.hls.levels;e.length>1&&e.some(t=>!!t.videoCodec)&&this.startCapping()}}}onBufferCodecs(e,t){t.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 e=this.hls.levels;if(e.length>1){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.observer||(this.clientRect=null),Er.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){const e=self.ResizeObserver;e&&(this.observer=new e(t=>{var s;const i=(s=t[0])==null?void 0:s.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.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 e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;const{ignoreDevicePixelRatio:t,maxDevicePixelRatio:s}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,s)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&i(l,e[o+1])){r=o;break}}return r}}var Fe=class Ui{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Ui?s:new Ui(s))),this.value=e,this.params=t}};const Au="Dict";function Iu(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function Lu(n,e,t,s){return new Error(`failed to ${n} "${Iu(e)}" as ${t}`,{cause:s})}const On="Bare Item",Ru="Boolean",bu="Byte Sequence",_u="Decimal",Du="Integer";function Pu(n){return n<-999999999999999||999999999999999<n}const Cu="String",ku=/[\x00-\x1f\x7f]+/;var Lo=class{constructor(n){this.description=n}};const Ou="Token",wu="Key";function lt(n,e,t){return Lu("serialize",n,e,t)}function Mu(n){if(typeof n!="boolean")throw lt(n,Ru);return n?"?1":"?0"}function Fu(n){if(ArrayBuffer.isView(n)===!1)throw lt(n,bu);return`:${Il(n)}:`}function Ro(n){if(Pu(n))throw lt(n,Du);return n.toString()}function Nu(n){return`@${Ro(n.getTime()/1e3)}`}function Bu(n){const e=da(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw lt(n,_u);const t=e.toString();return t.includes(".")?t:`${t}.0`}function $u(n){if(ku.test(n))throw lt(n,Cu);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Uu(n){return n.description||n.toString().slice(7,-1)}function wn(n){const e=Uu(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw lt(e,Ou);return e}function Gi(n){switch(typeof n){case"number":if(!B(n))throw lt(n,On);return Number.isInteger(n)?Ro(n):Bu(n);case"string":return $u(n);case"symbol":return wn(n);case"boolean":return Mu(n);case"object":if(n instanceof Date)return Nu(n);if(n instanceof Uint8Array)return Fu(n);if(n instanceof Lo)return wn(n);default:throw lt(n,On)}}function Vi(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw lt(n,wu);return n}function Tr(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${Vi(e)}`:`;${Vi(e)}=${Gi(t)}`).join("")}function bo(n){return n instanceof Fe?`${Gi(n.value)}${Tr(n.params)}`:Gi(n)}function Gu(n){return`(${n.value.map(bo).join(" ")})${Tr(n.params)}`}function Vu(n,e={whitespace:!0}){if(typeof n!="object"||n==null)throw lt(n,Au);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Fe||(r=new Fe(r));let a=Vi(i);return r.value===!0?a+=Tr(r.params):(a+="=",Array.isArray(r.value)?a+=Gu(r):a+=bo(r)),a}).join(`,${s}`)}function _o(n,e){return Vu(n,e)}const Ku=["url"],Hu=["version","eventTargets","sid","transmissionMode"],Yu=["customData","headers"],Mn=n=>n instanceof Fe?new Fe(Math.round(n.value),n.params):Math.round(n),pi=n=>Array.isArray(n)?n.map(Mn):Mn(n),Ki=(n,e)=>Array.isArray(n)?n.map(t=>Ki(t,e)):n instanceof Fe&&typeof n.value=="string"?new Fe(Ki(n.value,e),n.params):(e.baseUrl&&(n=_l(n,bl(e.baseUrl))),e.version===1?encodeURIComponent(n):n),Fn=n=>n instanceof Fe?new Fe(Math.round(n.value/100)*100,n.params):Math.round(n/100)*100,vs=n=>Array.isArray(n)?n.map(Fn):Fn(n),Wu=(n,e)=>{let t=n;return e.version>=2&&(n instanceof Fe&&typeof n.value=="string"?t=new Fe([n]):typeof n=="string"&&(t=[n])),Ki(t,e)},qu={br:pi,d:pi,bl:vs,dl:vs,mtp:vs,nor:Wu,rtp:vs,tb:pi},cs=2,Do="bc",ju="ps",Po="pr",zu="e",Nn="t",Xu="c",Co="b",Sr="rr",ko="ce",xs={BITRATE_CHANGE:Do,ERROR:zu,RESPONSE_RECEIVED:Sr,CUSTOM_EVENT:ko},Oo=new Map([[ju,"sta"],[Po,"pr"],[Xu,"cid"],[Co,"bg"],[Do,"br"]]),vr="event",xr="request",wo=["cen","e","h","ts"],Mo=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Qu=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ar(n){return Qu.test(n)}const Zu=new Set(Mo);function Fo(n){return Zu.has(n)||Ar(n)}const No=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Ju=new Set(No);function Bo(n){return Ju.has(n)}const ed=new Set(wo);function td(n){return Fo(n)||Bo(n)||ed.has(n)}const sd=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Js=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],id=new Set(Js);function rd(n){return id.has(n)||Ar(n)}const nd=new Set(["ot","sf","st","e","sta"]);function ad(n){return nd.has(n)}function od(n){return typeof n=="number"?B(n):n!=null&&n!==""&&n!==!1}const ld={[vr]:td,[xr]:Fo};function $o(n,e){if(Array.isArray(n)){let t;return e&&(t=n.find(s=>{var i;return((i=s.params)==null?void 0:i.ot)===e})),t||(t=n[0]),$o(t)}return n instanceof Fe?n.value:n}function cd(n){const e={};for(const[s,i]of Object.entries(n)){if(i==null){e[s]=i;continue}if(s==="nor"){const r=(Array.isArray(i)?i:[i])[0];if(r instanceof Fe){var t;e.nor=r.value,(t=r.params)!=null&&t.r&&(e.nrr=r.params.r)}else e.nor=r}else sd.has(s)?e[s]=$o(i,n.ot):e[s]=i}return e}function Uo(n,e={}){const t={};if(n==null||typeof n!="object")return t;const s=e.version||n.v||cs,i=e.reportingMode||xr,r=s===1?cd(n):n,a=s===1?rd:ld[i];let o=Object.keys(r).filter(a);r.e&&r.e!==Sr&&(o=o.filter(f=>!Bo(f)));const l=e.filter;typeof l=="function"&&(o=o.filter(l));const c=i===vr;if(c){const f=r.e;!o.includes("e")&&f!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&r.cen!=null&&f===ko&&o.push("cen");const g=f?Oo.get(f):void 0;g&&r[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return t;s>1&&!o.includes("v")&&o.push("v");const h={version:s,reportingMode:i,baseUrl:e.baseUrl};o.sort();for(const f of o){var u,d;let g=r[f];const m=(u=(d=e.formatters)==null?void 0:d[f])!=null?u:qu[f];if(typeof m=="function"&&(g=m(g,h)),f==="v"){if(s===1)continue;g=s}if(f==="pr"&&g===1&&!(c&&r.e===Po))continue;c&&f==="ts"&&!B(g)&&(g=Date.now());const y=c&&g===!1&&f==="bg"&&r.e===Co;!od(g)&&!y||(ad(f)&&typeof g=="string"&&(g=new Lo(g)),t[f]=g)}return t}const dt="CMCD-Object",Me="CMCD-Request",Ot="CMCD-Session",qe="CMCD-Status",hd={REQUEST:Me},ud={ab:dt,br:dt,d:dt,lab:dt,lb:dt,ot:dt,tab:dt,tb:dt,tpb:dt,bl:Me,cs:Me,dfa:Me,dl:Me,ltc:Me,mtp:Me,nor:Me,nrr:Me,pb:Me,sn:Me,sta:Me,su:Me,tbl:Me,cid:Ot,msd:Ot,sf:Ot,sid:Ot,st:Ot,v:Ot,bg:qe,bs:qe,bsa:qe,bsd:qe,bsda:qe,cdn:qe,ec:qe,nr:qe,pr:qe,pt:qe,rtp:qe};function dd(n){return Object.keys(n).reduce((e,t)=>{var s;return(s=n[t])==null||s.forEach(i=>e[i]=t),e},{})}function fd(n,e){const t={};if(!n)return t;const s=Object.keys(n),i=e?dd(e):{};for(const a of s){var r;const o=ud[a]||i[a]||hd.REQUEST,l=(r=t[o])!=null?r:t[o]={};l[a]=n[a]}return t}function gd(n,e){const t={},s=fd(n,e);for(const[i,r]of Object.entries(s)){const a=_o(r,{whitespace:!1});a&&(t[i]=a)}return t}const Bn="CMCD";function Go(n){return _o(n,{whitespace:!1})}function md(n,e={}){return n?Go(Uo(n,e)):""}const pd=30,Hi=[...Js,...Mo,...No,...wo].filter((n,e,t)=>t.indexOf(n)===e),yd="application/cmcd",Ed=1,_e={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},je={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},Ir="query",Vo="headers";function $n(n,e,t){var s;const i=new Set((s=e.enabledKeys)!=null?s:[]);return{version:e.version||cs,reportingMode:n,filter:r=>i.has(r),baseUrl:t}}function Td(n,e){if(n===e)return!0;if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++){const s=n[t],i=e[t];if(s===i)continue;if(typeof s=="number"||typeof i=="number"||s.value!==i.value)return!1;const r=s.params,a=i.params,o=r&&Object.keys(r)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&r&&a&&r[o]!==a[l])return!1}return!0}const Sd=Object.is,vd=n=>n,Ko=Array.from(Oo,([n,e])=>e==="br"?{event:n,field:e,equal:(t,s)=>t===void 0||s===void 0?t===s:Td(t,s),snapshot:t=>t.slice()}:{event:n,field:e,equal:Sd,snapshot:vd}),xd=new Map(Ko.map(n=>[n.event,n]));function Ad(n){const{url:e}=n,t=Xs(n,Ku);return fetch(e,t)}function Id(n){const{version:e=cs,eventTargets:t=[],sid:s=fa(),transmissionMode:i=Ir}=n,r=Xs(n,Hu);return j(j({},r),{},{version:e,transmissionMode:i,sid:s,eventTargets:t.reduce((a,o)=>{var l,c,h;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||cs,enabledKeys:((c=o.enabledKeys)==null?void 0:c.slice())||[],url:o.url,events:o.events.slice(),interval:(h=o.interval)!=null?h:pd,batchSize:o.batchSize||1}),a},[])})}var Ld=class{constructor(n,e=Ad){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=Id(n),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const s of this.config.eventTargets)this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((n,e)=>{if(this.disarmInterval(n),e.interval===0||!e.events.includes(Nn))return;const t=()=>{this.recordTargetEvent(n,e,Nn),this.processEventTargets()};n.intervalId=setInterval(t,e.interval*1e3),t()})}stop(n=!1){n&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(n){n.sid&&n.sid!==this.data.sid&&this.resetSession(),n.msd&&!isNaN(n.msd)&&(this.msd=n.msd),this.data=j(j(j({},this.data),n),{},{msd:void 0});for(const e of Ko)e.field in n&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(n,e={}){const t=xd.get(n);if(t){const s=t.field,i=e[s];i!==void 0&&ue(this.data,{[s]:i});const r=this.data[s];if(r===void 0||t.equal(r,this.lastEmitted[s]))return;ue(this.lastEmitted,{[s]:t.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,n,e)}),this.processEventTargets()}recordTargetEvent(n,e,t,s={}){var i;if(!e.events.includes(t))return;const r=j(j(j({},this.data),s),{},{e:t,ts:(i=s.ts)!=null?i:Date.now(),sn:n.sn++});!isNaN(this.msd)&&!n.msdSent&&(r.msd=this.msd,n.msdSent=!0),n.queue.push(r)}recordResponseReceived(n,e={}){var t,s,i;const{request:r}=n,a=(t=e.url)!=null?t:r?.url;if(!a)return;const o=new URL(a);o.searchParams.delete(Bn);const l={url:o.toString(),rc:n.status},c=n.resourceTiming;c&&(c.startTime!=null&&(l.ts=Math.round(this.timeOrigin+c.startTime),c.responseStart!=null&&(l.ttfb=Math.round(c.responseStart-c.startTime))),c.duration!=null&&(l.ttlb=Math.round(c.duration)));const h=(s=(i=r.customData)==null?void 0:i.cmcd)!=null?s:{};this.recordEvent(Sr,j(j(j({},h),l),e))}applyRequestReport(n){var e;return(e=this.createRequestReport(n))!=null?e:n}isRequestReportingEnabled(){var n;return!!((n=this.config.enabledKeys)!=null&&n.length)}createRequestReport(n,e){var t;const{customData:s={},headers:i={}}=n,r=Xs(n,Yu),a=j(j({},r),{},{headers:j({},i),customData:j(j({},s),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;const o=new URL(a.url),l=j(j(j({},this.data),e),{},{sn:this.requestTarget.sn++}),c=$n(xr,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);const h=a.customData.cmcd=Uo(l,c);switch(this.config.transmissionMode){case Ir:const u=Go(h);u&&(o.searchParams.set(Bn,u),a.url=o.toString());break;case Vo:ue(a.headers,gd(h,c.customHeaderMap));break}return a}processEventTargets(n=!1){let e=!1;this.eventTargets.forEach((t,s)=>{const{queue:i}=t;if(!i.length||i.length<s.batchSize&&!n)return;const r=n?i.length:s.batchSize,a=i.splice(0,r);this.sendEventReport(s,a).catch(()=>{t.queue.unshift(...a)}),e||(e=i.length>0)}),e&&this.processEventTargets()}async sendEventReport(n,e){const t=$n(vr,n),{status:s}=await this.requester({url:n.url,method:"POST",headers:{"Content-Type":yd},body:e.map(i=>md(i,t)).join(`
|
|
28
|
+
`)+`
|
|
29
|
+
`});if(s===410)this.disposeEventTarget(n);else if(s===429||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(n){clearInterval(n.intervalId),n.intervalId=void 0}disposeEventTarget(n){const e=this.eventTargets.get(n);e&&(this.disarmInterval(e),this.eventTargets.delete(n))}resetSession(){this.eventTargets.forEach(n=>n.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const Rd={HLS:"h"},yi={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function bd(n,e){return new Fe(n,e)}new Set(Js);new Set(Hi);const _d=["includeKeys"];function Un(n){return Object.keys(n).every(Ar)}class Dd{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(je.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(je.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(je.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(je.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(je.SEEKING)},this.onSeeked=()=>{var i;this.initialized&&(i=this.media)!=null&&i.paused&&this.setPlayerState(je.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=i=>{try{this.apply(i,{ot:_e.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:o,part:l}=i,c=this.hls.levels[o.level],h=this.getObjectType(o,c),u={d:(l||o).duration*1e3,ot:h};if(h===_e.VIDEO||h===_e.AUDIO||h===_e.MUXED||h==null&&(o.type==="main"||o.type==="audio")){var r;const f=c.bitrate/1e3;u.br=[f];const{cmcd:g}=this.config,m=(r=g?.rtpSafetyFactor)!=null?r:5;if(u.rtp=Math.round(f*m/100)*100,h===_e.MUXED||h==null&&o.type==="main"){const S=this.getTopBandwidth()/1e3;B(S)&&(u.tb=[S]);const T=this.getLowestBandwidth()/1e3;B(T)&&(u.lb=[T])}const y=this.getBufferLength(o);if(B(y)){var a;u.bl=[y];const S=((a=this.media)==null?void 0:a.playbackRate)||1;u.dl=Math.round(y/S/100)*100}this.playheadLevel&&(u.pb=[this.playheadLevel.bitrate/1e3]);const E=this.hls.maxAutoLevel;if(E>=0){const S=this.hls.levels[E];S&&(u.tpb=[S.bitrate/1e3])}}const d=l?this.getNextPart(l):this.getNextFrag(o);d!=null&&d.url&&d.url!==o.url&&(d.byteRange.length>0?u.nor=[bd(d.url,{r:`${d.byteRange[0]}-${d.byteRange[1]}`})]:u.nor=[d.url]),this.apply(i,u)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(i,r,a)=>{var o;const{cmcd:l}=this.config,c=l==null||(o=l.eventTargets)==null?void 0:o.some(h=>{var u;return(u=h.events)==null?void 0:u.includes(xs.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!c))try{this.reporter.recordResponseReceived({request:{url:i},status:r.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(h){this.hls.logger.warn("Could not record fragment response CMCD data.",h)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;const{cmcd:s}=this.config;if(s==null)return;const i=s.version||Ed;if(this.reporter=new Ld({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:s.useHeaders===!0?Vo:Ir,enabledKeys:(e=s.includeKeys)!=null?e:[...i>=cs?Hi:Js],eventTargets:((t=s.eventTargets)!=null?t:[]).map(r=>{let{includeKeys:a}=r,o=Xs(r,_d);return j(j({},o),{},{enabledKeys:a??Hi})})},s.loader),this.reporter.update({sf:Rd.HLS,sta:this.playerState}),s.reporterCallback){const r=this.reporter,a={updateCustomData:o=>{Un(o)&&r.update(o)},recordCustomEvent:(o,l={})=>{Un(l)&&r.recordEvent(xs.CUSTOM_EVENT,j({cen:o},l))}};s.reporterCallback(a)}this.reporter.start()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(p.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(p.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const e=this.hls;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(p.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(p.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){const s=this.media=t.media;this.setPlayerState(this.media.autoplay?je.STARTING:je.PRELOADING),he(s,"waiting",this.onWaiting),he(s,"play",this.onPlay),he(s,"playing",this.onPlaying),he(s,"pause",this.onPause),he(s,"seeking",this.onSeeking),he(s,"seeked",this.onSeeked),he(s,"ratechange",this.onRateChange)}onMediaDetached(){const e=this.media;e&&(ce(e,"waiting",this.onWaiting),ce(e,"play",this.onPlay),ce(e,"playing",this.onPlaying),ce(e,"pause",this.onPause),ce(e,"seeking",this.onSeeking),ce(e,"seeked",this.onSeeked),ce(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(je.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(je.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(je.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(xs.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var s;if(!this.reporter)return;const i={br:[t.bitrate/1e3]},r=(s=t.details)==null?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,t)),this.reporter.recordEvent(xs.BITRATE_CHANGE,i)}onLevelSwitched(e,t){const s=this.hls.levels[t.level];s&&(this.playheadLevel=s)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){const e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?yi.LOW_LATENCY:yi.LIVE:yi.VOD}apply(e,t={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(s=this.media)==null?void 0:s.playbackRate,st:this.getStreamType()});const i=t.ot===_e.INIT||t.ot===_e.VIDEO||t.ot===_e.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const r=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=r.url,e.headers=r.headers}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:a}=i;for(let o=r.length-1;o>=0;o--){const l=r[o];if(l.index===s&&l.fragment.sn===a)return r[o+1]}}}getObjectType(e,t){const{type:s}=e;if(s==="subtitle")return _e.TIMED_TEXT;if(e.sn==="initSegment")return _e.INIT;if(s==="audio")return _e.AUDIO;if(s==="main"){if(e.hasStreams){const i=e.elementaryStreams;if(i.audiovideo)return _e.MUXED;if(i.video)return _e.VIDEO;if(i.audio)return _e.AUDIO}if(t){const{audioCodec:i,videoCodec:r}=t;if(!this.hls.audioTracks.length){if(i&&r)return _e.MUXED;if(i)return _e.AUDIO}if(r)return _e.VIDEO}}}getTopBandwidth(){let e=0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),B(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;const t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;const e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;const s=e||t;return s?s.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;const s=this.getEventBufferLength();B(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=this.recordFragmentResponse,i=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new i(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);const{onSuccess:c}=l;this.loader.load(a,o,j(j({},l),{},{onSuccess:(h,u,d,f)=>{c(h,u,d,f),s(a.url,h,u)}}))}}}}const Pd=3e5;class Cd extends Ge{constructor(e){super("content-steering",e.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=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);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(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}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(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===Re.SendAlternateToPenaltyBox&&s.flags&Le.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a,!s.resolved&&(t.details!==R.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${fe(r)} penalized: ${fe(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Pd&&delete s[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,to(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===se.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===se.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new pe(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const g=Ho(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new rs({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)m.addGroupId("audio",`${h.audioGroups[y]}_clone_${a}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)m.addGroupId("text",`${h.subtitleGroups[y]}_clone_${a}`);return m});t.push(...c),Gn(this.audioTracks,s,l,a),Gn(this.subtitleTracks,i,l,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;St(i,"_HLS_pathway",this.pathwayId),St(i,"_HLS_throughput",""+h)}const r={type:se.STEERING_MANIFEST,responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.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":m,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=g;if(m)try{this.uri=new self.URL(m,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const S={steeringManifest:g,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,S),E&&this.updatePathwayPriority(E)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const m=this.loader;if(typeof m?.getResponseHeader=="function"){const y=m.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Gn(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=ue({},a);return o.details=void 0,o.attrs=new pe(o.attrs),o.url=o.attrs.URI=Ho(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Ho(n,e,t,s){if(e){const{[t]:o}=s;if(o){const l=o[e];if(l)return l}}const{HOST:i,PARAMS:r}=s,a=new self.URL(n);return i&&(a.hostname=i),r&&Object.keys(r).sort().forEach(o=>{o&&St(a,o,r[o])}),a.href}class kd{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new dr,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((e,t)=>{this.emitter.on("error",t),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();const e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class ze extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}class Ft extends Ge{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=Ft.CDMCleanupPromise?[Ft.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.log(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Gt(this.config));const o=a.map(li).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o;const l=Es(a),c=this.activeLevelKeys();if(l===me.FAIRPLAY&&s==="sinf")try{const g=Ze(new Uint8Array(i)),m=ir(JSON.parse(g).sinf),y=Ia(m);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(y.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}else if(l===me.PLAYREADY)o=hr(new Uint8Array(i));else if(l===me.WIDEVINE){const g=_a(i).filter(m=>m.systemId===qa.WIDEVINE);if(g.length){var h;const m=g[0];o=(h=m.kids)!=null&&h.length?m.kids[0]:null}}let u;if(o){const g=Ie(o);for(let m=0;m<c.length;m++){const y=c[m];if(y.keyId&&(Gs(o,y.keyId)||y.uri.replace(/-/g,"").indexOf(g)!==-1)){y.pssh||(y.scheme=s,y.pssh=new Uint8Array(i),y.keyId=o,gt.setKeyIdForUri(y.uri,o)),u=this.getSessionForKey(y,"encrypted-event-key-match");break}}}if(!u){if(c.length){var d,f;return(d=c[0]).scheme||(d.scheme=s),(f=c[0]).pssh||(f.pssh=new Uint8Array(i)),this.getSessionForKey(c[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ie(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return u}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));const t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,i,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof ze?o(u):o(new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return ja===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=Jc(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${fe(r)}`),o=this.requestMediaKeySystemAccess(e,r);const l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then(c=>{this.throwIfDestroyed(),this.log(`Access for key-system "${c.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=l.mediaKeys=c.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,s,i){const{mediaKeySessions:r}=this,a=` key-session "${e}" keyId: ${Ie(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let c=0;c<r.length;c++){const h=r[c];if(!h.initialized&&h.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${a}`),h}this.log(`Creating${a}`);const o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(l),l}resetMediaKeys(){var e;const t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,s=this.keySystemAccessPromises[t];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,s){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ie(t.keyId||[])}
|
|
30
|
+
} (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>li(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{const s=li(t);if(!s)throw new Error(`Unable to find format for key-system "${t}"`);return s})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Gt(this.config),s=e.map(Es).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}loadClear(e,t,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const a=t[i];if(e.cc<=a.cc&&(!Ee(e)||!Ee(a)||e.sn<a.sn)||!s&&i==r-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);const l=Es(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const i=Gt(this.config);if(i.length)return this.getKeySystemAccess(i)}}return null}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=Ei(e,t[s]);if(i)return i}}loadKey(e){const t=e.decryptdata,s=this.getKeyStatus(t);if(s==="internal-error"){const o=Vn(s,t);return o.data.frag=e,this.error(`${o.message} (${Ie(t.keyId||[])})`),Promise.reject(o)}const i=e.type,r=this.activeKeys,a=r[i];a&&!t.matches(a.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(a),delete r[i]),r[i]||(r[i]=e);for(let o=this.mediaKeySessions.length;o--;){const l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[Ie(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,s){const i=this.getSessionForKey(e,t);return i.catch(r=>this.handleError(r,s)),i.then(r=>e)}getSessionForKey(e,t){const s=this.findContextForKey(e);if(s!==void 0)return Promise.resolve(s);const i=e.uri,r=this.sessionSetupByUri[i];let a;r===void 0?a=this.resolveSessionForKey(e,t):a=r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[i]=a;const o=()=>{this.sessionSetupByUri[i]===a&&delete this.sessionSetupByUri[i]};return a.then(o,o),a}findContextForKey(e){const{mediaKeySessions:t}=this;for(let s=t.length;s--;){const i=t[s];if(Ei(e,i))return i}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let r=this.mediaKeySessions.length;r--;){const a=this.mediaKeySessions[r];if(Ei(e,a))return a;const o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,e,t))).then(r=>{this.throwIfDestroyed();const a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(r,e,a,o,t)})})}getUsableKeyPromise(e,t,s){const i=e.keyRequests[t.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${Md(t)} format: "${t.keyFormat}" URI: ${t.uri})`),i.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof ze){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ie(s.keyId||[])})`:""}`),this.hls.trigger(p.ERROR,e.data)}else this.error(e.message),this.hls.trigger(p.ERROR,{type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Es(e.keyFormat),s=t?[t]:Gt(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(e){if(e.length||(e=Gt(this.config)),e.length===0)throw new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${fe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){const e=this.activeKeys,t=(e.previous||[]).map(s=>s.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}filterInitData(e,t,s,i,r){var a;const o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const c=o.call(this.hls,s,i,ue({},e,{decryptdata:t,reason:r}),r);if(!c)throw new Error("Invalid response from configured generateRequest filter");t.scheme=c.initDataType?c.initDataType:"cenc";const h=c.initData?c.initData:null;return t.pssh=h?new Uint8Array(h):null,c}catch(c){var l;if(this.warn(c.message),(l=this.hls)!=null&&l.config.debug)throw c}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(e,t,s,i,r){const a=this.getUsableKeyPromise(e,t,r);if(a)return a;const o=this.filterInitData(e,t,s,i,r);if(o&&(i=o.initData?o.initData:null,s=o.initDataType),i===null)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e));const l=t.uri,c=new kd;e.keyRequests[l]=c;const h=d=>{const f=e.mediaKeysSession;if(!f){const y=new Error("invalid state");c.errored=y;return}const{messageType:g,message:m}=d;c.status=g,this.log(`"${g}" message event for session "${f.sessionId}" message size: ${m.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,t,m).catch(y=>{c.errored=y,c.hasListeners||this.handleError(y),this.removeSession(e)}):g==="license-release"?e.keySystem===me.FAIRPLAY&&this.updateKeySession(e,t,Fi("acknowledged")).then(()=>this.removeSession(e)).catch(y=>this.handleError(y)):this.warn(`unhandled media key message type "${g}"`)};return c.onmessage=h,he(e.mediaKeysSession,"message",h),this.generateRequest(e,t,s,i,r,!1)}generateRequest(e,t,s,i,r,a){if(a){const f=this.filterInitData(e,t,s,i,r);f&&(i=f.initData?f.initData:i,s=f.initDataType)}const o=t.uri,l=e.keyRequests[o],c=Ie(t.keyId||[]),h=f=>{let g;f.startsWith("usable")?l.resolve():f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?g=Vn(f,t):f==="expired"?g=new Error(`key expired (keyId: ${c})`):f==="released"?g=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${c})`),g&&(l.errored=g,l.hasListeners||this.handleError(g))},u=f=>{if(!e.mediaKeysSession){const x=new Error("invalid state");l.errored=x;return}const m=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(m).some(x=>m[x]!=="status-pending"))return;const E=this.activeLevelKeys();for(let x=0;x<E.length;x++){const A=Ie(E[x].keyId||[]);if(m[A]==="expired"){var S;this.log(`Expired key ${fe(m)} in key-session "${(S=e.mediaKeysSession)==null?void 0:S.sessionId}"`),this.renewKeySession(t,e).catch(I=>this.handleError(I));break}}let T=m[c];if(T)h(T);else{var v;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(v=e.keyStatusTimeouts)[c]||(v[c]=self.setTimeout(()=>{var A;if(!e.mediaKeysSession)return;const I=this.getKeyStatus(t);if(I&&I!=="status-pending"){var b;return this.log(`No status for keyId ${c} in key-session "${(b=e.mediaKeysSession)==null?void 0:b.sessionId}". Using session key-status ${I} from other session.`),h(I)}this.log(`key status for ${c} in key-session "${(A=e.mediaKeysSession)==null?void 0:A.sessionId}" timed out after 1000ms`),T="internal-error",h(T)},1e3)),this.log(`No status for keyId ${c} (${fe(m)}).`)}};l.onkeystatuseschange=u,he(e.mediaKeysSession,"keystatuseschange",u);const d=l.useable;return this.log(`Generating key-session request for "${r}" keyId: ${c} URI: ${o} (init data type: ${s} length: ${i.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(s,i).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${c} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>d).catch(f=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${f}`);const m=(g=f.data)==null?void 0:g.details;return(m===R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||m===R.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(y=>e.keyStatuses[y]==="usable")?(this.handleError(f),e):this.removeSession(e).then(()=>{throw f})}).then(()=>e)}getKeyStatuses(e){const t={},s=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){const l=r;r=i,i=l}const a="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===me.PLAYREADY&&a.length===16){const l=Ie(a);t[l]=i,Ya(a)}const o=Ie(a);this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${s}"`),t[o]=i}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=wd(e,t);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={type:se.SERVER_CERTIFICATE,responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,m)=>{a(d.data)},onError:(d,f,g,m)=>{o(new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:j({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};i.load(l,h,u)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,s){return this.requestLicense(e,t,new Uint8Array(s)).then(i=>this.updateKeySession(e,t,new Uint8Array(i)).catch(r=>{throw new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){const s=Ze(new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];const f=(a=h.querySelector("name"))==null?void 0:a.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const l=i.querySelector("Challenge"),c=l?.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Fi(atob(c))}setupLicenseXHR(e,t,s,i,r){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,j(j({},s),{},{decryptdata:i}),r))).catch(o=>{if(!s.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,j(j({},s),{},{decryptdata:i}),r)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t,s){return new Promise((i,r)=>{const a=Od(e.keySystem,this.config);if(!a)return r(new Error(`no license server URL configured for key-system "${e.keySystem}"`));const o=e.keyRequests[t.uri];if(!o)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);const l=this.config.keyLoadPolicy.default,c=new XMLHttpRequest;c.responseType="arraybuffer",c.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(c.readyState===4)if(c.status===200){o.requestErrors=[];let h=c.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);const u=this.config.licenseResponseCallback;if(u)try{h=u.call(this.hls,c,a,j(j({},e),{},{decryptdata:t}))}catch(d){this.error(d)}i(h)}else{const h=l.errorRetry,u=h?h.maxNumRetry:0;if(o.requestErrors.push({status:c.status,message:c.statusText}),o.requestErrors.length>u||c.status>=400&&c.status<500)r(new ze({type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:c,response:{url:a,data:void 0,code:c.status,text:c.statusText}},`License Request XHR failed (${a}). Status: ${c.status} (${c.statusText})`));else{const d=u-o.requestErrors.length;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t,s).then(i,r)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=c,this.setupLicenseXHR(c,a,e,t,s).then(({xhr:h,licenseChallenge:u})=>{e.keySystem==me.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(h,u)),h.send(u)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,he(s,"encrypted",this.onMediaEncrypted),he(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(ce(e,"encrypted",this.onMediaEncrypted),ce(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,gt.clearKeyUriToKeyIdMap();const r=i.length;Ft.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s),this.keyFormatPromise.catch(()=>{})}}removeSession(e){const{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{const l=e.keyRequests[o];l.onmessage&&t.removeEventListener("message",l.onmessage),l.onkeystatuseschange&&t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.reset(),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:i}=e;i&&Object.keys(i).forEach(o=>self.clearTimeout(i[o]));const{drmSystemOptions:r}=this.config;return(th(r)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}}Ft.CDMCleanupPromise=void 0;function Od(n,e){const{drmSystems:t,widevineLicenseUrl:s}=e,i=t?.[n];if(i)return i.licenseUrl;if(n===me.WIDEVINE&&s)return s}function wd(n,e){const{drmSystems:t}=e,s=t?.[n];if(s)return s.serverCertificateUrl}function Md(n){if(n.keyFormat===De.FAIRPLAY)return n.uri;if(n.keyId===null)throw new Error("keyId is null");return Ie(n.keyId)}function Ei(n,e){const t=n.keyId,s=e.mediaKeysSession;if(t&&s){const i=e.mediaKeysSession.keyStatuses;if(i.size)return i.has(t)?i.get(t):e.keyStatuses[Ie(t)]}}function Vn(n,e){const t=n==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ze({type:q.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${n}"`)}class Fd{constructor(e){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=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var Lr=(function(){if(Vs!=null&&Vs.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function s(o){return t(n,o)}function i(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)o[u]=h[u]}return o}function a(o,l,c){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,g=o,m=l,y=c,E=null,S="",T=!0,v="auto",x="start",A=50,I="middle",b=50,_="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(L){d=""+L}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(L){f=!!L}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return g},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");g=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return m},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");m=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(L){E=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return S},set:function(L){const P=s(L);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");S=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return v},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");v=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(L){const P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");x=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return A},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");A=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return I},set:function(L){const P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");I=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return b},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");b=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return _},set:function(L){const P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");_=P,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class Nd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Yo(n){function e(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}const t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Bd{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Wo(n,e,t,s){const i=s?n.split(s):[n];for(const r in i){if(typeof i[r]!="string")continue;const a=i[r].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const Yi=new Lr(0,0,""),As=Yi.align==="middle"?"middle":"center";function $d(n,e,t){const s=n;function i(){const o=Yo(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new Bd;Wo(o,function(d,f){let g;switch(d){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){c.set(d,t[m].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(d,g[0]),c.percent(d,g[0])&&c.set("snapToLines",!1),c.alt(d,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",As,"end"]);break;case"position":g=f.split(","),c.percent(d,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",As,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",As,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&Yi.line===-1&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",As);let u=c.get("position","auto");u==="auto"&&Yi.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),r(n,e)}function qo(n){return n.replace(/<br(?: \/)?>/gi,`
|
|
31
|
+
`)}class Ud{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Nd,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,a=0;for(r=qo(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
|
|
32
|
+
`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
|
|
33
|
+
`&&++a,t.buffer=r.slice(a),o}function i(r){Wo(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Lr(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{$d(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
34
|
+
`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
35
|
+
|
|
36
|
+
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}function Qt(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}const Gd=/\r\n|\n\r|\n|\r/g,Kn="Missing initPTS for VTT ",Vd=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!B(t)||!B(s)||!B(i)||!B(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function Rr(n,e,t){return Qt(n.toString())+Qt(e.toString())+Qt(t)}function Kd(n,e,t,s,i,r,a){const o=new Ud,l=Ue(new Uint8Array(n)).trim().replace(Gd,`
|
|
37
|
+
`).split(`
|
|
38
|
+
`),c=[],h=e?su(e.baseTime,e.timescale):0;let u="00:00.000",d=0,f=0,g=!1,m,y=!0;o.oncue=function(E){const S=t[s];let T=t.ccOffset;const v=(d-h)/9e4;if(g){if(S!=null&&S.new&&(T=t.ccOffset=S.start),v){if(!e){m=new Error(Kn+"MPEGTS");return}T=v-t.presentationOffset}}else if(e)T=-e.baseTime/e.timescale;else{m=new Error(Kn+"without X-TIMESTAMP-MAP");return}const x=E.endTime-E.startTime,A=$e((E.startTime+T-f)*9e4,i*9e4)/9e4;E.startTime=Math.max(A,0),E.endTime=Math.max(A+x,0);const I=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(I)),E.id?s&&(E.id=`hlsjscc${s}_${E.id}`):E.id=Rr(E.startTime,E.endTime,I),E.endTime>0&&c.push(E)},o.onparsingerror=function(E){m=E},o.onflush=function(){if(m){a(m);return}r(c)},l.forEach(E=>{if(y)if(E.startsWith("X-TIMESTAMP-MAP=")){y=!1,g=!0,E.slice(16).split(",").forEach(S=>{S.startsWith("LOCAL:")?u=S.slice(6):S.startsWith("MPEGTS:")&&(d=parseInt(S.slice(7)))});try{f=Vd(u)/1e3}catch(S){m=S}return}else E===""&&(y=!1);o.parse(E+`
|
|
39
|
+
`)}),o.flush()}const Wi="stpp.ttml.im1t",jo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,zo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Hd={left:"start",center:"center",right:"end",start:"start",end:"end"};function Hn(n,e,t,s){const i=J(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Ue(o)),a=tu(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Yd(o,a)))}catch(o){s(o)}}function Yd(n,e){const i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{});!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));const o=i.getAttribute("xml:space")!=="preserve",l=Yn(Ti(i,"styling","style")),c=Yn(Ti(i,"layout","region")),h=Ti(i,"body","[begin]");return[].map.call(h,u=>{const d=Xo(u,o);if(!d||!u.hasAttribute("begin"))return null;const f=vi(u.getAttribute("begin"),a),g=vi(u.getAttribute("dur"),a);let m=vi(u.getAttribute("end"),a);if(f===null)throw Wn(u);if(m===null){if(g===null)throw Wn(u);m=f+g}const y=new Lr(f-e,m-e,d);y.id=Rr(y.startTime,y.endTime,y.text);const E=c[u.getAttribute("region")],S=l[u.getAttribute("style")],T=Wd(E,S,l),{textAlign:v}=T;if(v){const x=Hd[v];x&&(y.lineAlign=x),y.align=v}return ue(y,T),y}).filter(u=>u!==null)}function Ti(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Yn(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Xo(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
|
|
40
|
+
`:(r=s.childNodes)!=null&&r.length?Xo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Wd(n,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,l)=>{const c=Si(e,s,l)||Si(n,s,l)||Si(i,s,l);return c&&(o[l]=c),o},{})}function Si(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function Wn(n){return new Error(`Could not parse ttml timestamp ${n}`)}function vi(n,e){if(!n)return null;let t=Yo(n);return t===null&&(jo.test(n)?t=qd(n,e):zo.test(n)&&(t=jd(n,e))),t}function qd(n,e){const t=jo.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function jd(n,e){const t=zo.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s/1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}function br(n,e,t,s="",i="disabled"){const r=n.ownerDocument.createElement("track");return r.kind=e,r.label=t,s&&(r.srclang=s),r.src="data:,WEBVTT",r.track.mode=i,n.appendChild(r),r}function zd(n){return n.forced&&hc()?"forced":n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function qi(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){le.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){le.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function ji(n,e,t,s){const i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=Qd(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function Xd(n,e){if(e<=n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<n[r].startTime)i=r-1;else if(e>n[r].startTime&&s<t)s=r+1;else return r;return n[s].startTime-e<e-n[i].startTime?s:i}function Qd(n,e,t){const s=[],i=Xd(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}class Zd extends yr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,s=!1;if(this.currentTrack){var i;const o=(i=this.currentTrack.trackNode)==null?void 0:i.track.mode;o==="showing"?(t=this.trackId,s=!0):o==="hidden"&&(t=this.trackId)}if(!s)for(let o=0;o<this.tracksInGroup.length;o++){var r;const l=(r=this.tracksInGroup[o].trackNode)==null?void 0:r.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(s=>{s.trackNode||(s.trackNode=br(this.media,zd(s),s.name,s.lang))});const t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;t?.mode==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){const s=t.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!i&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(r=>{const a=r.trackNode;a&&(a.track.mode="hidden",a.remove(),r.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s;const a=[];if(this.tracks.forEach(h=>{(h.textCodec===Wi?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(h.groupId)>-1?(h.id=a.length,a.push(h)):h.trackNode&&(h.trackNode.remove(),h.trackNode=void 0))}),a.length===this.tracksInGroup.length){let h=!1;for(let u=0;u<a.length;u++)if(a[u]!==this.tracksInGroup[u]){h=!0;break}if(!h)return}a.length&&this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=at(o,a);if(h>-1)r=a[h];else{const u=at(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,c),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||Dt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(ls(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(ls(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===se.SUBTITLE_TRACK&&t.context.id===this.trackId&&ns(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Dt(e,s))return s;const i=at(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),r}else{if(s)return null;{const r=at(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){const s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",i=t.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(e,t=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=s.length||!B(e)){this.warn(`Invalid subtitle track id: ${e}`);return}const i=this.currentTrack,r=s[e]||null;if(this.trackId=e,this.currentTrack=r,t&&this.toggleTrackModes(),!r){i&&this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const a=!!r.details&&!r.details.live;if(r===i&&a)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:o,groupId:l="",name:c,type:h,url:u}=r;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:c,type:h,url:u});const d=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(d)}}const Os=2,Jd=100;class ef extends Va{constructor(e,t){super("gap-controller",e.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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Jd),this.mediaSource=t.mediaSource;const s=this.media=t.media;he(s,"playing",this.onMediaPlaying),he(s,"waiting",this.onMediaWaiting),he(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(ce(s,"playing",this.onMediaPlaying),ce(s,"waiting",this.onMediaWaiting),ce(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;const t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,c=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(h){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1}));return}if(!X.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}const u=X.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&zn(u,e,d,this.hls);const f=u.nextStart||0;if(o&&d&&this.hls){const A=qn(this.hls.inFlightFragments,e),I=u.len>Os,b=!f||A||f-e>Os&&!d.getPartialFragment(e);if(I||b)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&d){if(!(u.len>0)&&!f)return;const I=Math.max(f,u.start||0)-e,_=!!(g!=null&&g.live)?g.targetduration*2:Os,L=Wt(e,d);if(I>0&&(I<=_||L)){a.paused||this._trySkipBufferHole(L);return}}const m=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting;let S=this.stalled;if(S===null)if(E>0&&y-E<m)S=this.stalled=E;else{this.stalled=y;return}const T=y-S;if(!o&&(T>=m||E&&this.moved)&&this.hls){var v;if(((v=this.mediaSource)==null?void 0:v.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-(g?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return;if(a.currentTime!==e){const A=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${A} > ${e}`);return}}const x=X.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(x,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(p.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=X.bufferedInfo(X.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=X.timeRangesToArray(i),o=X.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=X.bufferedInfo(a,e,0).bufferedIndex,c=a[o].end,h=a[o+1].start;if((l===-1||l>o)&&h-c<1&&e-c<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${h} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=Wt(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const f=X.bufferInfo(this.media,e,0);this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:a,media:o}=this,l=(i=this.hls)==null?void 0:i.config;if(!o||!a||!l)return;const c=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Wt(s,a);if((h||c!=null&&c.live&&s<c.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<l.maxBufferHole||d))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,H.MAIN),a=s.getFragAtPos(i,H.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${fe(e)})`);this.warn(a.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){const{fragmentTracker:t,media:s,hls:i}=this,r=i?.config;if(!s||!t||!r)return 0;const a=s.currentTime,o=X.bufferInfo(s,a,0);zn(o,a,t,i);const l=a<o.start?o.start:o.nextStart;if(l){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&s.readyState<3,d=l-a;if(d>0&&(h||u)){if(d>r.maxBufferHole){let E=!1;if(a===0){const S=t.getAppendedFrag(0,H.MAIN);S&&l<S.end&&(E=!0)}if(!E&&e){var c;if(!((c=i.loadLevelObj)!=null&&c.details)||qn(i.inFlightFragments,l))return 0;let T=!1,v=e.end;for(;v<l;){const x=Wt(v,t),A=x?x.duration:0;if(A>0)v+=A;else{T=!0;break}}if(T)return 0}}const{nudgeMaxRetry:f,skipBufferHolePadding:g}=r,m=++this.skipRetry>f,y=Math.max(l,a)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${y}`),this.moved=!0,s.currentTime=y),!(e!=null&&e.gap)||m){const E=new Error(m?`Playhead still not moving after seeking over buffer hole from ${a} to ${y} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${y}`),S={type:q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:m,error:E,reason:E.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?S.part=e:S.frag=e),i.trigger(p.ERROR,S)}return y}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;const a=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=a+(i+1)*r.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function qn(n,e){const t=jn(n.main);if(t&&t.start<=e)return t;const s=jn(n.audio);return s&&s.start<=e?s:null}function jn(n){if(!n)return null;switch(n.state){case D.IDLE:case D.STOPPED:case D.ENDED:case D.ERROR:return null}return n.frag}function Wt(n,e){return e.getAppendedFrag(n,H.MAIN)||e.getPartialFragment(n)}function zn(n,e,t,s){const i=s.latestLevelDetails,r=Wt(e,t);if(Ys(s.config)&&!n.nextStart&&i&&r&&s.interstitialsManager){const a="type"in r?r:r.fragment,o=Ua(i,a.sn);o?.level===a.level&&io(o,s.interstitialsManager.playerQueue,e)&&(n.nextStart=o.start)}}const tf=.25;function zi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function xi(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,fe(i?j({type:i},s):s))}return r}const Is=(()=>{const n=zi();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class sf{constructor(e){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(p.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return br(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=zi();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===Oe.emsg&&!s||!i)continue;const c=ma(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>Is&&(u=Is),u-h<=0&&(u=h+tf);for(let f=0;f<c.length;f++){const g=c[f];if(!pa(g)){this.updateId3CueEnds(h,l);const m=xi(a,h,u,g,l);m&&this.id3Track.track.addCue(m)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.track.cues;if(i)for(let r=i.length;r--;){const a=i[r];a.type===t&&a.startTime<e&&a.endTime===Is&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;i==="audio"?c=h=>h.type===Oe.audioId3&&l:i==="video"?c=h=>h.type===Oe.emsg&&o:c=h=>h.type===Oe.audioId3&&l||h.type===Oe.emsg&&o,ji(r.track,t,s,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=zi();if(s&&i&&!a){const{fragmentStart:m,fragmentEnd:y}=e;let E=this.assetCue;E?(E.startTime=m,E.endTime=y):o&&(E=this.assetCue=xi(o,m,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:c}=e,h=Object.keys(c);let u=this.dateRangeCuesAppended;if(l&&t){var d;if((d=l.track.cues)!=null&&d.length){const m=Object.keys(u).filter(y=>h.indexOf(y)===-1);for(let y=m.length;y--;){var f;const E=m[y],S=(f=u[E])==null?void 0:f.cues;delete u[E],S&&Object.keys(S).forEach(T=>{const v=S[T];if(v){v.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(v)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const g=e.fragments[e.fragments.length-1];if(!(h.length===0||!B(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<h.length;m++){const y=h[m],E=c[y],S=E.startTime,T=u[y],v=T?.cues||{};let x=T?.durationKnown||!1,A=Is;const{duration:I,endDate:b}=E;if(b&&I!==null)A=S+I,x=!0;else if(E.endOnNext&&!x){const L=h.reduce((P,C)=>{if(C!==E.id){const F=c[C];if(F.class===E.class&&F.startDate>E.startDate&&(!P||E.startDate<P.startDate))return F}return P},null);L&&(A=L.startTime,x=!0)}const _=Object.keys(E.attr);for(let L=0;L<_.length;L++){const P=_[L];if(!zc(P))continue;const C=v[P];if(C)x&&!(T!=null&&T.durationKnown)?C.endTime=A:Math.abs(C.startTime-S)>.01&&(C.startTime=S,C.endTime=A);else if(o){let F=E.attr[P];Xc(P)&&(F=ya(F));const $=xi(o,S,A,{key:P,data:F},Oe.dateRange);$&&($.id=y,this.id3Track.track.addCue($),v[P]=$,a&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:v,dateRange:E,durationKnown:x}}}}}function Qo(){return self.SourceBuffer||self.WebKitSourceBuffer}function Zo(){if(!xt())return!1;const e=Qo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function rf(){if(!Zo())return!1;const n=xt();return typeof n?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(is(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(is(e,"audio"))))}function nf(){var n;const e=Qo();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}var tt={DISABLED:0,SWITCHING:1,SWITCHED:2};const af=100;class Jo extends ur{constructor(e,t,s){super(e,t,s,"stream-controller",H.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=tt.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!B(r)||(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(i,r,H.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${r} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(af),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),e=s),this.state=D.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=D.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case D.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=D.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=D.IDLE;break}break}case D.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===D.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={type:this.targetBufferType()};this.hls.trigger(p.BUFFER_EOS,m),this.state=D.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=a.details;if(!c||this.state===D.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=D.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&Ee(f)&&this.fragmentTracker.getState(f)!==ye.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-c.startSN,E=c.fragments[y-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?de.AUDIO:de.VIDEO,E=(y===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y)}f=this.getNextFragmentLoopLoading(f,c,o,H.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===ye.NOT_LOADED||i===ye.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==tt.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===tt.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const s=this.fragPlaying;if(s){const i=s.level;this.hls.trigger(p.FRAG_CHANGED,{frag:s,previousFrag:e}),e?.level!==i&&this.hls.trigger(p.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===tt.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;he(s,"playing",this.onMediaPlaying),he(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(ce(s,"playing",this.onMediaPlaying),ce(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=tt.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const a=t.levels[r].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!nf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==D.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=D.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,a=t.level,o=t.details,l=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const c=t.levelInfo,h=this.fragCurrent;h&&(this.state===D.FRAG_LOADING||this.state===D.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=c.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(c.details=o,this.levelLastLoaded=c,r||this.setStartPosition(o,u),this.hls.trigger(p.LEVEL_UPDATED,{details:o,level:a}),this.state===D.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=D.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.playhead,a=e.fragmentStart,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!l)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i}`),this.config.liveSyncMode==="buffered"){var c;const u=X.bufferInfo(s,i,0);if(!((c=u.buffered)!=null&&c.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:f}=X.bufferedInfo(u.buffered,r,0);f&&(s.currentTime=f)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new xo(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,m=g!==-1,{decryptRange:y,byteRange:E}=Us(s,i,this.iframesOnly),S=new or(s.level,s.sn,s.stats.chunkCount,E?E.end-E.start:r.byteLength,g,m,s.duration,this.iframesOnly,y),T=this.initPTS[s.cc];f.push(r,u,d,c,s,i,l.totalduration,h,S,T)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==tt.DISABLED;if($s(t.url,s))this.altAudio=tt.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 a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=tt.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(p.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(p.AUDIO_TRACK_SWITCHED,t)}),s.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=$s(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?tt.SWITCHED:tt.DISABLED,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(r=o,i=l,o==="video"){const c=s[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===H.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===D.PARSED&&(this.state=D.IDLE);return}let l=!1;if(Ee(s)&&(l=!!s.gap&&!s.tagList.some(c=>c[0]==="GAP")),this.fragBufferedComplete(s,i),l){var a;s.stats.retry++;const c=(a=this.levels)==null?void 0:a[s.level];c&&c.fragmentError++}}const o=this.media;o&&(!this._hasEnoughToStart&&X.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===se.LEVEL&&(this.state=D.IDLE);break;case R.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=D.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==de.AUDIO||!this.altAudio){const s=(t===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),a=X.getBuffered(e),o=a.length?a.start(0):0,l=o-s,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=D.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:l,level:c}=a,{video:h,text:u,id3:d,initSegment:f}=i,{details:g}=c,m=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=D.PARSING,f){const y=f.tracks;if(y){const v=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,y,v,r),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:y})}const E=f.initPTS,S=f.timescale,T=this.initPTS[o.cc];if(B(E)&&(!T||T.baseTime!==E||T.timescale!==S)){const v=f.trackId;this.initPTS[o.cc]={baseTime:E,timescale:S,trackId:v};const x=this.initPTS.slice(0);s.trigger(p.INIT_PTS_FOUND,{timestampOffsets:x,frag:o,id:t,initPTS:E,timescale:S,trackId:v})}}if(h&&g){m&&h.type==="audiovideo"&&this.logMuxedErr(o);const y=g.fragments[o.sn-1-g.startSN],E=o.sn===g.startSN,S=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:v,startDTS:x,endDTS:A}=h;if(l)l.elementaryStreams[h.type]={startPTS:T,endPTS:v,startDTS:x,endDTS:A};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!S&&(this.couldBacktrack=!0),h.dropped&&h.independent){const I=this.getMainFwdBufferInfo(),b=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,_=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!E&&b<_-this.config.maxBufferHole&&!S){this.backtrack(o);return}else S&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,v,o.start,A,!0)}else E&&T-(g.appliedTimelineOffset||0)>Os&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,v,x,A),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,r,E||S)}else if(E||S)o.gap=!0;else{this.backtrack(o);return}}if(m){const{startPTS:y,endPTS:E,startDTS:S,endDTS:T}=m;l&&(l.elementaryStreams[de.AUDIO]={startPTS:y,endPTS:E,startDTS:S,endDTS:T}),o.setElementaryStreamInfo(de.AUDIO,y,E,S,T),this.bufferFragmentData(m,o,l,r)}if(g&&d!=null&&d.samples.length){const y={id:t,frag:o,details:g,samples:d.samples};s.trigger(p.FRAG_PARSING_METADATA,y)}if(g&&u){const y={id:t,frag:o,details:g,samples:u.samples};s.trigger(p.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${Ee(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==D.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:a,audiovideo:o}=t;if(r){const c=e.audioCodec;let h=Ds(r.codec,c);if(h==="mp4a"&&(h="mp4a.40.5"),this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const u=r.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&!cc()&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&uc()&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),c&&c!==h&&this.log(`Swapping manifest audio codec "${c}" for "${h}"`),r.levelCodec=h,r.id=H.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${c||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=H.MAIN;const c=a.codec;if(c?.length===4)switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${a.codec!==c?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const l=Object.keys(t);if(l.length){if(this.hls.trigger(p.BUFFER_CODECS,t),!this.hls)return;l.forEach(c=>{const u=t[c].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:c,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.getBufferOutput();return this.getFwdBufferInfo(e,H.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=D.IDLE}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return B(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(B(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?Bt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const a=r+(t-i.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class el extends Jo{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;const{seekOnAppend:s}=t,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case D.STOPPED:case D.ENDED:case D.ERROR:this.state=D.IDLE}this.state===D.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(p.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;s&&r&&this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}seekTo(e){const t=this.media;if(t){var s;const i=(s=this.getLevelDetails())==null?void 0:s.edge,r=i!==void 0?i:t.duration;if(e>=r&&(e=r-.01),X.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;const s=this.cached;s.push(e),this.cachedSize+=t.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){const r=s.shift();if(r.data)this.cachedSize-=r.data.byteLength,r.data=void 0;else{this.cached=s.filter(a=>!!a.data),this.cachedSize=s.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){const t=e.frag,{part:s,payload:i}=e;this.cacheFragmentData&&!s&&i!=null&&i.byteLength&&!t.data&&Ee(t)&&this.cacheSet(t,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if((i===ye.NOT_LOADED||i===ye.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,s)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;const s=e.decryptdata;return s?.keyFormat!=="identity"||!!s.key}replayCachedFragment(e){const t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;const s=e.stats=new Ji;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=t.byteLength,s.chunkCount=1,this.state=D.FRAG_LOADING;const i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(p.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);const{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=D.STOPPED,s!=null&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Hs(X.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(e,t){if(t){const s=this.media;if(s){const i=X.bufferInfo(s,e,0),r=i.len?i.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,H.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(p.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(p.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,s){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,s||i||void 0)}getMainFwdBufferInfo(){const e=this.playhead,t=this.getBufferedAt(e);if(t){const s=t.duration;return{len:s,start:e,end:e+s,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){const e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,H.MAIN);return!!(t!=null&&t.endList)}}class of extends el{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;const s=(t=this._img)==null?void 0:t.src;s&&self.URL.revokeObjectURL(s),this._img=e}loadMediaAt(e){if(!this.hls)return;const t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case D.STOPPED:case D.ENDED:case D.ERROR:this.state=D.IDLE}if(this.state===D.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===D.IDLE){const s=this.getBufferedAt(e);s&&(this.fragCurrent=s,this.updateImage(s,null))}}else{const s=this.fragCurrent;(!s||e>=s.start&&e<s.end)&&(this.queued=[t])}}updateImage(e,t,s){const i=e.data;i||this.fragmentTracker.removeFragment(e);const r=this._img;if(r&&i){const a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,r.onload=()=>{if(!this.hls)return;const h=this.hls.levels[e.level];h!=null&&h.fragmentError&&(h.fragmentError=0,e.stats.retry=0);const u=self.performance.now(),d=t?t.stats:e.stats;d.buffering.end=e.stats.buffering.end=u,this.hls.trigger(p.FRAG_BUFFERED,{frag:e,part:t,stats:d,id:e.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",e,t,s)};const l=r.src;l&&self.URL.revokeObjectURL(l);const c=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(c)}else this.state=D.STOPPED,this.processQueued()}processQueued(){const e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,s,i){if(!this.hls)return;const r=new Error(e);this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(e,t,s,i){super.bufferFragmentData(e,t,s,i,!0);const r=J(new Uint8Array(e.data1),["mdat"]);if(r.length===0){this.handleError("Could not find I-Frame mdat",t,s,i);return}const a=t;this.cacheSet(a,r[0]),this.updateImage(a,s,i)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;const t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){const s=this.getAppendedFrag(t);if(s&&!Yt(s,this.fragPlaying))return this.fragPlaying=s,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const lf=10,cf="Image I-Frame player does not accept HTMLMediaElements",Xn={seekOnAppend:!0};let Ls,Ai;class hf extends Ge{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Ls||(Ls=uf(t)),Ai||(Ai=df(Ls)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(p.MANIFEST_LOADING,this.clearAsset,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.clearAsset,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var s;const i=(s=this.hls)==null?void 0:s.pathwayPriority;t.length&&i&&this.iframeInstances.forEach(r=>{r.pathwayPriority=i})}onInitPtsFound(e,{id:t,timestampOffsets:s}){t===H.MAIN&&(this.initPTS=s)}onFragBuffered(e,t){var s;const i=this.hls;i&&i.hasEnoughToStart&&(((s=i.mainForwardBufferInfo)==null?void 0:s.len)||0)>lf&&this.iframeInstances.forEach(r=>{if(!r.loadingEnabled){var a;r.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(Ls,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;const s=(t=this.hls)==null?void 0:t.iframeVariants.filter(i=>i.imageCodec);return this.createInstance(Ai,s,e,"image-")}createInstance(e,t,s,i){const{hls:r}=this;if(!r)return null;const{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:c,loadLevel:h,bandwidthEstimate:u,sessionId:d}=r,{stats:f,variableList:g}=this;if(!(t!=null&&t.length)||!f||!a)return null;const m=`${i||""}iframe-player-${this.instanceCounter++}`,y=r.levels,E=c||y[h],S=Na(E,o.videoPreference),T=E?.pathwayId||".",v=j(j({},o),{},{loggerId:m,primarySessionId:d,videoPreference:S,abrEwmaDefaultEstimate:u,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},s),x=new e(v,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(A=>!A.url),this.iframeInstances.push(x),x.trigger(p.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:T},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),x}}function uf(n){return class extends n{constructor(t,s,i,r){t.streamController||(t.streamController=el),super(t),this._url=s,this.streamController.setInitPts(i),this.streamController.initDetails=r}loadSource(){}loadMediaAt(t,s=Xn){if(t<0)return;const i=j(j({},Xn),s);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,i)}}}function df(n){return class extends n{constructor(t,s,i,r){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=of),t.capLevelController=void 0,t.bufferController=void 0,super(t,s,i,r)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(cf)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}const vt=.025;let zs=(function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n})({});function ff(n,e,t){return`${n.identifier}-${t+1}-${Qt(e)}`}class gf{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Qn(t,e)?ws(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=ws(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=B(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Qn(t,e)?ws(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<vt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?zs.Range:zs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return mf(this)}}function ws(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<vt)?e.start:e.start+e.duration}function Qn(n,e){return e>n.start-vt&&e<n.start+n.duration+vt}function tl(n,e,t){const s=new self.URL(n,t);return s.protocol!=="data:"&&St(s,"_HLS_primary_id",e),s}function Ii(n,e){for(;(t=n.assetList[++e])!=null&&t.error;)var t;return e}function mf(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function wt(n){const e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class pf{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(p.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const a=()=>{this.hasDetails=!0};r.once(p.LEVEL_LOADED,a),r.once(p.AUDIO_TRACK_LOADED,a),r.once(p.SUBTITLE_TRACK_LOADED,a),r.on(p.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(p.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(p.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=tl(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var s;if(!this.appendInPlace)return!1;if((s=this.hls)!=null&&s.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(t||0),a=X.bufferInfo(e,r,.02);return this.getAssetTime(a.end)>=i-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=X.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${wt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Li=.033;class yf extends Ge{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];t&&t!=="primary"&&(r=r[t]);const a=r.start,o=s[i].event,l=o!=null&&o.cue.pre?o.duration:r.end;if(e===a||e>a&&e<l)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const a=s[r];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t,s=0){const i=e.main.details,{dateRanges:r}=i,a=this.events,o=this.parseDateRanges(r,{url:i.url},t),l=Object.keys(r),c=a?a.filter(h=>l.indexOf(h.identifier)===-1):[];o.length&&o.sort((h,u)=>{const d=h.cue.pre,f=h.cue.post,g=u.cue.pre,m=u.cue.post;if(d&&!g)return-1;if(g&&!d||f&&!m)return 1;if(m&&!f)return-1;if(!d&&!g&&!f&&!m){const y=h.startTime,E=u.startTime;if(y!==E)return y-E}return h.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,c.forEach(h=>{this.removeEvent(h)}),this.updateSchedule(e,c,s)}updateSchedule(e,t=[],s=0,i=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const a=this.items,o=this.parseSchedule(r,e,s);(i||t.length||a?.length!==o.length||o.some((c,h)=>Math.abs(c.playout.start-a[h].playout.start)>.005||Math.abs(c.playout.end-a[h].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let a=0;a<r.length;a++){const o=r[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new gf(l,t),this.eventMap[o]=c,s===!1&&(c.appendInPlace=s)),i.push(c)}}return i}parseSchedule(e,t,s=0){const i=[],r=t.main.details,a=r.live?1/0:r.edge;let o=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,h=0;if(e.forEach((u,d)=>{const f=u.cue.pre,g=u.cue.post,m=e[d-1]||null,y=u.appendInPlace,E=g?a:u.startOffset,S=u.duration,T=u.timelineOccupancy===zs.Range?S:0,v=f&&r.live?s+(u.resumeOffset||0):0,x=v||u.resumptionOffset,A=m?.startTime===E,I=E+u.cumulativeDuration;let b=y?I+S:E+x;if(f||!g&&E<=0){const L=h;h+=T,u.timelineStart=I;const P=o;o+=S,i.push({event:u,start:I,end:b,playout:{start:P,end:o},integrated:{start:L,end:h}})}else if(E<=a){if(!A){const C=E-c;if(C>Li){const F=c,V=h;h+=C;const $=o;o+=C;const k={previousEvent:e[d-1]||null,nextEvent:u,start:F,end:F+C,playout:{start:$,end:o},integrated:{start:V,end:h}};i.push(k)}else C>0&&m&&(m.cumulativeDuration+=C,i[i.length-1].end=E)}g&&(b=I),u.timelineStart=I;const L=h;h+=T;const P=o;o+=S,i.push({event:u,start:I,end:b,playout:{start:P,end:o},integrated:{start:L,end:h}})}else return;const _=v||u.resumeTime;g||_>a?c=a:!f&&b&&u.appendInPlaceStarted&&_-b>Li?c=b:c=_}),c<a){var l;const u=c,d=h,f=a-c;h+=f;const g=o;o+=f,i.push({previousEvent:((l=i[i.length-1])==null?void 0:l.event)||null,nextEvent:null,start:c,end:u+f,playout:{start:g,end:o},integrated:{start:d,end:h}})}this.setDurations(a,o,h)}else i.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return i}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,a=-1;e.forEach((o,l)=>{const c=o.cue.pre,h=o.cue.post,u=c?0:h?i:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=r:(r=0,a=u),!h&&o.snapOptions.in&&(o.resumeAnchor=Bt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<Li&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=B(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>vt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;const c=Bt(null,o.fragments,s);if(!c)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=a==="audio"?.175:0;return Math.abs(c.start-s)<vt+h||Math.abs(c.end-s)<vt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,i||(i=o.duration===null),r||(r=!!o.error);const c=o.error?0:o.duration||0;s+=c}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Be(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}class Ef{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=tl(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(p.ERROR,f);return}t&&i.protocol!=="data:"&&St(i,"_HLS_start_offset",""+t);const r=this.hls.config,a=r.loader,o=new a(r),l={type:se.INTERSTITIAL_ASSET_LIST,responseType:"json",url:i.href},c=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,m)=>{const y=d.data,E=y?.ASSETS;if(!Array.isArray(E)){const S=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,m);this.hls.trigger(p.ERROR,S);return}e.assetListResponse=y,this.hls.trigger(p.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:m})},onError:(d,f,g,m)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,m,g);this.hls.trigger(p.ERROR,y)},onTimeout:(d,f,g)=>{const m=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);this.hls.trigger(p.ERROR,m)}};return o.load(l,h,u),this.hls.trigger(p.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,a){return e.error=s,{type:q.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:r}}}function Zn(n){var e;n==null||(e=n.play())==null||e.catch(()=>{})}function Rt(n,e){return`[${n}] Advancing timeline position to ${e}`}class Tf extends Ge{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const a=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&g>f){const m=this.schedule.findJumpRestrictedIndex(f+1,g);if(m>f){this.setSchedulePosition(m);return}}this.setSchedulePosition(g);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const h=c.timelineStart,u=c.duration||0;if(a&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,c)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],l=r.items||[],c=r.durations,h=s.map(m=>m.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
41
|
+
Schedule: ${l.map(m=>Be(m))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),s.forEach(m=>{m.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const y=m.assetItem.timelineStart,E=m.timelineOffset-y;if(E)try{m.timelineOffset=y}catch(S){Math.abs(E)>vt&&this.warn(`${S} ("${m.assetId}" ${m.timelineOffset}->${y})`)}}}),u||i){if(this.hls.trigger(p.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:h}),this.isInterstitial(a)&&h.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),g&&f!==d&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Ef(e),this.schedule=new yf(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){ce(e,"play",this.onPlay),ce(e,"pause",this.onPause),ce(e,"seeking",this.onSeeking),ce(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;he(s,"seeking",this.onSeeking),he(s,"timeupdate",this.onTimeupdate),he(s,"play",this.onPlay),he(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,f,g,m)=>{if(u){let y=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==zs.Point){const S=s(f);S?.interstitial===E&&(y+=S.assetItem.startOffset+S[m])}}else{const S=g==="bufferedPos"?a():e[g];y+=S-u.start}return y}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const m=e.schedule.findItemIndexAtTime(u),y=(g=e.schedule.items)==null?void 0:g[m];if(y){const E=y[d].start-y.start;return u+E}}return u},a=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,d)=>{var f,g;const m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),S=(g=e.schedule.items)==null?void 0:g[E],T=e.getBufferingPlayer(),v=T?.interstitial,x=v?.appendInPlace,A=y&&e.itemsMatch(y,S);if(y&&(x||A)){const I=s(e.playingAsset),b=I?.media||e.primaryMedia;if(b){const _=d==="primary"?b.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),L=u-_,P=(x?_:b.currentTime)+L;if(P>=0&&(!I||x||P<=I.duration)){b.currentTime=P;return}}}if(S){let I=u;if(d!=="primary"){const _=S[d].start,L=u-_;I=S.start+L}const b=!e.isInterstitial(S);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(b||S.event.appendInPlace)){const _=e.media||(x?T?.media:null);_&&(_.currentTime=I)}else if(y){const _=e.findItemIndex(y);if(E>_){const P=e.schedule.findJumpRestrictedIndex(_+1,E);if(P>_){e.setSchedulePosition(P);return}}let L=0;if(b)e.timelinePos=I,e.checkBuffer();else{const P=S.event.assetList,C=u-(S[d]||S).start;for(let F=P.length;F--;){const V=P[F];if(V.duration&&C>=V.startOffset&&C<V.startOffset+V.duration){L=F;break}}}e.setSchedulePosition(E,L)}}},c=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const u=c(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=c(),f=e.effectivePlayingItem;f&&f===d&&l(u+f.playout.start,"playout")},get duration(){const u=c();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=c())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=c())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return c()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){l(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){return r(e.seekableStart,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(u);if(d.appendInPlace){const g=u.playout.start+u.event.duration;l(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!B(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${fe(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,c=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(a.media)l&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else{const g=this.getBufferingPlayer();g?(r=g.transferMedia(),this.detachedData=r,h=`${g}`):c?h="detached MediaSource":h="detached media"}if(!r){if(c)r=this.detachedData,this.log(`using detachedData: MediaSource ${fe(r)}`);else if(!this.detachedData||a.media===t){const g=this.playerQueue;g.length>1&&g.forEach(m=>{if(o&&m.interstitial.appendInPlace!==l){const y=m.interstitial;this.clearInterstitial(m.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed";if(this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`),!u&&!o){e.attachMedia(t);return}const d=u&&r?j({},r):{media:t},f=this.schedule;if(f&&o){const g=e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:g||e.appendInPlace===!1}}if(!u&&l){const g=e,m=g.assetItem.timelineStart;if(m){const y=g.hls,E=Math.max(this.timelinePos-m,Number.EPSILON);y.startPosition!==E&&(this.log(`Set ${g} startPosition: ${E}`),y.config.startPosition=E,y.loadingEnabled&&y.startLoad(E))}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events,s=this.hls;if(!t||this.playbackDisabled||!this.media||!s)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){if(!s.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}const a=s.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Rt("checkStart (preroll)",a));const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(Rt("checkStart",a));const o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else s.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(Rt("checkStart (playing item)",r.start));const a=e.findItemIndex(r);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Ii(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!B(e.resumeOffset)&&this.hls){const s=this.getLiveStartPos();if(t){const i=this.getBufferingPlayer(),r=i!=null&&i.interstitial.cue.pre?i.remaining:0;return s+r}return s}}getNextItemIndex(e,t){if(this.schedule){const s=this.livePrerollResumption(e.event,t);if(s!==void 0)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,s){const i=Ii(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const a=r[t],o=a.event?this.getNextItemIndex(a):t+1,l=r.length;if(o>=l){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(Rt("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&!r[o].event&&this.hls.startLoad(c+.01),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const a=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Be(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const u=a.event,d=this.playingAsset,f=d?.identifier,g=f?this.getAssetPlayer(f):null;if(g&&f&&(!this.eventItemsMatch(a,r)||t!==void 0&&f!==u.assetList[t].identifier)){var l;const m=u.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${wt(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(p.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:m,event:u,schedule:i.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(f,r),g.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${Be(a)}`),u.hasPlayed=!0,this.hls.trigger(p.INTERSTITIAL_ENDED,{event:u,schedule:i.slice(0),scheduleIndex:e}),u.cue.once&&this.hls)){var c;this.updateSchedule();const m=(c=this.schedule)==null?void 0:c.items;if(r&&m){const y=this.findItemIndex(r),E=this.livePrerollResumption(u);if(E!==void 0){let S=E;const T=this.getNextItemIndex(a);if(!this.isInterstitial(i[T])){var h;const v=(h=this.primaryDetails)==null?void 0:h.fragments;if(u.snapOptions.in&&v){const x=Bt(null,v,E);x&&(S=Math.min(Math.max(i[T].start,ws(S,x)),i[T].end))}}if(this.log(Rt("live join (preroll)",S)),this.timelinePos=S,T!==y&&(T||T===0)){this.advanceSchedule(T,m,void 0,a,o);return}}this.advanceSchedule(y,m,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,r){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(h=>{const u=h.interstitial,d=a.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=h.cue.pre?0:a.findAssetIndex(h,this.timelinePos);const g=Ii(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}const u=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Be(o)} ${h.appendInPlace?"append in place":""}`),h.hasPlayed=!1,this.hls.trigger(p.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),d=this.createAssetPlayer(h,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,l),this.shouldPlay&&Zn(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Zn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Be(e)}`);let a=this.timelinePos;if((i=this.detachedData)!=null&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Rt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!s)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Be(e)}`),this.hls.trigger(p.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,s){const i=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;const r=this.endedItem||this.playingItem,a=r!=null&&r.event?this.livePrerollResumption(r.event,s):void 0;if(a!==void 0)return a;const o=this.primaryDetails;if(o){const{fragmentStart:l,edge:c}=o;if(i<l||i>c&&!s){const h=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${l}-${c}]) snapping to liveSync ${h}`),h||l}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var e;const t=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||s&&s-t<i?s||0:t}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:X.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Rt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){const s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:a}=s,o=s.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${i} bufferingEnabled: ${r}`),!t&&o||!i||Math.abs(a-e)>.1){const l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){const c=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${c?Be(c):null}`),s.pauseBuffering(),this.bufferPastEdge=!0;return}s.startLoad(e,t)}else r||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(p.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(p.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=j(j({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;const r=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,r===-1?0:r),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){const o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;const c=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${c?Be(c):null}`),c?.end===1/0){const u=this.playingItem,d=this.isInterstitial(u)&&u.event.appendInPlace;this.hls.startLoad(Math.max(l,c.start),d)}else{const u=this.getBufferingPlayer();u&&u.bufferedInPlaceToEnd(this.primaryMedia,u.currentTime)&&u.hls&&u.hls.trigger(p.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=j(j({},this.altSelection),{},{audio:s});return}const r=j(j({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=j(j({},this.altSelection),{},{subtitles:s});return}const r=j(j({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){const i=t[s];if(i.cue.post){const r=this.getEventItem(i.identifier);r&&this.eventItemsMatch(r,this.bufferingItem)&&this.bufferedToItem(r,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=X.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Be(e)} (was ${Be(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;const s=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(s)&&s.event.identifier===e)return s}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,s;const i=this.mediaSelection;if(!i)return;const r=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(s=this.schedule)==null||s.updateSchedule(i,[],r,e)}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=X.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((l===-1&&r&&e>=r.end||(c=d.event)!=null&&c.appendInPlace&&e+.01>=d.start)&&(l=u),this.isInterstitial(r)){const f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>h&&l>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&a&&!this.itemsMatch(a,r)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Be(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const c=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===c&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(p.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.getPrimaryResumption(e,this.findItemIndex(e),!0),r=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(r,e,!0):this.startLoadingPrimaryAt(r);else{const o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(r,l)}}}}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,a=e.cue.once;if(r){const l=e.timelineStart,c=this.playingItem,h=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(c)&&(c==null||(o=c.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let u,d=0;if((!h||h.interstitial.cue.pre)&&this.primaryLive&&(d=this.getLiveStartPos(),h&&(d+=h.remaining)),d&&!(e.cue.pre||e.cue.post)){const g=d-l;g>0&&(u=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${d?` live-start: ${d} start-offset: ${u} (timeline-start: ${l})`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);const f=this.assetListLoader.loadAssetList(e,u);f&&(e.assetListLoader=f)}else if(!a&&i){for(let c=t;c<i;c++){const h=e.assetList[c],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,c)}const l=e.assetList[t];if(l){const c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;const s=this.primaryDetails;if(s&&e>=s.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,a){const o={parentIdentifier:e.identifier,identifier:ff(e,a,t),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig,a=i.loadLevelObj||i.levels[i.currentLevel],o=Na(a,r.videoPreference),l=i.audioTracks[i.audioTrack],c=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const v=this.timelinePos-t.timelineStart;if(v>=0){const x=t.duration;x&&v<x&&(h=v)}}const u=t.identifier,d=j(j({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||r.audioPreference,subtitlePreference:c||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=ue({},f,{contentId:Qt(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const g=new pf(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let m=!0;const y=v=>{if(v.live){const I=new Error(`Interstitials MUST be VOD assets ${e}`),b={fatal:!0,type:q.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},_=this.findEventIndex(e.identifier);this.handleAssetItemError(b,e,_,s,I.message);return}const x=v.edge-v.fragmentStart,A=t.duration;(m||A===null||x>A)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${x}`),t.duration=x,this.updateSchedule())};g.on(p.LEVEL_UPDATED,(v,{details:x})=>y(x)),g.on(p.LEVEL_PTS_UPDATED,(v,{details:x})=>y(x)),g.on(p.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(v,x)=>{const A=this.getAssetPlayer(u);if(A&&x.tracks){A.off(p.BUFFER_CODECS,E),A.tracks=x.tracks;const I=this.primaryMedia;this.bufferingAsset===A.assetItem&&I&&!A.media&&this.bufferAssetPlayer(A,I)}};g.on(p.BUFFER_CODECS,E);const S=()=>{const v=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${v}`),!v||!this.schedule)return;const x=this.getEventItem(e.identifier);x&&this.advanceAssetBuffering(x,v.assetItem)};g.on(p.BUFFERED_TO_END,S);const T=v=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const A=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,A,v)};return g.once(p.MEDIA_ENDED,T(s)),g.once(p.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(p.ERROR,(v,x)=>{if(!this.schedule)return;const A=this.getAssetPlayer(u);if(x.details===R.BUFFER_STALLED_ERROR){if(A!=null&&A.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(x.details===R.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(x,e,this.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),g.on(p.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const x=new Error(`Asset player destroyed unexpectedly ${u}`),A={fatal:!0,type:q.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(A,e,this.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${wt(t)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Be(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:a,assetItem:o,assetId:l}=e,c=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,h?.identifier!==l&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${wt(o)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s;if(!this.schedule)return;const{interstitial:i,assetItem:r}=e,a=this.getEventItem(i.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,r);return}const o=this.getBufferingPlayer();if(o===e)return;const l=i.appendInPlace;if(l&&o?.interstitial.appendInPlace===!1)return;const c=o?.tracks||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(l&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!ua(c,e.tracks)){const h=new Error(`Asset ${wt(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),u={fatal:!0,type:q.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},d=i.findAssetIndex(r);this.handleAssetItemError(u,i,this.findEventIndex(i.identifier),d,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),a=e.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||i-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${i})`),l&&(c/s.playbackRate<.5||o.bufferedInPlaceToEnd(s,o.currentTime))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;if(t&&t.currentTime<e){const s=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(s),t.currentTime=e):this.log(`Cannot ${s}`)}}handleAssetItemError(e,t,s,i,r){if(e.details===R.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&wt(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,h=this.schedule.items,u=ue({},e,{fatal:!1,errorAction:jt(!0),asset:a,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:c});if(this.hls.trigger(p.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(m=>!m.error))t.error=g;else for(let m=i;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d?.identifier===o?this.advanceAfterAssetEnded(t,s,i):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,a=this.hls.startPosition;let o=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Be(s)} startPosition: ${a} seekableStart: ${r} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,r);const c=this.updateItem(s,o);this.itemsMatch(s,c)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||!this.isInterstitial(i))return;const l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var s,i;const r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const l=r.timelineStart,c=r.duration;let h=0;o.forEach((g,m)=>{const y=parseFloat(g.DURATION);this.createAsset(r,m,h,l+h,y,g.URI),h+=y}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${c}) ${r}`);const u=this.waitingItem,d=u?.event.identifier===a;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(d){const g=this.findEventIndex(a),m=this.getEventItem(a);if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if(f?.identifier===a){const g=r.assetList[0];if(g){const m=this.getAssetPlayer(g.identifier);if(f.appendInPlace){const y=this.primaryMedia;m&&y&&this.bufferAssetPlayer(m,y)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}const i=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${i?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class Sf{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:s}=this,i=this.levelDetails;if(!s||!i||!this.hls)return;this.currentTime=s.currentTime;const r=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=r;if(!o||l===1||!i.live)return;const c=this.targetLatency;if(c===null)return;const h=a-c,u=Math.min(this.maxLatency,c+i.targetduration),d=h<u,f=Ys(r)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(d&&h>.05&&this.forwardBufferLength>1&&!f){const g=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20,y=Math.min(g,Math.max(1,m));this.changeMediaPlaybackRate(s,y)}else s.playbackRate!==1&&s.playbackRate!==0&&this.changeMediaPlaybackRate(s,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;const t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const s=this.levelDetails;return s?t.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||!this.hls)return null;const t=this.hls.config,{holdBack:s,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,c=this.hls.userConfig;let h=l&&i||s;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||h===0)&&(h=a!==void 0?a:o*r);const u=r;return h+Math.min(this.stallCount*t.liveSyncOnStallIncrease,u)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.hls.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null||!this.hls)return 0;const t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.ERROR,this.onError,this),e.on(p.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.ERROR,this.onError,this),e.off(p.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.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(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var s;const i=this.hls,r=this.media||t.event.appendInPlace&&(i==null||(s=i.interstitialsManager)==null?void 0:s.playerQueue.reduce((a,o)=>a||o.media,null));i&&r&&r.playbackRate>1&&r.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(e,t){var s;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Jn=500;class vf extends ur{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",H.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=D.IDLE,this.setInterval(Jn),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,part:i,success:r}=t;if(!r)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o;const l=(i||s).start;for(let h=0;h<a.length;h++)if(l>=a[h].start&&l<=a[h].end){o=a[h];break}const c=l+(i||s).duration;if(o?o.end=c:(o={start:l,end:c},a.push(o)),!i||c>=s.end){const h=this.fragmentTracker.fragBuffered(s);i&&h&&(h.range.subs={time:[{startPTS:s.start,endPTS:c}],partial:!0}),Ee(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,H.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===H.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==D.STOPPED&&(this.state=D.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Ao(this.levels,t)){this.levels=t.map(s=>new rs(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new rs(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,H.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];if(!(i!=null&&i.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==D.STOPPED&&this.setInterval(Jn)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const c=this.mainDetails;let h=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}if(l.details){var u;h=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}a.alignedSliding||(Ks(c,a,this),h=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,c&&!this.startFragRequested&&this.setStartPosition(c,h),o===i&&(this.hls.trigger(p.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){const{frag:t,part:s,payload:i}=e;!s||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,s)}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e;this.fragContextChanged(t)||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,null)}shouldDecrypt(e){const t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&Mt(t.method))}decryptPayload(e,t,s){const i=t.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,cr(i.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(p.FRAG_DECRYPTED,{frag:t,part:s,payload:a,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:s}),s||(this.warn(`${a.name}: ${a.message}`),this.state=D.IDLE)})}doTick(){if(this.state===D.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:s,levels:i}=this,r=i[s],a=r?.details;if(!a||this.waitForLive(r)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}const{config:o}=this,l=this.playhead,c=X.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:h,len:u}=c,d=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(u>d||u&&!this.buffering)return;let f=this.getNextFragment(h,a);if(!f)return;if(Ee(f)){var t;const g=f.sn-a.startSN,m=a.fragments[g-1];f.cc===m?.cc&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(m)===ye.NOT_LOADED&&(f=m)}this.loadFragment(f,r,h)}}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);(i===ye.NOT_LOADED||i===ye.PARTIAL)&&super.loadFragment(e,t,s)}get mediaBufferTimeRanges(){return new xf(this.tracksBuffered[this.currentTrackId]||[])}}class xf{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const Af={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},sl=n=>String.fromCharCode(Af[n]||n),Qe=15,Xe=42,If={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Lf={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Rf={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},bf={25:2,26:4,29:6,30:8,31:10,27:13,28:15},_f=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Df{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;le.log(`${this.time} [${e}] ${s}`)}}}const bt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Xi=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class il{constructor(){this.styles=Xi}get foreground(){return this.styles.foreground}set foreground(e){const t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){const t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=Xi}setStyles(e){const t=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(e,"foreground")?e.foreground:t.foreground,underline:s.call(e,"underline")?e.underline:t.underline,italics:s.call(e,"italics")?e.italics:t.italics,background:s.call(e,"background")?e.background:t.background,flash:s.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Pf{constructor(){this.uchar=" ",this.penState=new il}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}class Cf{constructor(e){this.chars=[],this.pos=0,this.currPenState=new il,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Xe;t++)this.chars.push(new Pf);this.logger=e}equals(e){const t=this.chars,s=e.chars;for(let i=0;i<Xe;i++){const r=t[i],a=s[i];if(r.uchar!==a.uchar)return!1;const o=r.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Xe;t++)this.chars[t].copy(e.chars[t])}isEmpty(){const e=this.chars;for(let t=0;t<Xe;t++){const s=e[t];if(s.uchar!==" ")return!1;const i=s.penState.styles;if(i!==Xi&&(i.foreground!=="white"||i.underline||i.italics||i.background!=="black"||i.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Xe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Xe-1)}moveCursor(e){const t=Math.min(this.pos+e,Xe);if(e>1)for(let s=this.pos+1;s<t;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=sl(e);if(this.pos>=Xe){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Xe;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Xe;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Ri{constructor(e){this.rows=[],this.currRow=Qe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Qe;t++)this.rows.push(new Cf(e));this.logger=e}reset(){for(let e=0;e<Qe;e++)this.rows[e].clear();this.currRow=Qe-1}equals(e){let t=!0;for(let s=0;s<Qe;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Qe;t++){const s=this.rows[t].chars,i=e.rows[t].chars;for(let r=0;r<Xe;r++){const a=s[r],o=i[r];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Qe;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+fe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Qe;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+fe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Qe;r++){const a=this.rows[r].getTextString();a&&(i=r+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
42
|
+
`)),s}getTextAndFormat(){return this.rows}}class kf{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Ri(s),this.nonDisplayedMemory=new Ri(s),this.lastOutputScreen=new Ri(s),this.currRollUpRow=this.displayedMemory.rows[Qe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Qe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+fe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class ea{constructor(e,t,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=wf(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Df,this.field=e,this.outputFilters=[null,t,s]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var s;this.outputFilters[e]=t,(s=this.channels[e])==null||s.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new kf(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+bt([t[s],t[s+1]])+"] -> ("+bt([i,r])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(Of(i,r,l)){Rs(null,null,l),this.logger.log(3,()=>"Repeated command ("+bt([i,r])+") is dropped");continue}Rs(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else Rs(null,null,l);if(!a&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.getChannel(h).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+bt([i,r])+" orig: "+bt([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,a=this.getChannel(r);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+bt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const a=e<=23?1:2;return t>=64&&t<=95?s=a===1?If[e]:Rf[e]:s=a===1?Lf[e]:bf[e],this.getChannel(a).setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+sl(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+bt(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=_f[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Rs(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Rs(n,e,t){t.a=n,t.b=e}function Of(n,e,t){return t.a===n&&t.b===e}function wf(){return{a:null,b:null}}class bs{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Mf{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ta(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new bs(this,"textTrack1"),t=new bs(this,"textTrack2"),s=new bs(this,"textTrack3"),i=new bs(this,"textTrack4");this.cea608Parser1=new ea(1,e,t),this.cea608Parser2=new ea(3,s,i)}addCues(e,t,s,i,r){let a=!1;for(let l=r.length;l--;){const c=r[l],h=Ff(c[0],c[1],t,s);if(h>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,h/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){const l=this.cueCache[e];if(l){const c=this.Cues.newCue(null,t,s,i);c.length&&l.push.apply(l,c)}else{const c=this.captionsTracks[e].track;this.Cues.newCue(c,t,s,i)}}else{var o;const l=this.Cues.newCue(null,t,s,i),c=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:c})}}onInitPtsFound(e,{id:t,timestampOffsets:s}){const{unparsedVttFrags:i}=this;t===H.MAIN&&(this.initPTS=s),i.length&&(this.unparsedVttFrags=[],i.forEach(r=>{this.initPTS[r.frag.cc]?this.onFragLoaded(p.FRAG_LOADED,r):this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,cueCache:i,media:r}=this,{label:a,languageCode:o}=t[e];r&&(i[e]=[],s[e]=br(r,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:i,cueCache:r}=this;for(const a in i)i[a].remove(),delete r[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ta(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!Ao(this.tracks,s)){const i=s.map(r=>({label:r.name,kind:r.type.toLowerCase(),default:r.default,subtitleTrack:r}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.level<this.tracks.length&&s.type===H.SUBTITLE){var r;if(i.byteLength||(r=s.initSegment)!=null&&(r=r.data)!=null&&r.byteLength){const a=s.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){const l=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),l?.textCodec===Wi?this._parseIMSC1(t):this._parseVTTs(t)}}else{const a="part"in t?t.part:null;this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){const{frag:t,payload:s}=e,i="part"in e?e.part:null,r=this.hls;Hn(s,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:i})},a=>{r.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),r.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:i,error:a})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,r="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[s.cc]&&l===-1){o.push(e);return}const c=this.hls,h=(t=s.initSegment)==null?void 0:t.data,u=h?He(h,new Uint8Array(i)).buffer:i;Kd(u,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!h?r:s).start,d=>{this._appendCues(d,s.level),c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},d=>{const f=d.message.startsWith("Missing initPTS");if(c.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${d}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:d})})}_fallbackToIMSC1(e){const{frag:t,payload:s}=e,i=this.tracks[t.level];i.textCodec||Hn(s,this.initPTS[t.cc],()=>{i.textCodec=Wi,this._parseIMSC1(e)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){var i;const r=(i=this.tracks[t].trackNode)==null?void 0:i.track;if(!r||r.mode==="disabled")return;e.forEach(a=>qi(r,a))}else{const r=this.tracks[t];if(!r)return;const a=r.default?"default":"subtitles"+t;s.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===H.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===H.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const a=i[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var s;const{type:i,timeRanges:r}=t;if(i==="video"&&(s=r[i])!=null&&s.length){const{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var c;const h=(c=a[l])==null?void 0:c.track;if(h){const u=o[l];for(let d=0;d<u.length;d++)qi(h,u[d])}delete o[l]})}}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<i)){if(!a||a==="video"){const{captionsTracks:l,cueCache:c}=this;Object.keys(l).forEach(h=>ji(l[h].track,s,i)),Object.keys(c).forEach(h=>{const u=c[h];for(let d=u.length;d--;){const f=u[d];f.startTime>=s&&f.endTime<=i&&u.splice(d,1)}})}this.config.renderTextTracksNatively&&s===0&&r!==void 0&&this.tracks.forEach(l=>{var c;const h=(c=l.trackNode)==null?void 0:c.track;h&&ji(h,s,r)})}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const a=e[i++],o=127&e[i++],l=127&e[i++];if(o===0&&l===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}}function Ff(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function ta(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Nf=/\s/,Bf={newCue(n,e,t,s){const i=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let m=0;m<r.chars.length;m++)Nf.test(r.chars[m].uchar)&&o?l++:(c+=r.chars[m].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=qo(c.trim()),g=Rr(e,t,f);n!=null&&(u=n.cues)!=null&&u.getCueById(g)||(a=new h(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>qi(n,d))),i}};class rl{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Ji}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Zt(e,t,!0))this.retry(e);else{var s;le.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=er(e,s.retry),s.retry++,le.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function $f(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Uf=/(\d+)-(\d+)\/(\d+)/;class sa extends rl{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||Hf}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:t,stats:s}=this;if(!e||!t)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const i=Gf(t,this.controller.signal),r=t.responseType==="arraybuffer",a=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=o&&B(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(os(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var u;this.response=h;const d=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(d-s.loading.start)),!h.ok){const{status:g,statusText:m}=h;throw new Yf(m||"fetch, bad network response",g,h)}s.loading.first=d,s.total=Kf(h.headers)||s.total;const f=(u=this.callbacks)==null?void 0:u.onProgress;return f&&B(e.highWaterMark)?this.loadProgressively(h,s,t,e.highWaterMark,f):r?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var u,d;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const g=h[a];g&&(s.loaded=s.total=g);const m={url:f.url,data:h,code:f.status},y=(u=this.callbacks)==null?void 0:u.onProgress;y&&!B(e.highWaterMark)&&y(s,t,h,f),(d=this.callbacks)==null||d.onSuccess(m,s,t,f)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=h&&h.code||0,d=h?h.message:null,f=e.loadPolicy.errorRetry,g=s.retry,m={url:t.url,data:void 0,code:u};if(Zt(f,g,!1,m))this.retry(f);else{var y;le.error(`${u} while loading ${t.url}`),(y=this.callbacks)==null||y.onError({code:u,text:d},t,h?h.details:null,s)}})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const a=new ro,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush().buffer,e)):r(t,s,h.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function Gf(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ue({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function Vf(n){const e=Uf.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Kf(n){const e=n.get("Content-Range");if(e){const s=Vf(e);if(B(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function Hf(n,e){return new self.Request(n.url,e)}class Yf extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Wf=(n,e,t)=>Math.max(e,Math.min(n,t)),qf=/^age:\s*[\d.]+\s*$/im;class nl extends rl{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r.call(this,s,t.url,t)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r.call(this,s,t.url,t)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&B(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const c=t.status,h=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){const g=h??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const m=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=m,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(s,e,g,t);const E={url:t.responseURL,data:g,code:c};e.rangeEnd&&m!==e.rangeEnd-e.rangeStart&&le.warn(`Payload length ${m} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:c};if(Zt(u,d,!1,f))this.retry(u);else{var l;le.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,s)}}}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&qf.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const jf={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},zf=j(j({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:nl,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:ja,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:jf},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:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},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:Jo,abrController:Oc,bufferController:vu,capLevelController:Er,errorController:Nc,fpsController:Fd,id3TrackController:sf,gapController:ef,latencyController:Sf},Xf()),{},{subtitleStreamController:vf,subtitleTrackController:Zd,timelineController:Mf,audioStreamController:mu,audioTrackController:pu,emeController:Ft,cmcdController:Dd,contentSteeringController:Cd,iframeController:hf,interstitialsController:Tf});function Xf(){return{cueHandler:Bf,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Qf(n,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){const a=e.liveMaxUnchangedPlaylistRefresh,o=Wf(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}const s=Qi(n),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];r.forEach(h=>{const u=`${a}Loading${h}`,d=e[u];if(d!==void 0&&l){c.push(u);const f=s[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${o}": ${fe(e[o])}`)}),j(j({},s),e)}function Qi(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(Qi):Object.keys(n).reduce((e,t)=>(e[t]=Qi(n[t]),e),{}):n}function Zf(n,e){const t=n.loader;t!==sa&&t!==nl?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):$f()&&(n.loader=sa,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Jf extends yr{constructor(e,t){super(e,"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=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,l=!1,c=!1,h=!1;t.levels.forEach(u=>{const d=u.attrs,f=ia(u,s),{audioCodec:g,videoCodec:m,imageCodec:y,width:E,height:S}=u;if(!f){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}o||(o=!!(E&&S)),l||(l=!!m),c||(c=!!g),h||(h=!!y);const{CODECS:T,"FRAME-RATE":v,"HDCP-LEVEL":x,"PATHWAY-ID":A,RESOLUTION:I,"VIDEO-RANGE":b}=d,L=`${`${A||"."}-`}${u.bitrate}-${I}-${v}-${T}-${b}-${x}`;if(r[L])if(r[L].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const P=a[L]+=1;u.attrs["PATHWAY-ID"]=new Array(P+1).join(".");const C=this.createLevel(u);r[L]=C,i.push(C)}else u.iframes||(r[L].addGroupId("audio",d.AUDIO),r[L].addGroupId("text",d.SUBTITLES));else{const P=this.createLevel(u);r[L]=P,a[L]=1,i.push(P)}}),this.filterAndSortMediaOptions(i,t,o,l,c,h)}createLevel(e){const t=new rs(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!ol(s.videoCodec,this.hls.config.preferManagedMediaSource)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=ka(i,[])}return t}filterAndSortMediaOptions(e,t,s,i,r,a){var o;let l=[],c=[],h=e;const u=((o=t.stats)==null?void 0:o.parsing)||{},d=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(h=h.filter(({videoCodec:x,videoRange:A,width:I,height:b})=>(!!x||!!(I&&b))&&Ic(A))),i&&a&&(h=h.filter(x=>!x.imageCodec)),h.length===0){Promise.resolve().then(()=>{if(this.hls){let x="no level with compatible codecs found in manifest",A=x;t.levels.length&&(A=`one or more CODECS in variant not supported: ${fe(t.levels.map(b=>b.attrs.CODECS).filter((b,_,L)=>L.indexOf(b)===_))}`,this.warn(A),x+=` (${A})`);const I=new Error(x);this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:I,reason:A})}}),u.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(x=>!x.audioCodec||al(x.audioCodec,d)),ra(l)),t.subtitles&&(c=t.subtitles,ra(c));const f=h.slice(0);h.sort((x,A)=>{if(x.attrs["HDCP-LEVEL"]!==A.attrs["HDCP-LEVEL"])return(x.attrs["HDCP-LEVEL"]||"")>(A.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&x.height!==A.height)return x.height-A.height;if(x.frameRate!==A.frameRate)return x.frameRate-A.frameRate;if(x.videoRange!==A.videoRange)return Bs.indexOf(x.videoRange)-Bs.indexOf(A.videoRange);if(x.videoCodec!==A.videoCodec){const I=Br(x.videoCodec),b=Br(A.videoCodec);if(I!==b)return b-I}if(x.uri===A.uri&&x.codecSet!==A.codecSet){const I=Fs(x.codecSet),b=Fs(A.codecSet);if(I!==b)return b-I}return x.averageBitrate!==A.averageBitrate?x.averageBitrate-A.averageBitrate:0});let g=f[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==f.length)){for(let x=0;x<f.length;x++)if(f[x].pathwayId===h[0].pathwayId){g=f[x];break}}this._levels=h;for(let x=0;x<h.length;x++)if(h[x]===g){var m;this._firstLevel=x;const A=g.bitrate,I=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${A}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){const b=Math.min(A,this.hls.config.abrEwmaDefaultEstimateMax);b>I&&I===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}const y=t.iframeVariants.filter(x=>ia(x,d));this._iframeVariants=y;const E=r&&!i,S=this.hls.config,T=!!(S.audioStreamController&&S.audioTrackController),v={levels:h,audioTracks:l,subtitleTracks:c,iframeVariants:y,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:T&&!E&&l.some(x=>!!x.url)};u.end=performance.now(),this.hls.trigger(p.MANIFEST_PARSED,v)}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(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,i?.details,c);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===se.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===H.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(i,t,l)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(p.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){const t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){const i=this.hls.config.abrSwitchInterval;if(i>0){const r=performance.now(),a=r-this.lastABRSwitchTime,o=i*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${i}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${i}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));to(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(p.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function al(n,e){return ss(n,"audio",e)}function ol(n,e){return ss(n,"video",e)}function ia(n,e){let{audioCodec:t,videoCodec:s}=n;t&&(n.audioCodec=t=Ns(t,e)||void 0),s&&(s=n.videoCodec=mc(s));const{unknownCodecs:i}=n;return!(i?.length||0||t&&!al(t,e)||s&&!ol(s,e))}function ra(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class eg extends Ge{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyLoaderInfo){const i=this.keyLoaderInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}destroy(){for(const e in this.keyLoaderInfo){const t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,s){return this.emeController?this.emeController.loadClear(e,t,s):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,t,s)):this.loadInternal(e,t)}loadInternal(e,t,s){s&&e.setKeyFormat(s);const i=e.decryptdata;if(!i){const a=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(pt(e,R.KEY_LOAD_ERROR,a))}const r=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(r):t?t.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(pt(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){const s=zl(e.initSegment.data);if(s.length){let i=s[0];const r=e.decryptdata.uri;if(i.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ie(i)} keyUri: ${r}`),gt.setKeyIdForUri(r,i);else{const a=gt.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Ie(a)} keyUri: ${r}`),i=a}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(pt(e,R.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){const t=e.decryptdata,s=t.uri;if(!s)return Promise.reject(pt(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return t.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(c=>(t.key=i.decryptdata.key,j(j({},c),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ie(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);const r=this.config,a=r.loader,o=new a(r);e.keyLoader=o;const l=this.keyLoaderInfo[s]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((c,h)=>{const u={type:se.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:s},d=r.keyLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,y,E,S)=>{const{frag:T,keyInfo:v,url:x}=E;if(!T.decryptdata||v!==this.keyLoaderInfo[x])return h(pt(T,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),S));v.decryptdata.key=T.decryptdata.key=new Uint8Array(m.data),T.keyLoader=v.loader=v.keyLoadPromise=null,c({frag:T,keyInfo:v})},onError:(m,y,E,S)=>{this.resetLoader(y),h(pt(e,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),E,j({url:s,data:void 0},m)))},onTimeout:(m,y,E)=>{this.resetLoader(y),h(pt(e,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),E))},onAbort:(m,y,E)=>{this.resetLoader(y),h(pt(e,R.INTERNAL_ABORTED,new Error("key loading aborted"),E))}};o.load(u,f,g)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}}function pt(n,e=R.KEY_LOAD_ERROR,t,s,i){return new rt({type:q.NETWORK_ERROR,details:e,fatal:!1,frag:n,response:i,error:t,networkDetails:s||null})}function na(n){const{type:e}=n;switch(e){case se.AUDIO_TRACK:return H.AUDIO;case se.SUBTITLE_TRACK:return H.SUBTITLE;default:return H.MAIN}}function bi(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class tg{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:se.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:se.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:se.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:se.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[se.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[se.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const c=this.hls.logger,h=i.context;if(h?.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===se.MANIFEST?r=s.manifestLoadPolicy.default:r=ue({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),B((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===se.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===se.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===se.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const h=c.partTarget,u=c.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=ue({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,h,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=c.data;h.parsing.start=performance.now(),ot.isMediaPlaylist(g)||u.type!==se.MANIFEST?this.handleTrackOrLevelPlaylist(c,h,u,d||null,f):this.handleMasterPlaylist(c,h,u,d)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};i.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,a=e.data,o=bi(e,s),l=ot.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,i,t);return}const{contentSteering:c,levels:h,iframeVariants:u,sessionData:d,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,h.forEach(T=>{const{unknownCodecs:v}=T;if(v){const{preferManagedMediaSource:x}=this.hls.config;let{audioCodec:A,videoCodec:I}=T;for(let b=v.length;b--;){const _=v[b];ss(_,"audio",x)?(T.audioCodec=A=A?`${A},${_}`:_,Nt.audio[A.substring(0,4)]=2,v.splice(b,1)):ss(_,"video",x)&&(T.videoCodec=I=I?`${I},${_}`:_,Nt.video[I.substring(0,4)]=2,v.splice(b,1))}}});const{AUDIO:y=[],SUBTITLES:E,"CLOSED-CAPTIONS":S}=ot.parseMasterPlaylistMedia(a,o,l);y.length&&!y.some(v=>!v.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new pe({}),bitrate:0,url:""})),r.trigger(p.MANIFEST_LOADED,{levels:h,audioTracks:y,subtitles:E,iframeVariants:u,captions:S,contentSteering:c,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,i,r){const a=this.hls,{id:o,level:l,type:c}=s,h=bi(e,s),u=B(l)?l:B(o)?o:0,d=na(s),f=ot.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(c===se.MANIFEST){const g={attrs:new pe({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+Za(f,0),a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===se.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===se.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===se.AUDIO_TRACK||e.type===se.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=R.UNKNOWN,c=!1;const h=this.getInternalLoader(e);switch(e.type){case se.MANIFEST:l=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,c=!0;break;case se.LEVEL:l=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,c=!1;break;case se.AUDIO_TRACK:l=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case se.SUBTITLE_TRACK:l=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(e.type);const u={type:q.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){let d=e.url;t&&"url"in t&&(d=t.url),u.response=j({url:d,data:void 0},i)}this.hls.trigger(p.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,a){const o=this.hls,{type:l,level:c,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:f}=i,g=bi(t,i),m=na(i);let y=typeof i.level=="number"&&m===H.MAIN?c:void 0;h&&"iframes"in h&&h.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:i,level:y,parent:m,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const S=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:S,reason:S.message,response:t,context:i,level:y,parent:m,networkDetails:r,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case se.MANIFEST:case se.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){const S=o.levels.indexOf(h);S>-1&&(y=S)}}o.trigger(p.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:l===se.MANIFEST,context:i});break;case se.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break;case se.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break}}}class Tt{static get version(){return as}static isMSESupported(){return Zo()}static isSupported(){return rf()}static getMediaSource(){return xt()}static get Events(){return p}static get MetadataSchema(){return Oe}static get ErrorTypes(){return q}static get ErrorDetails(){return R}static get DefaultConfig(){return Tt.defaultConfig?Tt.defaultConfig:zf}static set DefaultConfig(e){Tt.defaultConfig=e}constructor(e={}){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 dr,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 t=this.logger=xl(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),s=this.config=Qf(Tt.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Zf(s,t);const{streamController:i,abrController:r,bufferController:a,capLevelController:o,errorController:l,fpsController:c,id3TrackController:h,iframeController:u,gapController:d}=s,f=new l(this),g=this.abrController=new r(this),m=new Bc(this),y=s.interstitialsController,E=y?this.interstitialsController=new y(this,Tt):null,S=a?this.bufferController=new a(this,m):null,T=o?this.capLevelController=new o(this):null,v=c?new c(this):null,x=s.cmcdController,A=x?this.cmcdController=new x(this):null,I=new tg(this),b=s.contentSteeringController,_=b?new b(this):null,L=this.levelController=new Jf(this,_),P=h?new h(this):void 0,C=new eg(this.config,this.logger),F=this.streamController=new i(this,m,C),V=this.gapController=d?new d(this,m):void 0;T&&T.setStreamController(F);const $=[I,L,F];E&&$.splice(1,0,E),_&&$.splice(1,0,_),this.networkControllers=$;const k=[g];S&&k.push(S),V&&k.push(V),T&&k.push(T),v&&(v.setStreamController(F),k.push(v)),P&&k.push(P),k.push(m),this.audioTrackController=this.createController(s.audioTrackController,$);const w=s.audioStreamController;w&&$.push(this.audioStreamController=new w(this,m,C)),this.subtitleTrackController=this.createController(s.subtitleTrackController,$);const O=s.subtitleStreamController;O&&$.push(this.subtititleStreamController=new O(this,m,C)),this.createController(s.timelineController,k),C.emeController=this.emeController=this.createController(s.emeController,k),A&&k.push(A),this.latencyController=this.createController(s.latencyController,k),this.coreComponents=k,this.iframeController=u?new u(this,Tt):void 0,$.push(f);const N=f.onErrorOut;typeof N=="function"&&this.on(p.ERROR,N,f),this.on(p.MANIFEST_LOADED,I.onManifestLoaded,I)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===p.ERROR;this.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(p.ERROR,{type:q.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(p.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(p.MEDIA_DETACHING,e),this._media=null,this.trigger(p.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;const t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,s={transferMedia:t};return this.trigger(p.MEDIA_DETACHING,s),this.trigger(p.MEDIA_DETACHED,s),t}loadSource(e){var t;this.stopLoad();const s=this.media,i=this._url,r=this._url=Zi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(p.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==D.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[H.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[H.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[H.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=this.started,s=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=fa()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=this.capLevelController,s=!!e;t&&s!==this.config.capLevelToPlayerSize&&(s?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Ac(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){const{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Fa(t);return Oa(e,s,navigator.mediaCapabilities)}}Tt.defaultConfig=void 0;export{Oc as AbrController,pe as AttrList,mu as AudioStreamController,pu as AudioTrackController,rl as BaseLoader,yr as BasePlaylistController,aa as BaseSegment,ur as BaseStreamController,vu as BufferController,Dd as CMCDController,Er as CapLevelController,or as ChunkMetadata,Cd as ContentSteeringController,Bf as Cues,Ka as DateRange,Ft as EMEController,Le as ErrorActionFlags,Nc as ErrorController,R as ErrorDetails,q as ErrorTypes,p as Events,Fd as FPSController,sa as FetchLoader,us as Fragment,Tt as Hls,Ps as HlsSkip,Vr as HlsUrlParameters,De as KeySystemFormats,me as KeySystems,rs as Level,Qc as LevelDetails,gt as LevelKey,Ji as LoadStats,se as LoaderContextType,ot as M3U8Parser,Oe as MetadataSchema,Re as NetworkErrorAction,dl as Part,H as PlaylistLevelType,vf as SubtitleStreamController,Zd as SubtitleTrackController,Mf as TimelineController,nl as XhrLoader,Tt as default,$f as fetchSupported,xt as getMediaSource,Zo as isMSESupported,rf as isSupported,ja as requestMediaKeySystemAccess};
|