friendica-github/view/js/hls/hls.light.min.js.map
2024-09-14 18:06:59 +00:00

1 line
No EOL
1.3 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"version":3,"file":"hls.light.js.min.map","sources":["node_modules/url-toolkit/src/url-toolkit.js","src/polyfills/number.ts","src/events.ts","src/errors.ts","src/utils/logger.ts","src/utils/attr-list.ts","src/loader/date-range.ts","src/loader/load-stats.ts","src/loader/fragment.ts","src/loader/level-details.ts","src/empty.js","src/utils/typed-array.ts","src/demux/id3.ts","src/utils/hex.ts","src/utils/mp4-tools.ts","src/loader/level-key.ts","src/utils/mediasource-helper.ts","src/utils/codecs.ts","src/loader/m3u8-parser.ts","src/types/loader.ts","src/loader/playlist-loader.ts","src/utils/texttrack-utils.ts","src/types/demuxer.ts","src/controller/id3-track-controller.ts","src/controller/latency-controller.ts","src/types/level.ts","src/utils/level-helper.ts","src/utils/error-helper.ts","src/utils/binary-search.ts","src/controller/fragment-finders.ts","src/controller/error-controller.ts","src/controller/base-playlist-controller.ts","src/utils/ewma.ts","src/utils/ewma-bandwidth-estimator.ts","src/utils/hdr.ts","src/utils/rendition-helper.ts","src/controller/abr-controller.ts","src/utils/buffer-helper.ts","src/controller/buffer-operation-queue.ts","src/controller/buffer-controller.ts","src/controller/cap-level-controller.ts","src/controller/fps-controller.ts","src/controller/content-steering-controller.ts","src/utils/xhr-loader.ts","src/demux/chunk-cache.ts","src/utils/fetch-loader.ts","src/controller/level-controller.ts","src/config.ts","src/controller/fragment-tracker.ts","src/loader/fragment-loader.ts","src/loader/key-loader.ts","src/task-loop.ts","src/types/transmuxer.ts","src/utils/discontinuities.ts","src/crypt/aes-crypto.ts","src/crypt/fast-aes-key.ts","src/crypt/aes-decryptor.ts","src/crypt/decrypter.ts","src/utils/time-ranges.ts","src/controller/base-stream-controller.ts","src/is-supported.ts","src/demux/dummy-demuxed-track.ts","src/demux/audio/base-audio-demuxer.ts","src/demux/audio/adts.ts","src/demux/audio/mpegaudio.ts","src/demux/audio/aacdemuxer.ts","src/demux/mp4demuxer.ts","src/demux/video/base-video-parser.ts","src/demux/video/exp-golomb.ts","src/demux/video/avc-video-parser.ts","src/demux/sample-aes.ts","src/demux/tsdemuxer.ts","src/demux/audio/mp3demuxer.ts","src/demux/audio/dolby.ts","src/remux/aac-helper.ts","src/remux/mp4-generator.ts","src/utils/timescale-conversion.ts","src/remux/mp4-remuxer.ts","src/remux/passthrough-remuxer.ts","src/utils/global.ts","src/demux/transmuxer.ts","node_modules/eventemitter3/index.js","src/demux/transmuxer-worker.ts","src/demux/transmuxer-interface.ts","src/demux/inject-worker.ts","src/controller/gap-controller.ts","src/controller/stream-controller.ts","src/hls.ts"],"sourcesContent":["// see https://tools.ietf.org/html/rfc1808\n\n(function (root) {\n var URL_REGEX =\n /^(?=((?:[a-zA-Z0-9+\\-.]+:)?))\\1(?=((?:\\/\\/[^\\/?#]*)?))\\2(?=((?:(?:[^?#\\/]*\\/)*[^;?#\\/]*)?))\\3((?:;[^?#]*)?)(\\?[^#]*)?(#[^]*)?$/;\n var FIRST_SEGMENT_REGEX = /^(?=([^\\/?#]*))\\1([^]*)$/;\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/)[^\\/]*(?=\\/)/g;\n\n var URLToolkit = {\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n // E.g\n // With opts.alwaysNormalize = false (default, spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n // With opts.alwaysNormalize = true (not spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n opts = opts || {};\n // remove any remaining space and CRLF\n baseURL = baseURL.trim();\n relativeURL = relativeURL.trim();\n if (!relativeURL) {\n // 2a) If the embedded URL is entirely empty, it inherits the\n // entire base URL (i.e., is set equal to the base URL)\n // and we are done.\n if (!opts.alwaysNormalize) {\n return baseURL;\n }\n var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n if (!basePartsForNormalise) {\n throw new Error('Error trying to parse base URL.');\n }\n basePartsForNormalise.path = URLToolkit.normalizePath(\n basePartsForNormalise.path\n );\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\n }\n var relativeParts = URLToolkit.parseURL(relativeURL);\n if (!relativeParts) {\n throw new Error('Error trying to parse relative URL.');\n }\n if (relativeParts.scheme) {\n // 2b) If the embedded URL starts with a scheme name, it is\n // interpreted as an absolute URL and we are done.\n if (!opts.alwaysNormalize) {\n return relativeURL;\n }\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n return URLToolkit.buildURLFromParts(relativeParts);\n }\n var baseParts = URLToolkit.parseURL(baseURL);\n if (!baseParts) {\n throw new Error('Error trying to parse base URL.');\n }\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n baseParts.netLoc = pathParts[1];\n baseParts.path = pathParts[2];\n }\n if (baseParts.netLoc && !baseParts.path) {\n baseParts.path = '/';\n }\n var builtParts = {\n // 2c) Otherwise, the embedded URL inherits the scheme of\n // the base URL.\n scheme: baseParts.scheme,\n netLoc: relativeParts.netLoc,\n path: null,\n params: relativeParts.params,\n query: relativeParts.query,\n fragment: relativeParts.fragment,\n };\n if (!relativeParts.netLoc) {\n // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n // Step 7. Otherwise, the embedded URL inherits the <net_loc>\n // (if any) of the base URL.\n builtParts.netLoc = baseParts.netLoc;\n // 4) If the embedded URL path is preceded by a slash \"/\", the\n // path is not relative and we skip to Step 7.\n if (relativeParts.path[0] !== '/') {\n if (!relativeParts.path) {\n // 5) If the embedded URL path is empty (and not preceded by a\n // slash), then the embedded URL inherits the base URL path\n builtParts.path = baseParts.path;\n // 5a) if the embedded URL's <params> is non-empty, we skip to\n // step 7; otherwise, it inherits the <params> of the base\n // URL (if any) and\n if (!relativeParts.params) {\n builtParts.params = baseParts.params;\n // 5b) if the embedded URL's <query> is non-empty, we skip to\n // step 7; otherwise, it inherits the <query> of the base\n // URL (if any) and we skip to step 7.\n if (!relativeParts.query) {\n builtParts.query = baseParts.query;\n }\n }\n } else {\n // 6) The last segment of the base URL's path (anything\n // following the rightmost slash \"/\", or the entire path if no\n // slash is present) is removed and the embedded URL's path is\n // appended in its place.\n var baseURLPath = baseParts.path;\n var newPath =\n baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +\n relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize\n ? URLToolkit.normalizePath(relativeParts.path)\n : relativeParts.path;\n }\n return URLToolkit.buildURLFromParts(builtParts);\n },\n parseURL: function (url) {\n var parts = URL_REGEX.exec(url);\n if (!parts) {\n return null;\n }\n return {\n scheme: parts[1] || '',\n netLoc: parts[2] || '',\n path: parts[3] || '',\n params: parts[4] || '',\n query: parts[5] || '',\n fragment: parts[6] || '',\n };\n },\n normalizePath: function (path) {\n // The following operations are\n // then applied, in order, to the new path:\n // 6a) All occurrences of \"./\", where \".\" is a complete path\n // segment, are removed.\n // 6b) If the path ends with \".\" as a complete path segment,\n // that \".\" is removed.\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n // complete path segment not equal to \"..\", are removed.\n // Removal of these path segments is performed iteratively,\n // removing the leftmost matching pattern on each iteration,\n // until no matching pattern remains.\n // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n // complete path segment not equal to \"..\", that\n // \"<segment>/..\" is removed.\n while (\n path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length\n ) {}\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function (parts) {\n return (\n parts.scheme +\n parts.netLoc +\n parts.path +\n parts.params +\n parts.query +\n parts.fragment\n );\n },\n };\n\n if (typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if (typeof define === 'function' && define.amd)\n define([], function () {\n return URLToolkit;\n });\n else if (typeof exports === 'object') exports['URLToolkit'] = URLToolkit;\n else root['URLToolkit'] = URLToolkit;\n})(this);\n","// https://caniuse.com/mdn-javascript_builtins_number_isfinite\nexport const isFiniteNumber =\n Number.isFinite ||\n function (value) {\n return typeof value === 'number' && isFinite(value);\n };\n\n// https://caniuse.com/mdn-javascript_builtins_number_issafeinteger\nexport const isSafeInteger =\n Number.isSafeInteger ||\n function (value) {\n return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;\n };\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n","import {\n ManifestLoadedData,\n ManifestLoadingData,\n MediaAttachedData,\n MediaAttachingData,\n LevelLoadingData,\n LevelLoadedData,\n ManifestParsedData,\n LevelUpdatedData,\n LevelsUpdatedData,\n FragParsingUserdataData,\n FragDecryptedData,\n FragLoadedData,\n InitPTSFoundData,\n CuesParsedData,\n SubtitleFragProcessedData,\n NonNativeTextTracksData,\n FragLoadingData,\n AudioTrackLoadedData,\n SubtitleTrackLoadedData,\n ErrorData,\n AudioTrackSwitchingData,\n AudioTrackSwitchedData,\n KeyLoadedData,\n KeyLoadingData,\n SubtitleTrackSwitchData,\n SubtitleTracksUpdatedData,\n LevelSwitchedData,\n FragChangedData,\n BufferAppendingData,\n BufferCodecsData,\n FragParsingMetadataData,\n FragParsingInitSegmentData,\n FragBufferedData,\n BufferFlushingData,\n BufferEOSData,\n LevelSwitchingData,\n MaxAutoLevelUpdatedData,\n FPSDropLevelCappingData,\n FPSDropData,\n BufferCreatedData,\n BufferAppendedData,\n LevelPTSUpdatedData,\n FragParsedData,\n AudioTracksUpdatedData,\n FragLoadEmergencyAbortedData,\n BackBufferData,\n LiveBackBufferData,\n TrackLoadingData,\n BufferFlushedData,\n SteeringManifestLoadedData,\n} from './types/events';\n\nexport enum Events {\n // Fired before MediaSource is attaching to media element\n MEDIA_ATTACHING = 'hlsMediaAttaching',\n // Fired when MediaSource has been successfully attached to media element\n MEDIA_ATTACHED = 'hlsMediaAttached',\n // Fired before detaching MediaSource from media element\n MEDIA_DETACHING = 'hlsMediaDetaching',\n // Fired when MediaSource has been detached from media element\n MEDIA_DETACHED = 'hlsMediaDetached',\n // Fired when the buffer is going to be reset\n BUFFER_RESET = 'hlsBufferReset',\n // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS = 'hlsBufferCodecs',\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n BUFFER_CREATED = 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING = 'hlsBufferAppending',\n // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}\n BUFFER_APPENDED = 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n BUFFER_EOS = 'hlsBufferEos',\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n BUFFER_FLUSHING = 'hlsBufferFlushing',\n // fired when the media buffer has been flushed - data: { }\n BUFFER_FLUSHED = 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING = 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }\n MANIFEST_LOADED = 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED = 'hlsManifestParsed',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING = 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED = 'hlsLevelSwitched',\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n LEVEL_LOADING = 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }\n LEVEL_LOADED = 'hlsLevelLoaded',\n // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }\n LEVEL_UPDATED = 'hlsLevelUpdated',\n // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }\n LEVEL_PTS_UPDATED = 'hlsLevelPtsUpdated',\n // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }\n LEVELS_UPDATED = 'hlsLevelsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED = 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING = 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED = 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING = 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }\n AUDIO_TRACK_LOADED = 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED = 'hlsSubtitleTracksUpdated',\n // fired to notify that subtitle tracks were cleared as a result of stopping the media\n SUBTITLE_TRACKS_CLEARED = 'hlsSubtitleTracksCleared',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH = 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING = 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }\n SUBTITLE_TRACK_LOADED = 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED = 'hlsSubtitleFragProcessed',\n // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n CUES_PARSED = 'hlsCuesParsed',\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n NON_NATIVE_TEXT_TRACKS_FOUND = 'hlsNonNativeTextTracksFound',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }\n INIT_PTS_FOUND = 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING = 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED = 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }\n FRAG_LOADED = 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED = 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n FRAG_PARSING_INIT_SEGMENT = 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA = 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA = 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n // FRAG_PARSING_DATA = 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED = 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }\n FRAG_BUFFERED = 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED = 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP = 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }\n FPS_DROP_LEVEL_CAPPING = 'hlsFpsDropLevelCapping',\n // triggered when maxAutoLevel changes - data { autoLevelCapping, levels, maxAutoLevel, minAutoLevel, maxHdcpLevel }\n MAX_AUTO_LEVEL_UPDATED = 'hlsMaxAutoLevelUpdated',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n ERROR = 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n DESTROYING = 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING = 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }\n KEY_LOADED = 'hlsKeyLoaded',\n // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }\n LIVE_BACK_BUFFER_REACHED = 'hlsLiveBackBufferReached',\n // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }\n BACK_BUFFER_REACHED = 'hlsBackBufferReached',\n // fired after steering manifest has been loaded - data: { steeringManifest: SteeringManifest object, url: steering manifest URL }\n STEERING_MANIFEST_LOADED = 'hlsSteeringManifestLoaded',\n}\n\n/**\n * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.\n */\nexport interface HlsListeners {\n [Events.MEDIA_ATTACHING]: (\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) => void;\n [Events.MEDIA_ATTACHED]: (\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ) => void;\n [Events.MEDIA_DETACHING]: (event: Events.MEDIA_DETACHING) => void;\n [Events.MEDIA_DETACHED]: (event: Events.MEDIA_DETACHED) => void;\n [Events.BUFFER_RESET]: (event: Events.BUFFER_RESET) => void;\n [Events.BUFFER_CODECS]: (\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData,\n ) => void;\n [Events.BUFFER_CREATED]: (\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData,\n ) => void;\n [Events.BUFFER_APPENDING]: (\n event: Events.BUFFER_APPENDING,\n data: BufferAppendingData,\n ) => void;\n [Events.BUFFER_APPENDED]: (\n event: Events.BUFFER_APPENDED,\n data: BufferAppendedData,\n ) => void;\n [Events.BUFFER_EOS]: (event: Events.BUFFER_EOS, data: BufferEOSData) => void;\n [Events.BUFFER_FLUSHING]: (\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData,\n ) => void;\n [Events.BUFFER_FLUSHED]: (\n event: Events.BUFFER_FLUSHED,\n data: BufferFlushedData,\n ) => void;\n [Events.MANIFEST_LOADING]: (\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) => void;\n [Events.MANIFEST_LOADED]: (\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ) => void;\n [Events.MANIFEST_PARSED]: (\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) => void;\n [Events.LEVEL_SWITCHING]: (\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData,\n ) => void;\n [Events.LEVEL_SWITCHED]: (\n event: Events.LEVEL_SWITCHED,\n data: LevelSwitchedData,\n ) => void;\n [Events.LEVEL_LOADING]: (\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData,\n ) => void;\n [Events.LEVEL_LOADED]: (\n event: Events.LEVEL_LOADED,\n data: LevelLoadedData,\n ) => void;\n [Events.LEVEL_UPDATED]: (\n event: Events.LEVEL_UPDATED,\n data: LevelUpdatedData,\n ) => void;\n [Events.LEVEL_PTS_UPDATED]: (\n event: Events.LEVEL_PTS_UPDATED,\n data: LevelPTSUpdatedData,\n ) => void;\n [Events.LEVELS_UPDATED]: (\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData,\n ) => void;\n [Events.AUDIO_TRACKS_UPDATED]: (\n event: Events.AUDIO_TRACKS_UPDATED,\n data: AudioTracksUpdatedData,\n ) => void;\n [Events.AUDIO_TRACK_SWITCHING]: (\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData,\n ) => void;\n [Events.AUDIO_TRACK_SWITCHED]: (\n event: Events.AUDIO_TRACK_SWITCHED,\n data: AudioTrackSwitchedData,\n ) => void;\n [Events.AUDIO_TRACK_LOADING]: (\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData,\n ) => void;\n [Events.AUDIO_TRACK_LOADED]: (\n event: Events.AUDIO_TRACK_LOADED,\n data: AudioTrackLoadedData,\n ) => void;\n [Events.SUBTITLE_TRACKS_UPDATED]: (\n event: Events.SUBTITLE_TRACKS_UPDATED,\n data: SubtitleTracksUpdatedData,\n ) => void;\n [Events.SUBTITLE_TRACKS_CLEARED]: (\n event: Events.SUBTITLE_TRACKS_CLEARED,\n ) => void;\n [Events.SUBTITLE_TRACK_SWITCH]: (\n event: Events.SUBTITLE_TRACK_SWITCH,\n data: SubtitleTrackSwitchData,\n ) => void;\n [Events.SUBTITLE_TRACK_LOADING]: (\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData,\n ) => void;\n [Events.SUBTITLE_TRACK_LOADED]: (\n event: Events.SUBTITLE_TRACK_LOADED,\n data: SubtitleTrackLoadedData,\n ) => void;\n [Events.SUBTITLE_FRAG_PROCESSED]: (\n event: Events.SUBTITLE_FRAG_PROCESSED,\n data: SubtitleFragProcessedData,\n ) => void;\n [Events.CUES_PARSED]: (\n event: Events.CUES_PARSED,\n data: CuesParsedData,\n ) => void;\n [Events.NON_NATIVE_TEXT_TRACKS_FOUND]: (\n event: Events.NON_NATIVE_TEXT_TRACKS_FOUND,\n data: NonNativeTextTracksData,\n ) => void;\n [Events.INIT_PTS_FOUND]: (\n event: Events.INIT_PTS_FOUND,\n data: InitPTSFoundData,\n ) => void;\n [Events.FRAG_LOADING]: (\n event: Events.FRAG_LOADING,\n data: FragLoadingData,\n ) => void;\n // [Events.FRAG_LOAD_PROGRESS]: TodoEventType\n [Events.FRAG_LOAD_EMERGENCY_ABORTED]: (\n event: Events.FRAG_LOAD_EMERGENCY_ABORTED,\n data: FragLoadEmergencyAbortedData,\n ) => void;\n [Events.FRAG_LOADED]: (\n event: Events.FRAG_LOADED,\n data: FragLoadedData,\n ) => void;\n [Events.FRAG_DECRYPTED]: (\n event: Events.FRAG_DECRYPTED,\n data: FragDecryptedData,\n ) => void;\n [Events.FRAG_PARSING_INIT_SEGMENT]: (\n event: Events.FRAG_PARSING_INIT_SEGMENT,\n data: FragParsingInitSegmentData,\n ) => void;\n [Events.FRAG_PARSING_USERDATA]: (\n event: Events.FRAG_PARSING_USERDATA,\n data: FragParsingUserdataData,\n ) => void;\n [Events.FRAG_PARSING_METADATA]: (\n event: Events.FRAG_PARSING_METADATA,\n data: FragParsingMetadataData,\n ) => void;\n // [Events.FRAG_PARSING_DATA]: TodoEventType\n [Events.FRAG_PARSED]: (\n event: Events.FRAG_PARSED,\n data: FragParsedData,\n ) => void;\n [Events.FRAG_BUFFERED]: (\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData,\n ) => void;\n [Events.FRAG_CHANGED]: (\n event: Events.FRAG_CHANGED,\n data: FragChangedData,\n ) => void;\n [Events.FPS_DROP]: (event: Events.FPS_DROP, data: FPSDropData) => void;\n [Events.FPS_DROP_LEVEL_CAPPING]: (\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData,\n ) => void;\n [Events.MAX_AUTO_LEVEL_UPDATED]: (\n event: Events.MAX_AUTO_LEVEL_UPDATED,\n data: MaxAutoLevelUpdatedData,\n ) => void;\n [Events.ERROR]: (event: Events.ERROR, data: ErrorData) => void;\n [Events.DESTROYING]: (event: Events.DESTROYING) => void;\n [Events.KEY_LOADING]: (\n event: Events.KEY_LOADING,\n data: KeyLoadingData,\n ) => void;\n [Events.KEY_LOADED]: (event: Events.KEY_LOADED, data: KeyLoadedData) => void;\n [Events.LIVE_BACK_BUFFER_REACHED]: (\n event: Events.LIVE_BACK_BUFFER_REACHED,\n data: LiveBackBufferData,\n ) => void;\n [Events.BACK_BUFFER_REACHED]: (\n event: Events.BACK_BUFFER_REACHED,\n data: BackBufferData,\n ) => void;\n [Events.STEERING_MANIFEST_LOADED]: (\n event: Events.STEERING_MANIFEST_LOADED,\n data: SteeringManifestLoadedData,\n ) => void;\n}\nexport interface HlsEventEmitter {\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context,\n ): void;\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context,\n ): void;\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E): void;\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E],\n context?: Context,\n once?: boolean,\n ): void;\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][];\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1],\n ): boolean;\n listenerCount<E extends keyof HlsListeners>(event: E): number;\n}\n","export enum ErrorTypes {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR = 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR = 'mediaError',\n // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR = 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR = 'muxError',\n // Identifier for all other errors\n OTHER_ERROR = 'otherError',\n}\n\nexport enum ErrorDetails {\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 // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR = 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT = 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR = 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR = 'manifestIncompatibleCodecsError',\n // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: \"no fragments found in level\", level: index of the bad level }\n LEVEL_EMPTY_ERROR = 'levelEmptyError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR = 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT = 'levelLoadTimeOut',\n // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }\n LEVEL_PARSING_ERROR = 'levelParsingError',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR = 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR = 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT = 'audioTrackLoadTimeOut',\n // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n SUBTITLE_LOAD_ERROR = 'subtitleTrackLoadError',\n // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n SUBTITLE_TRACK_LOAD_TIMEOUT = 'subtitleTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR = 'fragLoadError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT = 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n FRAG_DECRYPT_ERROR = 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR = 'fragParsingError',\n // Identifier for a fragment or part load skipped because of a GAP tag or attribute\n FRAG_GAP = 'fragGap',\n // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }\n REMUX_ALLOC_ERROR = 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR = 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT = 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR = 'bufferAddCodecError',\n // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }\n BUFFER_INCOMPATIBLE_CODECS_ERROR = 'bufferIncompatibleCodecsError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR = 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR = 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR = 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR = 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE = 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL = 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION = 'internalException',\n // Identifier for an internal call to abort a loader\n INTERNAL_ABORTED = 'aborted',\n // Uncategorized error\n UNKNOWN = 'unknown',\n}\n","export interface ILogFunction {\n (message?: any, ...optionalParams: any[]): void;\n}\n\nexport interface ILogger {\n trace: ILogFunction;\n debug: ILogFunction;\n log: ILogFunction;\n warn: ILogFunction;\n info: ILogFunction;\n error: ILogFunction;\n}\n\nconst noop: ILogFunction = function () {};\n\nconst fakeLogger: ILogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop,\n};\n\nlet exportedLogger: ILogger = fakeLogger;\n\n// let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction consolePrintFn(type: string): ILogFunction {\n const func: ILogFunction = self.console[type];\n if (func) {\n return func.bind(self.console, `[${type}] >`);\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(\n debugConfig: boolean | ILogger,\n ...functions: string[]\n): void {\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type]\n ? debugConfig[type].bind(debugConfig)\n : consolePrintFn(type);\n });\n}\n\nexport function enableLogs(debugConfig: boolean | ILogger, id: string): void {\n // check that console is available\n if (\n (typeof console === 'object' && debugConfig === true) ||\n typeof debugConfig === 'object'\n ) {\n exportLoggerFunctions(\n debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error',\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log(\n `Debug logs enabled for \"${id}\" in hls.js version ${__VERSION__}`,\n );\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n } else {\n exportedLogger = fakeLogger;\n }\n}\n\nexport const logger: ILogger = exportedLogger;\n","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/;\nconst ATTR_LIST_REGEX = /(.+?)=(\".*?\"|.*?)(?:,|$)/g;\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nexport class AttrList {\n [key: string]: any;\n\n constructor(attrs: string | Record<string, any>) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n Object.assign(this, attrs);\n }\n\n get clientAttrs(): string[] {\n return Object.keys(this).filter((attr) => attr.substring(0, 2) === 'X-');\n }\n\n decimalInteger(attrName: string): number {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n hexadecimalInteger(attrName: string) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber(attrName: string): number {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n decimalFloatingPoint(attrName: string): number {\n return parseFloat(this[attrName]);\n }\n\n optionalFloat(attrName: string, defaultValue: number): number {\n const value = this[attrName];\n return value ? parseFloat(value) : defaultValue;\n }\n\n enumeratedString(attrName: string): string | undefined {\n return this[attrName];\n }\n\n bool(attrName: string): boolean {\n return this[attrName] === 'YES';\n }\n\n decimalResolution(attrName: string):\n | {\n width: number;\n height: number;\n }\n | undefined {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10),\n };\n }\n\n static parseAttrList(input: string): Record<string, any> {\n let match;\n const attrs = {};\n const quote = '\"';\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let value = match[2];\n\n if (\n value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === value.length - 1\n ) {\n value = value.slice(1, -1);\n }\n const name = match[1].trim();\n attrs[name] = value;\n }\n return attrs;\n }\n}\n","import { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\n\n// Avoid exporting const enum so that these values can be inlined\nconst enum DateRangeAttribute {\n ID = 'ID',\n CLASS = 'CLASS',\n START_DATE = 'START-DATE',\n DURATION = 'DURATION',\n END_DATE = 'END-DATE',\n END_ON_NEXT = 'END-ON-NEXT',\n PLANNED_DURATION = 'PLANNED-DURATION',\n SCTE35_OUT = 'SCTE35-OUT',\n SCTE35_IN = 'SCTE35-IN',\n}\n\nexport function isDateRangeCueAttribute(attrName: string): boolean {\n return (\n attrName !== DateRangeAttribute.ID &&\n attrName !== DateRangeAttribute.CLASS &&\n attrName !== DateRangeAttribute.START_DATE &&\n attrName !== DateRangeAttribute.DURATION &&\n attrName !== DateRangeAttribute.END_DATE &&\n attrName !== DateRangeAttribute.END_ON_NEXT\n );\n}\n\nexport function isSCTE35Attribute(attrName: string): boolean {\n return (\n attrName === DateRangeAttribute.SCTE35_OUT ||\n attrName === DateRangeAttribute.SCTE35_IN\n );\n}\n\nexport class DateRange {\n public attr: AttrList;\n private _startDate: Date;\n private _endDate?: Date;\n private _badValueForSameId?: string;\n\n constructor(dateRangeAttr: AttrList, dateRangeWithSameId?: DateRange) {\n if (dateRangeWithSameId) {\n const previousAttr = dateRangeWithSameId.attr;\n for (const key in previousAttr) {\n if (\n Object.prototype.hasOwnProperty.call(dateRangeAttr, key) &&\n dateRangeAttr[key] !== previousAttr[key]\n ) {\n logger.warn(\n `DATERANGE tag attribute: \"${key}\" does not match for tags with ID: \"${dateRangeAttr.ID}\"`,\n );\n this._badValueForSameId = key;\n break;\n }\n }\n // Merge DateRange tags with the same ID\n dateRangeAttr = Object.assign(\n new AttrList({}),\n previousAttr,\n dateRangeAttr,\n );\n }\n this.attr = dateRangeAttr;\n this._startDate = new Date(dateRangeAttr[DateRangeAttribute.START_DATE]);\n if (DateRangeAttribute.END_DATE in this.attr) {\n const endDate = new Date(this.attr[DateRangeAttribute.END_DATE]);\n if (Number.isFinite(endDate.getTime())) {\n this._endDate = endDate;\n }\n }\n }\n\n get id(): string {\n return this.attr.ID;\n }\n\n get class(): string {\n return this.attr.CLASS;\n }\n\n get startDate(): Date {\n return this._startDate;\n }\n\n get endDate(): Date | null {\n if (this._endDate) {\n return this._endDate;\n }\n const duration = this.duration;\n if (duration !== null) {\n return new Date(this._startDate.getTime() + duration * 1000);\n }\n return null;\n }\n\n get duration(): number | null {\n if (DateRangeAttribute.DURATION in this.attr) {\n const duration = this.attr.decimalFloatingPoint(\n DateRangeAttribute.DURATION,\n );\n if (Number.isFinite(duration)) {\n return duration;\n }\n } else if (this._endDate) {\n return (this._endDate.getTime() - this._startDate.getTime()) / 1000;\n }\n return null;\n }\n\n get plannedDuration(): number | null {\n if (DateRangeAttribute.PLANNED_DURATION in this.attr) {\n return this.attr.decimalFloatingPoint(\n DateRangeAttribute.PLANNED_DURATION,\n );\n }\n return null;\n }\n\n get endOnNext(): boolean {\n return this.attr.bool(DateRangeAttribute.END_ON_NEXT);\n }\n\n get isValid(): boolean {\n return (\n !!this.id &&\n !this._badValueForSameId &&\n Number.isFinite(this.startDate.getTime()) &&\n (this.duration === null || this.duration >= 0) &&\n (!this.endOnNext || !!this.class)\n );\n }\n}\n","import type {\n HlsPerformanceTiming,\n HlsProgressivePerformanceTiming,\n LoaderStats,\n} from '../types/loader';\n\nexport class LoadStats implements LoaderStats {\n aborted: boolean = false;\n loaded: number = 0;\n retry: number = 0;\n total: number = 0;\n chunkCount: number = 0;\n bwEstimate: number = 0;\n loading: HlsProgressivePerformanceTiming = { start: 0, first: 0, end: 0 };\n parsing: HlsPerformanceTiming = { start: 0, end: 0 };\n buffering: HlsProgressivePerformanceTiming = { start: 0, first: 0, end: 0 };\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport { LevelKey } from './level-key';\nimport { LoadStats } from './load-stats';\nimport { AttrList } from '../utils/attr-list';\nimport type {\n FragmentLoaderContext,\n KeyLoaderContext,\n Loader,\n PlaylistLevelType,\n} from '../types/loader';\nimport type { KeySystemFormats } from '../utils/mediakeys-helper';\n\nexport const enum ElementaryStreamTypes {\n AUDIO = 'audio',\n VIDEO = 'video',\n AUDIOVIDEO = 'audiovideo',\n}\n\nexport interface ElementaryStreamInfo {\n startPTS: number;\n endPTS: number;\n startDTS: number;\n endDTS: number;\n partial?: boolean;\n}\n\nexport type ElementaryStreams = Record<\n ElementaryStreamTypes,\n ElementaryStreamInfo | null\n>;\n\nexport class BaseSegment {\n private _byteRange: [number, number] | null = null;\n private _url: string | null = null;\n\n // baseurl is the URL to the playlist\n public readonly baseurl: string;\n // relurl is the portion of the URL that comes from inside the playlist.\n public relurl?: string;\n // Holds the types of data this fragment supports\n public elementaryStreams: ElementaryStreams = {\n [ElementaryStreamTypes.AUDIO]: null,\n [ElementaryStreamTypes.VIDEO]: null,\n [ElementaryStreamTypes.AUDIOVIDEO]: null,\n };\n\n constructor(baseurl: string) {\n this.baseurl = baseurl;\n }\n\n // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n setByteRange(value: string, previous?: BaseSegment) {\n const params = value.split('@', 2);\n let start: number;\n if (params.length === 1) {\n start = previous?.byteRangeEndOffset || 0;\n } else {\n start = parseInt(params[1]);\n }\n this._byteRange = [start, parseInt(params[0]) + start];\n }\n\n get byteRange(): [number, number] | [] {\n if (!this._byteRange) {\n return [];\n }\n\n return this._byteRange;\n }\n\n get byteRangeStartOffset(): number | undefined {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset(): number | undefined {\n return this.byteRange[1];\n }\n\n get url(): string {\n if (!this._url && this.baseurl && this.relurl) {\n this._url = buildAbsoluteURL(this.baseurl, this.relurl, {\n alwaysNormalize: true,\n });\n }\n return this._url || '';\n }\n\n set url(value: string) {\n this._url = value;\n }\n}\n\n/**\n * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.\n */\nexport class Fragment extends BaseSegment {\n private _decryptdata: LevelKey | null = null;\n\n public rawProgramDateTime: string | null = null;\n public programDateTime: number | null = null;\n public tagList: Array<string[]> = [];\n\n // EXTINF has to be present for a m3u8 to be considered valid\n public duration: number = 0;\n // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'\n public sn: number | 'initSegment' = 0;\n // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption\n // core difference from the private field _decryptdata is the lack of the initialized IV\n // _decryptdata will set the IV for this segment based on the segment number in the fragment\n public levelkeys?: { [key: string]: LevelKey };\n // A string representing the fragment type\n public readonly type: PlaylistLevelType;\n // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading\n public loader: Loader<FragmentLoaderContext> | null = null;\n // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading\n public keyLoader: Loader<KeyLoaderContext> | null = null;\n // The level/track index to which the fragment belongs\n public level: number = -1;\n // The continuity counter of the fragment\n public cc: number = 0;\n // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n public startPTS?: number;\n // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n public endPTS?: number;\n // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public startDTS!: number;\n // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public endDTS!: number;\n // The start time of the fragment, as listed in the manifest. Updated after transmux complete.\n public start: number = 0;\n // Set by `updateFragPTSDTS` in level-helper\n public deltaPTS?: number;\n // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public maxStartPTS?: number;\n // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public minEndPTS?: number;\n // Load/parse timing information\n public stats: LoadStats = new LoadStats();\n // Init Segment bytes (unset for media segments)\n public data?: Uint8Array;\n // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered\n public bitrateTest: boolean = false;\n // #EXTINF segment title\n public title: string | null = null;\n // The Media Initialization Section for this segment\n public initSegment: Fragment | null = null;\n // Fragment is the last fragment in the media playlist\n public endList?: boolean;\n // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded\n public gap?: boolean;\n // Deprecated\n public urlId: number = 0;\n\n constructor(type: PlaylistLevelType, baseurl: string) {\n super(baseurl);\n this.type = type;\n }\n\n get decryptdata(): LevelKey | null {\n const { levelkeys } = this;\n if (!levelkeys && !this._decryptdata) {\n return null;\n }\n\n if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {\n const key = this.levelkeys.identity;\n if (key) {\n this._decryptdata = key.getDecryptData(this.sn);\n } else {\n const keyFormats = Object.keys(this.levelkeys);\n if (keyFormats.length === 1) {\n return (this._decryptdata = this.levelkeys[\n keyFormats[0]\n ].getDecryptData(this.sn));\n } else {\n // Multiple keys. key-loader to call Fragment.setKeyFormat based on selected key-system.\n }\n }\n }\n\n return this._decryptdata;\n }\n\n get end(): number {\n return this.start + this.duration;\n }\n\n get endProgramDateTime() {\n if (this.programDateTime === null) {\n return null;\n }\n\n if (!Number.isFinite(this.programDateTime)) {\n return null;\n }\n\n const duration = !Number.isFinite(this.duration) ? 0 : this.duration;\n\n return this.programDateTime + duration * 1000;\n }\n\n get encrypted() {\n // At the m3u8-parser level we need to add support for manifest signalled keyformats\n // when we want the fragment to start reporting that it is encrypted.\n // Currently, keyFormat will only be set for identity keys\n if (this._decryptdata?.encrypted) {\n return true;\n } else if (this.levelkeys) {\n const keyFormats = Object.keys(this.levelkeys);\n const len = keyFormats.length;\n if (len > 1 || (len === 1 && this.levelkeys[keyFormats[0]].encrypted)) {\n return true;\n }\n }\n\n return false;\n }\n\n setKeyFormat(keyFormat: KeySystemFormats) {\n if (this.levelkeys) {\n const key = this.levelkeys[keyFormat];\n if (key && !this._decryptdata) {\n this._decryptdata = key.getDecryptData(this.sn);\n }\n }\n }\n\n abortRequests(): void {\n this.loader?.abort();\n this.keyLoader?.abort();\n }\n\n setElementaryStreamInfo(\n type: ElementaryStreamTypes,\n startPTS: number,\n endPTS: number,\n startDTS: number,\n endDTS: number,\n partial: boolean = false,\n ) {\n const { elementaryStreams } = this;\n const info = elementaryStreams[type];\n if (!info) {\n elementaryStreams[type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n partial,\n };\n return;\n }\n\n info.startPTS = Math.min(info.startPTS, startPTS);\n info.endPTS = Math.max(info.endPTS, endPTS);\n info.startDTS = Math.min(info.startDTS, startDTS);\n info.endDTS = Math.max(info.endDTS, endDTS);\n }\n\n clearElementaryStreamInfo() {\n const { elementaryStreams } = this;\n elementaryStreams[ElementaryStreamTypes.AUDIO] = null;\n elementaryStreams[ElementaryStreamTypes.VIDEO] = null;\n elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;\n }\n}\n\n/**\n * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.\n */\nexport class Part extends BaseSegment {\n public readonly fragOffset: number = 0;\n public readonly duration: number = 0;\n public readonly gap: boolean = false;\n public readonly independent: boolean = false;\n public readonly relurl: string;\n public readonly fragment: Fragment;\n public readonly index: number;\n public stats: LoadStats = new LoadStats();\n\n constructor(\n partAttrs: AttrList,\n frag: Fragment,\n baseurl: string,\n index: number,\n previous?: Part,\n ) {\n super(baseurl);\n this.duration = partAttrs.decimalFloatingPoint('DURATION');\n this.gap = partAttrs.bool('GAP');\n this.independent = partAttrs.bool('INDEPENDENT');\n this.relurl = partAttrs.enumeratedString('URI') as string;\n this.fragment = frag;\n this.index = index;\n const byteRange = partAttrs.enumeratedString('BYTERANGE');\n if (byteRange) {\n this.setByteRange(byteRange, previous);\n }\n if (previous) {\n this.fragOffset = previous.fragOffset + previous.duration;\n }\n }\n\n get start(): number {\n return this.fragment.start + this.fragOffset;\n }\n\n get end(): number {\n return this.start + this.duration;\n }\n\n get loaded(): boolean {\n const { elementaryStreams } = this;\n return !!(\n elementaryStreams.audio ||\n elementaryStreams.video ||\n elementaryStreams.audiovideo\n );\n }\n}\n","import { Part } from './fragment';\nimport type { Fragment } from './fragment';\nimport type { AttrList } from '../utils/attr-list';\nimport type { DateRange } from './date-range';\nimport type { VariableMap } from '../types/level';\n\nconst DEFAULT_TARGET_DURATION = 10;\n\n/**\n * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.\n */\nexport class LevelDetails {\n public PTSKnown: boolean = false;\n public alignedSliding: boolean = false;\n public averagetargetduration?: number;\n public endCC: number = 0;\n public endSN: number = 0;\n public fragments: Fragment[];\n public fragmentHint?: Fragment;\n public partList: Part[] | null = null;\n public dateRanges: Record<string, DateRange>;\n public live: boolean = true;\n public ageHeader: number = 0;\n public advancedDateTime?: number;\n public updated: boolean = true;\n public advanced: boolean = true;\n public availabilityDelay?: number; // Manifest reload synchronization\n public misses: number = 0;\n public startCC: number = 0;\n public startSN: number = 0;\n public startTimeOffset: number | null = null;\n public targetduration: number = 0;\n public totalduration: number = 0;\n public type: string | null = null;\n public url: string;\n public m3u8: string = '';\n public version: number | null = null;\n public canBlockReload: boolean = false;\n public canSkipUntil: number = 0;\n public canSkipDateRanges: boolean = false;\n public skippedSegments: number = 0;\n public recentlyRemovedDateranges?: string[];\n public partHoldBack: number = 0;\n public holdBack: number = 0;\n public partTarget: number = 0;\n public preloadHint?: AttrList;\n public renditionReports?: AttrList[];\n public tuneInGoal: number = 0;\n public deltaUpdateFailed?: boolean;\n public driftStartTime: number = 0;\n public driftEndTime: number = 0;\n public driftStart: number = 0;\n public driftEnd: number = 0;\n public encryptedFragments: Fragment[];\n public playlistParsingError: Error | null = null;\n public variableList: VariableMap | null = null;\n public hasVariableRefs = false;\n\n constructor(baseUrl: string) {\n this.fragments = [];\n this.encryptedFragments = [];\n this.dateRanges = {};\n this.url = baseUrl;\n }\n\n reloaded(previous: LevelDetails | undefined) {\n if (!previous) {\n this.advanced = true;\n this.updated = true;\n return;\n }\n const partSnDiff = this.lastPartSn - previous.lastPartSn;\n const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;\n this.updated =\n this.endSN !== previous.endSN ||\n !!partIndexDiff ||\n !!partSnDiff ||\n !this.live;\n this.advanced =\n this.endSN > previous.endSN ||\n partSnDiff > 0 ||\n (partSnDiff === 0 && partIndexDiff > 0);\n if (this.updated || this.advanced) {\n this.misses = Math.floor(previous.misses * 0.6);\n } else {\n this.misses = previous.misses + 1;\n }\n this.availabilityDelay = previous.availabilityDelay;\n }\n\n get hasProgramDateTime(): boolean {\n if (this.fragments.length) {\n return Number.isFinite(\n this.fragments[this.fragments.length - 1].programDateTime as number,\n );\n }\n return false;\n }\n\n get levelTargetDuration(): number {\n return (\n this.averagetargetduration ||\n this.targetduration ||\n DEFAULT_TARGET_DURATION\n );\n }\n\n get drift(): number {\n const runTime = this.driftEndTime - this.driftStartTime;\n if (runTime > 0) {\n const runDuration = this.driftEnd - this.driftStart;\n return (runDuration * 1000) / runTime;\n }\n return 1;\n }\n\n get edge(): number {\n return this.partEnd || this.fragmentEnd;\n }\n\n get partEnd(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].end;\n }\n return this.fragmentEnd;\n }\n\n get fragmentEnd(): number {\n if (this.fragments?.length) {\n return this.fragments[this.fragments.length - 1].end;\n }\n return 0;\n }\n\n get age(): number {\n if (this.advancedDateTime) {\n return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;\n }\n return 0;\n }\n\n get lastPartIndex(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].index;\n }\n return -1;\n }\n\n get lastPartSn(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].fragment.sn as number;\n }\n return this.endSN;\n }\n}\n","// This file is inserted as a shim for modules which we do not want to include into the distro.\n// This replacement is done in the \"alias\" plugin of the rollup config.\nmodule.exports = undefined;\n","export function sliceUint8(\n array: Uint8Array,\n start?: number,\n end?: number,\n): Uint8Array {\n // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.\n // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.\n return Uint8Array.prototype.slice\n ? array.slice(start, end)\n : new Uint8Array(Array.prototype.slice.call(array, start, end));\n}\n","type RawFrame = { type: string; size: number; data: Uint8Array };\n\n// breaking up those two types in order to clarify what is happening in the decoding path.\ntype DecodedFrame<T> = { key: string; data: T; info?: any };\nexport type Frame = DecodedFrame<ArrayBuffer | string>;\n\n/**\n * Returns true if an ID3 header can be found at offset in data\n * @param data - The data to search\n * @param offset - The offset at which to start searching\n */\nexport const isHeader = (data: Uint8Array, offset: number): boolean => {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n // look for 'ID3' identifier\n if (\n data[offset] === 0x49 &&\n data[offset + 1] === 0x44 &&\n data[offset + 2] === 0x33\n ) {\n // check version is within range\n if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n // check size is within range\n if (\n data[offset + 6] < 0x80 &&\n data[offset + 7] < 0x80 &&\n data[offset + 8] < 0x80 &&\n data[offset + 9] < 0x80\n ) {\n return true;\n }\n }\n }\n }\n\n return false;\n};\n\n/**\n * Returns true if an ID3 footer can be found at offset in data\n * @param data - The data to search\n * @param offset - The offset at which to start searching\n */\nexport const isFooter = (data: Uint8Array, offset: number): boolean => {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n // look for '3DI' identifier\n if (\n data[offset] === 0x33 &&\n data[offset + 1] === 0x44 &&\n data[offset + 2] === 0x49\n ) {\n // check version is within range\n if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n // check size is within range\n if (\n data[offset + 6] < 0x80 &&\n data[offset + 7] < 0x80 &&\n data[offset + 8] < 0x80 &&\n data[offset + 9] < 0x80\n ) {\n return true;\n }\n }\n }\n }\n\n return false;\n};\n\n/**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n * @param data - The data to search in\n * @param offset - The offset at which to start searching\n * @returns the block of data containing any ID3 tags found\n * or *undefined* if no header is found at the starting offset\n */\nexport const getID3Data = (\n data: Uint8Array,\n offset: number,\n): Uint8Array | undefined => {\n const front = offset;\n let length = 0;\n\n while (isHeader(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n\n const size = readSize(data, offset + 6);\n length += size;\n\n if (isFooter(data, offset + 10)) {\n // ID3 footer is 10 bytes\n length += 10;\n }\n\n offset += length;\n }\n\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n\n return undefined;\n};\n\nconst readSize = (data: Uint8Array, offset: number): number => {\n let size = 0;\n size = (data[offset] & 0x7f) << 21;\n size |= (data[offset + 1] & 0x7f) << 14;\n size |= (data[offset + 2] & 0x7f) << 7;\n size |= data[offset + 3] & 0x7f;\n return size;\n};\n\nexport const canParse = (data: Uint8Array, offset: number): boolean => {\n return (\n isHeader(data, offset) &&\n readSize(data, offset + 6) + 10 <= data.length - offset\n );\n};\n\n/**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n * @param data - Block of data containing one or more ID3 tags\n */\nexport const getTimeStamp = (data: Uint8Array): number | undefined => {\n const frames: Frame[] = getID3Frames(data);\n\n for (let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n\n if (isTimeStampFrame(frame)) {\n return readTimeStamp(frame as DecodedFrame<ArrayBuffer>);\n }\n }\n\n return undefined;\n};\n\n/**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n */\nexport const isTimeStampFrame = (frame: Frame): boolean => {\n return (\n frame &&\n frame.key === 'PRIV' &&\n frame.info === 'com.apple.streaming.transportStreamTimestamp'\n );\n};\n\nconst getFrameData = (data: Uint8Array): RawFrame => {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type: string = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size: number = readSize(data, 4);\n\n // skip frame id, size, and flags\n const offset = 10;\n\n return { type, size, data: data.subarray(offset, offset + size) };\n};\n\n/**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n * @param id3Data - The ID3 data containing one or more ID3 tags\n */\nexport const getID3Frames = (id3Data: Uint8Array): Frame[] => {\n let offset = 0;\n const frames: Frame[] = [];\n\n while (isHeader(id3Data, offset)) {\n const size = readSize(id3Data, offset + 6);\n // skip past ID3 header\n offset += 10;\n const end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + 8 < end) {\n const frameData: RawFrame = getFrameData(id3Data.subarray(offset));\n const frame: Frame | undefined = decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\n\n // skip frame header and frame data\n offset += frameData.size + 10;\n }\n\n if (isFooter(id3Data, offset)) {\n offset += 10;\n }\n }\n\n return frames;\n};\n\nexport const decodeFrame = (frame: RawFrame): Frame | undefined => {\n if (frame.type === 'PRIV') {\n return decodePrivFrame(frame);\n } else if (frame.type[0] === 'W') {\n return decodeURLFrame(frame);\n }\n\n return decodeTextFrame(frame);\n};\n\nconst decodePrivFrame = (\n frame: RawFrame,\n): DecodedFrame<ArrayBuffer> | undefined => {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n const owner = utf8ArrayToStr(frame.data, true);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n};\n\nconst decodeTextFrame = (frame: RawFrame): DecodedFrame<string> | undefined => {\n if (frame.size < 2) {\n return undefined;\n }\n\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = utf8ArrayToStr(frame.data.subarray(index), true);\n\n index += description.length + 1;\n const value = utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n }\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Value}\n */\n const text = utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n};\n\nconst decodeURLFrame = (frame: RawFrame): DecodedFrame<string> | undefined => {\n if (frame.type === 'WXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{URL}\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n let index = 1;\n const description: string = utf8ArrayToStr(\n frame.data.subarray(index),\n true,\n );\n\n index += description.length + 1;\n const value: string = utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n }\n /*\n Format:\n [0-?] = {URL}\n */\n const url: string = utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n};\n\nconst readTimeStamp = (\n timeStampFrame: DecodedFrame<ArrayBuffer>,\n): number | undefined => {\n if (timeStampFrame.data.byteLength === 8) {\n const data = new Uint8Array(timeStampFrame.data);\n // timestamp is 33 bit expressed as a big-endian eight-octet number,\n // with the upper 31 bits set to zero.\n const pts33Bit = data[3] & 0x1;\n let timestamp =\n (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84;\n } // 2^32 / 90\n\n return Math.round(timestamp);\n }\n\n return undefined;\n};\n\n// http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n/* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\nexport const utf8ArrayToStr = (\n array: Uint8Array,\n exitOnNull: boolean = false,\n): string => {\n const decoder = getTextDecoder();\n if (decoder) {\n const decoded = decoder.decode(array);\n\n if (exitOnNull) {\n // grab up to the first null\n const idx = decoded.indexOf('\\0');\n return idx !== -1 ? decoded.substring(0, idx) : decoded;\n }\n\n // remove any null characters\n return decoded.replace(/\\0/g, '');\n }\n\n const len = array.length;\n let c;\n let char2;\n let char3;\n let out = '';\n let i = 0;\n while (i < len) {\n c = array[i++];\n if (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\n continue;\n }\n switch (c >> 4) {\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12:\n case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode(\n ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0),\n );\n break;\n default:\n }\n }\n return out;\n};\n\nexport const testables = {\n decodeTextFrame: decodeTextFrame,\n};\n\nlet decoder: TextDecoder;\n\nfunction getTextDecoder() {\n // On Play Station 4, TextDecoder is defined but partially implemented.\n // Manual decoding option is preferable\n if (navigator.userAgent.includes('PlayStation 4')) {\n return;\n }\n\n if (!decoder && typeof self.TextDecoder !== 'undefined') {\n decoder = new self.TextDecoder('utf-8');\n }\n\n return decoder;\n}\n","/**\n * hex dump helper class\n */\n\nconst Hex = {\n hexDump: function (array: Uint8Array) {\n let str = '';\n for (let i = 0; i < array.length; i++) {\n let h = array[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n str += h;\n }\n return str;\n },\n};\n\nexport default Hex;\n","import { ElementaryStreamTypes } from '../loader/fragment';\nimport { sliceUint8 } from './typed-array';\nimport { utf8ArrayToStr } from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport Hex from './hex';\nimport type { KeySystemIds } from './mediakeys-helper';\nimport type { PassthroughTrack, UserdataSample } from '../types/demuxer';\nimport type { DecryptData } from '../loader/level-key';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\nconst push = [].push;\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nexport const RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4,\n};\n\nexport function bin2str(data: Uint8Array): string {\n return String.fromCharCode.apply(null, data);\n}\n\nexport function readUint16(buffer: Uint8Array, offset: number): number {\n const val = (buffer[offset] << 8) | buffer[offset + 1];\n return val < 0 ? 65536 + val : val;\n}\n\nexport function readUint32(buffer: Uint8Array, offset: number): number {\n const val = readSint32(buffer, offset);\n return val < 0 ? 4294967296 + val : val;\n}\n\nexport function readUint64(buffer: Uint8Array, offset: number) {\n let result = readUint32(buffer, offset);\n result *= Math.pow(2, 32);\n result += readUint32(buffer, offset + 4);\n return result;\n}\n\nexport function readSint32(buffer: Uint8Array, offset: number): number {\n return (\n (buffer[offset] << 24) |\n (buffer[offset + 1] << 16) |\n (buffer[offset + 2] << 8) |\n buffer[offset + 3]\n );\n}\n\nexport function writeUint32(buffer: Uint8Array, offset: number, value: number) {\n buffer[offset] = value >> 24;\n buffer[offset + 1] = (value >> 16) & 0xff;\n buffer[offset + 2] = (value >> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n}\n\n// Find \"moof\" box\nexport function hasMoofData(data: Uint8Array): boolean {\n const end = data.byteLength;\n for (let i = 0; i < end; ) {\n const size = readUint32(data, i);\n if (\n size > 8 &&\n data[i + 4] === 0x6d &&\n data[i + 5] === 0x6f &&\n data[i + 6] === 0x6f &&\n data[i + 7] === 0x66\n ) {\n return true;\n }\n i = size > 1 ? i + size : end;\n }\n return false;\n}\n\n// Find the data for a box specified by its path\nexport function findBox(data: Uint8Array, path: string[]): Uint8Array[] {\n const results = [] as Uint8Array[];\n if (!path.length) {\n // short-circuit the search for empty paths\n return results;\n }\n const end = data.byteLength;\n\n for (let i = 0; i < end; ) {\n const size = readUint32(data, i);\n const type = bin2str(data.subarray(i + 4, i + 8));\n const endbox = size > 1 ? i + size : end;\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push(data.subarray(i + 8, endbox));\n } else {\n // recursively search for the next box along the path\n const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));\n if (subresults.length) {\n push.apply(results, subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n}\n\ntype SidxInfo = {\n earliestPresentationTime: number;\n timescale: number;\n version: number;\n referencesCount: number;\n references: any[];\n};\n\nexport function parseSegmentIndex(sidx: Uint8Array): SidxInfo | null {\n const references: any[] = [];\n\n const version = sidx[0];\n\n // set initial offset, we skip the reference ID (not needed)\n let index = 8;\n\n const timescale = readUint32(sidx, index);\n index += 4;\n\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n earliestPresentationTime = readUint32(sidx, index);\n firstOffset = readUint32(sidx, index + 4);\n index += 8;\n } else {\n earliestPresentationTime = readUint64(sidx, index);\n firstOffset = readUint64(sidx, index + 8);\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.length + firstOffset;\n\n const referencesCount = readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7fffffff;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n logger.warn('SIDX has hierarchical references (not supported)');\n return null;\n }\n\n const subsegmentDuration = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1,\n },\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n };\n}\n\n/**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param initSegment the bytes of the init segment\n * @returns a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n\nexport interface InitDataTrack {\n timescale: number;\n id: number;\n codec: string;\n}\n\ntype HdlrType = ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO;\n\nexport interface InitData extends Array<any> {\n [index: number]:\n | {\n timescale: number;\n type: HdlrType;\n default?: {\n duration: number;\n flags: number;\n };\n }\n | undefined;\n audio?: InitDataTrack;\n video?: InitDataTrack;\n caption?: InitDataTrack;\n}\n\nexport function parseInitSegment(initSegment: Uint8Array): InitData {\n const result: InitData = [];\n const traks = findBox(initSegment, ['moov', 'trak']);\n for (let i = 0; i < traks.length; i++) {\n const trak = traks[i];\n const tkhd = findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd[0];\n const trackId = readUint32(tkhd, version === 0 ? 12 : 20);\n const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd[0];\n const timescale = readUint32(mdhd, version === 0 ? 12 : 20);\n const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = bin2str(hdlr.subarray(8, 12));\n const type: HdlrType | undefined = {\n soun: ElementaryStreamTypes.AUDIO as const,\n vide: ElementaryStreamTypes.VIDEO as const,\n }[hdlrType];\n if (type) {\n // Parse codec details\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n const stsdData = parseStsd(stsd);\n result[trackId] = { timescale, type };\n result[type] = { timescale, id: trackId, ...stsdData };\n }\n }\n }\n }\n }\n\n const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);\n trex.forEach((trex) => {\n const trackId = readUint32(trex, 4);\n const track = result[trackId];\n if (track) {\n track.default = {\n duration: readUint32(trex, 12),\n flags: readUint32(trex, 20),\n };\n }\n });\n\n return result;\n}\n\nfunction parseStsd(stsd: Uint8Array): { codec: string; encrypted: boolean } {\n const sampleEntries = stsd.subarray(8);\n const sampleEntriesEnd = sampleEntries.subarray(8 + 78);\n const fourCC = bin2str(sampleEntries.subarray(4, 8));\n let codec = fourCC;\n const encrypted = fourCC === 'enca' || fourCC === 'encv';\n if (encrypted) {\n const encBox = findBox(sampleEntries, [fourCC])[0];\n const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);\n const sinfs = findBox(encBoxChildren, ['sinf']);\n sinfs.forEach((sinf) => {\n const schm = findBox(sinf, ['schm'])[0];\n if (schm) {\n const scheme = bin2str(schm.subarray(4, 8));\n if (scheme === 'cbcs' || scheme === 'cenc') {\n const frma = findBox(sinf, ['frma'])[0];\n if (frma) {\n // for encrypted content codec fourCC will be in frma\n codec = bin2str(frma);\n }\n }\n }\n });\n }\n switch (codec) {\n case 'avc1':\n case 'avc2':\n case 'avc3':\n case 'avc4': {\n // extract profile + compatibility + level out of avcC box\n const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];\n codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);\n break;\n }\n case 'mp4a': {\n const codecBox = findBox(sampleEntries, [fourCC])[0];\n const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];\n if (esdsBox && esdsBox.length > 12) {\n let i = 4;\n // ES Descriptor tag\n if (esdsBox[i++] !== 0x03) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n i += 2; // skip es_id;\n const flags = esdsBox[i++];\n if (flags & 0x80) {\n i += 2; // skip dependency es_id\n }\n if (flags & 0x40) {\n i += esdsBox[i++]; // skip URL\n }\n // Decoder config descriptor\n if (esdsBox[i++] !== 0x04) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n const objectType = esdsBox[i++];\n if (objectType === 0x40) {\n codec += '.' + toHex(objectType);\n } else {\n break;\n }\n i += 12;\n // Decoder specific info\n if (esdsBox[i++] !== 0x05) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n const firstByte = esdsBox[i++];\n let audioObjectType = (firstByte & 0xf8) >> 3;\n if (audioObjectType === 31) {\n audioObjectType +=\n 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);\n }\n codec += '.' + audioObjectType;\n }\n break;\n }\n case 'hvc1':\n case 'hev1': {\n const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];\n const profileByte = hvcCBox[1];\n const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];\n const generalProfileIdc = profileByte & 0x1f;\n const profileCompat = readUint32(hvcCBox, 2);\n const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';\n const levelIDC = hvcCBox[12];\n const constraintIndicator = hvcCBox.subarray(6, 12);\n codec += '.' + profileSpace + generalProfileIdc;\n codec += '.' + profileCompat.toString(16).toUpperCase();\n codec += '.' + tierFlag + levelIDC;\n let constraintString = '';\n for (let i = constraintIndicator.length; i--; ) {\n const byte = constraintIndicator[i];\n if (byte || constraintString) {\n const encodedByte = byte.toString(16).toUpperCase();\n constraintString = '.' + encodedByte + constraintString;\n }\n }\n codec += constraintString;\n break;\n }\n case 'dvh1':\n case 'dvhe': {\n const dvcCBox = findBox(sampleEntriesEnd, ['dvcC'])[0];\n const profile = (dvcCBox[2] >> 1) & 0x7f;\n const level = ((dvcCBox[2] << 5) & 0x20) | ((dvcCBox[3] >> 3) & 0x1f);\n codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level);\n break;\n }\n case 'vp09': {\n const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];\n const profile = vpcCBox[4];\n const level = vpcCBox[5];\n const bitDepth = (vpcCBox[6] >> 4) & 0x0f;\n codec +=\n '.' +\n addLeadingZero(profile) +\n '.' +\n addLeadingZero(level) +\n '.' +\n addLeadingZero(bitDepth);\n break;\n }\n case 'av01': {\n const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];\n const profile = av1CBox[1] >>> 5;\n const level = av1CBox[1] & 0x1f;\n const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';\n const highBitDepth = (av1CBox[2] & 0x40) >> 6;\n const twelveBit = (av1CBox[2] & 0x20) >> 5;\n const bitDepth =\n profile === 2 && highBitDepth\n ? twelveBit\n ? 12\n : 10\n : highBitDepth\n ? 10\n : 8;\n const monochrome = (av1CBox[2] & 0x10) >> 4;\n const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;\n const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;\n const chromaSamplePosition = av1CBox[2] & 0x03;\n // TODO: parse color_description_present_flag\n // default it to BT.709/limited range for now\n // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax\n const colorPrimaries = 1;\n const transferCharacteristics = 1;\n const matrixCoefficients = 1;\n const videoFullRangeFlag = 0;\n codec +=\n '.' +\n profile +\n '.' +\n addLeadingZero(level) +\n tierFlag +\n '.' +\n addLeadingZero(bitDepth) +\n '.' +\n monochrome +\n '.' +\n chromaSubsamplingX +\n chromaSubsamplingY +\n chromaSamplePosition +\n '.' +\n addLeadingZero(colorPrimaries) +\n '.' +\n addLeadingZero(transferCharacteristics) +\n '.' +\n addLeadingZero(matrixCoefficients) +\n '.' +\n videoFullRangeFlag;\n break;\n }\n case 'ac-3':\n case 'ec-3':\n case 'alac':\n case 'fLaC':\n case 'Opus':\n default:\n break;\n }\n return { codec, encrypted };\n}\n\nfunction skipBERInteger(bytes: Uint8Array, i: number): number {\n const limit = i + 5;\n while (bytes[i++] & 0x80 && i < limit) {}\n return i;\n}\n\nfunction toHex(x: number): string {\n return ('0' + x.toString(16).toUpperCase()).slice(-2);\n}\n\nfunction addLeadingZero(num: number): string {\n return (num < 10 ? '0' : '') + num;\n}\n\nexport function patchEncyptionData(\n initSegment: Uint8Array | undefined,\n decryptdata: DecryptData | null,\n): Uint8Array | undefined {\n if (!initSegment || !decryptdata) {\n return initSegment;\n }\n const keyId = decryptdata.keyId;\n if (keyId && decryptdata.isCommonEncryption) {\n const traks = findBox(initSegment, ['moov', 'trak']);\n traks.forEach((trak) => {\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n\n // skip the sample entry count\n const sampleEntries = stsd.subarray(8);\n let encBoxes = findBox(sampleEntries, ['enca']);\n const isAudio = encBoxes.length > 0;\n if (!isAudio) {\n encBoxes = findBox(sampleEntries, ['encv']);\n }\n encBoxes.forEach((enc) => {\n const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);\n const sinfBoxes = findBox(encBoxChildren, ['sinf']);\n sinfBoxes.forEach((sinf) => {\n const tenc = parseSinf(sinf);\n if (tenc) {\n // Look for default key id (keyID offset is always 8 within the tenc box):\n const tencKeyId = tenc.subarray(8, 24);\n if (!tencKeyId.some((b) => b !== 0)) {\n logger.log(\n `[eme] Patching keyId in 'enc${\n isAudio ? 'a' : 'v'\n }>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(\n keyId,\n )}`,\n );\n tenc.set(keyId, 8);\n }\n }\n });\n });\n });\n }\n\n return initSegment;\n}\n\nexport function parseSinf(sinf: Uint8Array): Uint8Array | null {\n const schm = findBox(sinf, ['schm'])[0];\n if (schm) {\n const scheme = bin2str(schm.subarray(4, 8));\n if (scheme === 'cbcs' || scheme === 'cenc') {\n return findBox(sinf, ['schi', 'tenc'])[0];\n }\n }\n return null;\n}\n\n/**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param initData - a hash of track type to timescale values\n * @param fmp4 - the bytes of the mp4 fragment\n * @returns the earliest base media decode start time for the\n * fragment, in seconds\n */\nexport function getStartDTS(\n initData: InitData,\n fmp4: Uint8Array,\n): number | null {\n // we need info from two children of each track fragment box\n return findBox(fmp4, ['moof', 'traf']).reduce(\n (result: number | null, traf) => {\n const tfdt = findBox(traf, ['tfdt'])[0];\n const version = tfdt[0];\n const start = findBox(traf, ['tfhd']).reduce(\n (result: number | null, tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (track) {\n let baseTime = readUint32(tfdt, 4);\n if (version === 1) {\n // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.\n // This prevents large values from being used for initPTS, which can cause playlist sync issues.\n // https://github.com/video-dev/hls.js/issues/5303\n if (baseTime === UINT32_MAX) {\n logger.warn(\n `[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`,\n );\n return result;\n }\n baseTime *= UINT32_MAX + 1;\n baseTime += readUint32(tfdt, 8);\n }\n // assume a 90kHz clock if no timescale was specified\n const scale = track.timescale || 90e3;\n // convert base time to seconds\n const startTime = baseTime / scale;\n if (\n Number.isFinite(startTime) &&\n (result === null || startTime < result)\n ) {\n return startTime;\n }\n }\n return result;\n },\n null,\n );\n if (\n start !== null &&\n Number.isFinite(start) &&\n (result === null || start < result)\n ) {\n return start;\n }\n return result;\n },\n null,\n );\n}\n\n/*\n For Reference:\n aligned(8) class TrackFragmentHeaderBox\n extends FullBox(tfhd, 0, tf_flags){\n unsigned int(32) track_ID;\n // all the following are optional fields\n unsigned int(64) base_data_offset;\n unsigned int(32) sample_description_index;\n unsigned int(32) default_sample_duration;\n unsigned int(32) default_sample_size;\n unsigned int(32) default_sample_flags\n }\n */\nexport function getDuration(data: Uint8Array, initData: InitData) {\n let rawDuration = 0;\n let videoDuration = 0;\n let audioDuration = 0;\n const trafs = findBox(data, ['moof', 'traf']);\n for (let i = 0; i < trafs.length; i++) {\n const traf = trafs[i];\n // There is only one tfhd & trun per traf\n // This is true for CMAF style content, and we should perhaps check the ftyp\n // and only look for a single trun then, but for ISOBMFF we should check\n // for multiple track runs.\n const tfhd = findBox(traf, ['tfhd'])[0];\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n continue;\n }\n const trackDefault = track.default;\n const tfhdFlags = readUint32(tfhd, 0) | trackDefault?.flags!;\n let sampleDuration: number | undefined = trackDefault?.duration;\n if (tfhdFlags & 0x000008) {\n // 0x000008 indicates the presence of the default_sample_duration field\n if (tfhdFlags & 0x000002) {\n // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration\n // If present, the default_sample_duration exists at byte offset 12\n sampleDuration = readUint32(tfhd, 12);\n } else {\n // Otherwise, the duration is at byte offset 8\n sampleDuration = readUint32(tfhd, 8);\n }\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n const truns = findBox(traf, ['trun']);\n for (let j = 0; j < truns.length; j++) {\n rawDuration = computeRawDurationFromSamples(truns[j]);\n if (!rawDuration && sampleDuration) {\n const sampleCount = readUint32(truns[j], 4);\n rawDuration = sampleDuration * sampleCount;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n videoDuration += rawDuration / timescale;\n } else if (track.type === ElementaryStreamTypes.AUDIO) {\n audioDuration += rawDuration / timescale;\n }\n }\n }\n if (videoDuration === 0 && audioDuration === 0) {\n // If duration samples are not available in the traf use sidx subsegment_duration\n let sidxMinStart = Infinity;\n let sidxMaxEnd = 0;\n let sidxDuration = 0;\n const sidxs = findBox(data, ['sidx']);\n for (let i = 0; i < sidxs.length; i++) {\n const sidx = parseSegmentIndex(sidxs[i]);\n if (sidx?.references) {\n sidxMinStart = Math.min(\n sidxMinStart,\n sidx.earliestPresentationTime / sidx.timescale,\n );\n const subSegmentDuration = sidx.references.reduce(\n (dur, ref) => dur + ref.info.duration || 0,\n 0,\n );\n sidxMaxEnd = Math.max(\n sidxMaxEnd,\n subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale,\n );\n sidxDuration = sidxMaxEnd - sidxMinStart;\n }\n }\n if (sidxDuration && Number.isFinite(sidxDuration)) {\n return sidxDuration;\n }\n }\n if (videoDuration) {\n return videoDuration;\n }\n return audioDuration;\n}\n\n/*\n For Reference:\n aligned(8) class TrackRunBox\n extends FullBox(trun, version, tr_flags) {\n unsigned int(32) sample_count;\n // the following are optional fields\n signed int(32) data_offset;\n unsigned int(32) first_sample_flags;\n // all fields in the following array are optional\n {\n unsigned int(32) sample_duration;\n unsigned int(32) sample_size;\n unsigned int(32) sample_flags\n if (version == 0)\n { unsigned int(32)\n else\n { signed int(32)\n }[ sample_count ]\n }\n */\nexport function computeRawDurationFromSamples(trun): number {\n const flags = readUint32(trun, 0);\n // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.\n // Each field is an int32, which is 4 bytes\n let offset = 8;\n // data-offset-present flag\n if (flags & 0x000001) {\n offset += 4;\n }\n // first-sample-flags-present flag\n if (flags & 0x000004) {\n offset += 4;\n }\n\n let duration = 0;\n const sampleCount = readUint32(trun, 4);\n for (let i = 0; i < sampleCount; i++) {\n // sample-duration-present flag\n if (flags & 0x000100) {\n const sampleDuration = readUint32(trun, offset);\n duration += sampleDuration;\n offset += 4;\n }\n // sample-size-present flag\n if (flags & 0x000200) {\n offset += 4;\n }\n // sample-flags-present flag\n if (flags & 0x000400) {\n offset += 4;\n }\n // sample-composition-time-offsets-present flag\n if (flags & 0x000800) {\n offset += 4;\n }\n }\n return duration;\n}\n\nexport function offsetStartDTS(\n initData: InitData,\n fmp4: Uint8Array,\n timeOffset: number,\n) {\n findBox(fmp4, ['moof', 'traf']).forEach((traf) => {\n findBox(traf, ['tfhd']).forEach((tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n return;\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n // get the base media decode time from the tfdt\n findBox(traf, ['tfdt']).forEach((tfdt) => {\n const version = tfdt[0];\n const offset = timeOffset * timescale;\n if (offset) {\n let baseMediaDecodeTime = readUint32(tfdt, 4);\n if (version === 0) {\n baseMediaDecodeTime -= offset;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n writeUint32(tfdt, 4, baseMediaDecodeTime);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += readUint32(tfdt, 8);\n baseMediaDecodeTime -= offset;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n writeUint32(tfdt, 4, upper);\n writeUint32(tfdt, 8, lower);\n }\n }\n });\n });\n });\n}\n\n// TODO: Check if the last moof+mdat pair is part of the valid range\nexport function segmentValidRange(data: Uint8Array): SegmentedRange {\n const segmentedRange: SegmentedRange = {\n valid: null,\n remainder: null,\n };\n\n const moofs = findBox(data, ['moof']);\n if (moofs.length < 2) {\n segmentedRange.remainder = data;\n return segmentedRange;\n }\n const last = moofs[moofs.length - 1];\n // Offset by 8 bytes; findBox offsets the start by as much\n segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);\n segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);\n return segmentedRange;\n}\n\nexport interface SegmentedRange {\n valid: Uint8Array | null;\n remainder: Uint8Array | null;\n}\n\nexport function appendUint8Array(\n data1: Uint8Array,\n data2: Uint8Array,\n): Uint8Array {\n const temp = new Uint8Array(data1.length + data2.length);\n temp.set(data1);\n temp.set(data2, data1.length);\n\n return temp;\n}\n\nexport interface IEmsgParsingData {\n schemeIdUri: string;\n value: string;\n timeScale: number;\n presentationTimeDelta?: number;\n presentationTime?: number;\n eventDuration: number;\n id: number;\n payload: Uint8Array;\n}\n\nexport function parseSamples(\n timeOffset: number,\n track: PassthroughTrack,\n): UserdataSample[] {\n const seiSamples = [] as UserdataSample[];\n const videoData = track.samples;\n const timescale = track.timescale;\n const trackId = track.id;\n let isHEVCFlavor = false;\n\n const moofs = findBox(videoData, ['moof']);\n moofs.map((moof) => {\n const moofOffset = moof.byteOffset - 8;\n const trafs = findBox(moof, ['traf']);\n trafs.map((traf) => {\n // get the base media decode time from the tfdt\n const baseTime = findBox(traf, ['tfdt']).map((tfdt) => {\n const version = tfdt[0];\n let result = readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n result += readUint32(tfdt, 8);\n }\n return result / timescale;\n })[0];\n\n if (baseTime !== undefined) {\n timeOffset = baseTime;\n }\n\n return findBox(traf, ['tfhd']).map((tfhd) => {\n const id = readUint32(tfhd, 4);\n const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;\n const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;\n const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;\n const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;\n let defaultSampleDuration = 0;\n const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;\n let defaultSampleSize = 0;\n const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;\n let tfhdOffset = 8;\n\n if (id === trackId) {\n if (baseDataOffsetPresent) {\n tfhdOffset += 8;\n }\n if (sampleDescriptionIndexPresent) {\n tfhdOffset += 4;\n }\n if (defaultSampleDurationPresent) {\n defaultSampleDuration = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleSizePresent) {\n defaultSampleSize = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleFlagsPresent) {\n tfhdOffset += 4;\n }\n if (track.type === 'video') {\n isHEVCFlavor = isHEVC(track.codec);\n }\n\n findBox(traf, ['trun']).map((trun) => {\n const version = trun[0];\n const flags = readUint32(trun, 0) & 0xffffff;\n const dataOffsetPresent = (flags & 0x000001) !== 0;\n let dataOffset = 0;\n const firstSampleFlagsPresent = (flags & 0x000004) !== 0;\n const sampleDurationPresent = (flags & 0x000100) !== 0;\n let sampleDuration = 0;\n const sampleSizePresent = (flags & 0x000200) !== 0;\n let sampleSize = 0;\n const sampleFlagsPresent = (flags & 0x000400) !== 0;\n const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;\n let compositionOffset = 0;\n const sampleCount = readUint32(trun, 4);\n let trunOffset = 8; // past version, flags, and sample count\n\n if (dataOffsetPresent) {\n dataOffset = readUint32(trun, trunOffset);\n trunOffset += 4;\n }\n if (firstSampleFlagsPresent) {\n trunOffset += 4;\n }\n\n let sampleOffset = dataOffset + moofOffset;\n\n for (let ix = 0; ix < sampleCount; ix++) {\n if (sampleDurationPresent) {\n sampleDuration = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleDuration = defaultSampleDuration;\n }\n if (sampleSizePresent) {\n sampleSize = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleSize = defaultSampleSize;\n }\n if (sampleFlagsPresent) {\n trunOffset += 4;\n }\n if (sampleCompositionOffsetsPresent) {\n if (version === 0) {\n compositionOffset = readUint32(trun, trunOffset);\n } else {\n compositionOffset = readSint32(trun, trunOffset);\n }\n trunOffset += 4;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n let naluTotalSize = 0;\n while (naluTotalSize < sampleSize) {\n const naluSize = readUint32(videoData, sampleOffset);\n sampleOffset += 4;\n if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {\n const data = videoData.subarray(\n sampleOffset,\n sampleOffset + naluSize,\n );\n parseSEIMessageFromNALu(\n data,\n isHEVCFlavor ? 2 : 1,\n timeOffset + compositionOffset / timescale,\n seiSamples,\n );\n }\n sampleOffset += naluSize;\n naluTotalSize += naluSize + 4;\n }\n }\n\n timeOffset += sampleDuration / timescale;\n }\n });\n }\n });\n });\n });\n return seiSamples;\n}\n\nfunction isHEVC(codec: string) {\n if (!codec) {\n return false;\n }\n const delimit = codec.indexOf('.');\n const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);\n return (\n baseCodec === 'hvc1' ||\n baseCodec === 'hev1' ||\n // Dolby Vision\n baseCodec === 'dvh1' ||\n baseCodec === 'dvhe'\n );\n}\n\nfunction isSEIMessage(isHEVCFlavor: boolean, naluHeader: number) {\n if (isHEVCFlavor) {\n const naluType = (naluHeader >> 1) & 0x3f;\n return naluType === 39 || naluType === 40;\n } else {\n const naluType = naluHeader & 0x1f;\n return naluType === 6;\n }\n}\n\nexport function parseSEIMessageFromNALu(\n unescapedData: Uint8Array,\n headerSize: number,\n pts: number,\n samples: UserdataSample[],\n) {\n const data = discardEPB(unescapedData);\n let seiPtr = 0;\n // skip nal header\n seiPtr += headerSize;\n let payloadType = 0;\n let payloadSize = 0;\n let b = 0;\n\n while (seiPtr < data.length) {\n payloadType = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadType += b;\n } while (b === 0xff);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadSize += b;\n } while (b === 0xff);\n\n const leftOver = data.length - seiPtr;\n // Create a variable to process the payload\n let payPtr = seiPtr;\n\n // Increment the seiPtr to the end of the payload\n if (payloadSize < leftOver) {\n seiPtr += payloadSize;\n } else if (payloadSize > leftOver) {\n // Some type of corruption has happened?\n logger.error(\n `Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`,\n );\n // We might be able to parse some data, but let's be safe and ignore it.\n break;\n }\n\n if (payloadType === 4) {\n const countryCode = data[payPtr++];\n if (countryCode === 181) {\n const providerCode = readUint16(data, payPtr);\n payPtr += 2;\n\n if (providerCode === 49) {\n const userStructure = readUint32(data, payPtr);\n payPtr += 4;\n\n if (userStructure === 0x47413934) {\n const userDataType = data[payPtr++];\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n const firstByte = data[payPtr++];\n const totalCCs = 0x1f & firstByte;\n const enabled = 0x40 & firstByte;\n const totalBytes = enabled ? 2 + totalCCs * 3 : 0;\n const byteArray = new Uint8Array(totalBytes);\n if (enabled) {\n byteArray[0] = firstByte;\n for (let i = 1; i < totalBytes; i++) {\n byteArray[i] = data[payPtr++];\n }\n }\n\n samples.push({\n type: userDataType,\n payloadType,\n pts,\n bytes: byteArray,\n });\n }\n }\n }\n }\n } else if (payloadType === 5) {\n if (payloadSize > 16) {\n const uuidStrArray: Array<string> = [];\n for (let i = 0; i < 16; i++) {\n const b = data[payPtr++].toString(16);\n uuidStrArray.push(b.length == 1 ? '0' + b : b);\n\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataBytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n userDataBytes[i] = data[payPtr++];\n }\n\n samples.push({\n payloadType,\n pts,\n uuid: uuidStrArray.join(''),\n userData: utf8ArrayToStr(userDataBytes),\n userDataBytes,\n });\n }\n }\n }\n}\n\n/**\n * remove Emulation Prevention bytes from a RBSP\n */\nexport function discardEPB(data: Uint8Array): Uint8Array {\n const length = data.byteLength;\n const EPBPositions = [] as Array<number>;\n let i = 1;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n const newLength = length - EPBPositions.length;\n const newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n}\n\nexport function parseEmsg(data: Uint8Array): IEmsgParsingData {\n const version = data[0];\n let schemeIdUri: string = '';\n let value: string = '';\n let timeScale: number = 0;\n let presentationTimeDelta: number = 0;\n let presentationTime: number = 0;\n let eventDuration: number = 0;\n let id: number = 0;\n let offset: number = 0;\n\n if (version === 0) {\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n timeScale = readUint32(data, 12);\n presentationTimeDelta = readUint32(data, 16);\n eventDuration = readUint32(data, 20);\n id = readUint32(data, 24);\n offset = 28;\n } else if (version === 1) {\n offset += 4;\n timeScale = readUint32(data, offset);\n offset += 4;\n const leftPresentationTime = readUint32(data, offset);\n offset += 4;\n const rightPresentationTime = readUint32(data, offset);\n offset += 4;\n presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;\n if (!Number.isSafeInteger(presentationTime)) {\n presentationTime = Number.MAX_SAFE_INTEGER;\n logger.warn(\n 'Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box',\n );\n }\n\n eventDuration = readUint32(data, offset);\n offset += 4;\n id = readUint32(data, offset);\n offset += 4;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n const payload = data.subarray(offset, data.byteLength);\n\n return {\n schemeIdUri,\n value,\n timeScale,\n presentationTime,\n presentationTimeDelta,\n eventDuration,\n id,\n payload,\n };\n}\n\nexport function mp4Box(type: ArrayLike<number>, ...payload: Uint8Array[]) {\n const len = payload.length;\n let size = 8;\n let i = len;\n while (i--) {\n size += payload[i].byteLength;\n }\n const result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n for (i = 0, size = 8; i < len; i++) {\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n}\n\nexport function mp4pssh(\n systemId: Uint8Array,\n keyids: Array<Uint8Array> | null,\n data: Uint8Array,\n) {\n if (systemId.byteLength !== 16) {\n throw new RangeError('Invalid system id');\n }\n let version;\n let kids;\n if (keyids) {\n version = 1;\n kids = new Uint8Array(keyids.length * 16);\n for (let ix = 0; ix < keyids.length; ix++) {\n const k = keyids[ix]; // uint8array\n if (k.byteLength !== 16) {\n throw new RangeError('Invalid key');\n }\n kids.set(k, ix * 16);\n }\n } else {\n version = 0;\n kids = new Uint8Array();\n }\n let kidCount;\n if (version > 0) {\n kidCount = new Uint8Array(4);\n if (keyids!.length > 0) {\n new DataView(kidCount.buffer).setUint32(0, keyids!.length, false);\n }\n } else {\n kidCount = new Uint8Array();\n }\n const dataSize = new Uint8Array(4);\n if (data && data.byteLength > 0) {\n new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);\n }\n return mp4Box(\n [112, 115, 115, 104],\n new Uint8Array([\n version,\n 0x00,\n 0x00,\n 0x00, // Flags\n ]),\n systemId, // 16 bytes\n kidCount,\n kids,\n dataSize,\n data || new Uint8Array(),\n );\n}\n\nexport type PsshData = {\n version: 0 | 1;\n systemId: KeySystemIds;\n kids: null | Uint8Array[];\n data: null | Uint8Array;\n offset: number;\n size: number;\n};\n\nexport type PsshInvalidResult = {\n systemId?: undefined;\n offset: number;\n size: number;\n};\n\nexport function parseMultiPssh(\n initData: ArrayBuffer,\n): (PsshData | PsshInvalidResult)[] {\n const results: (PsshData | PsshInvalidResult)[] = [];\n if (initData instanceof ArrayBuffer) {\n const length = initData.byteLength;\n let offset = 0;\n while (offset + 32 < length) {\n const view = new DataView(initData, offset);\n const pssh = parsePssh(view);\n results.push(pssh);\n offset += pssh.size;\n }\n }\n return results;\n}\n\nfunction parsePssh(view: DataView): PsshData | PsshInvalidResult {\n const size = view.getUint32(0);\n const offset = view.byteOffset;\n const length = view.byteLength;\n if (length < size) {\n return {\n offset,\n size: length,\n };\n }\n const type = view.getUint32(4);\n if (type !== 0x70737368) {\n return { offset, size };\n }\n const version = view.getUint32(8) >>> 24;\n if (version !== 0 && version !== 1) {\n return { offset, size };\n }\n const buffer = view.buffer;\n const systemId = Hex.hexDump(\n new Uint8Array(buffer, offset + 12, 16),\n ) as KeySystemIds;\n const dataSizeOrKidCount = view.getUint32(28);\n let kids: null | Uint8Array[] = null;\n let data: null | Uint8Array = null;\n if (version === 0) {\n if (size - 32 < dataSizeOrKidCount || dataSizeOrKidCount < 22) {\n return { offset, size };\n }\n data = new Uint8Array(buffer, offset + 32, dataSizeOrKidCount);\n } else if (version === 1) {\n if (\n !dataSizeOrKidCount ||\n length < offset + 32 + dataSizeOrKidCount * 16 + 16\n ) {\n return { offset, size };\n }\n kids = [];\n for (let i = 0; i < dataSizeOrKidCount; i++) {\n kids.push(new Uint8Array(buffer, offset + 32 + i * 16, 16));\n }\n }\n return {\n version,\n systemId,\n kids,\n data,\n offset,\n size,\n };\n}\n","import {\n changeEndianness,\n convertDataUriToArrayBytes,\n} from '../utils/keysystem-util';\nimport { KeySystemFormats } from '../utils/mediakeys-helper';\nimport { mp4pssh } from '../utils/mp4-tools';\nimport { logger } from '../utils/logger';\nimport { base64Decode } from '../utils/numeric-encoding-utils';\n\nlet keyUriToKeyIdMap: { [uri: string]: Uint8Array } = {};\n\nexport interface DecryptData {\n uri: string;\n method: string;\n keyFormat: string;\n keyFormatVersions: number[];\n iv: Uint8Array | null;\n key: Uint8Array | null;\n keyId: Uint8Array | null;\n pssh: Uint8Array | null;\n encrypted: boolean;\n isCommonEncryption: boolean;\n}\n\nexport class LevelKey implements DecryptData {\n public readonly uri: string;\n public readonly method: string;\n public readonly keyFormat: string;\n public readonly keyFormatVersions: number[];\n public readonly encrypted: boolean;\n public readonly isCommonEncryption: boolean;\n public iv: Uint8Array | null = null;\n public key: Uint8Array | null = null;\n public keyId: Uint8Array | null = null;\n public pssh: Uint8Array | null = null;\n\n static clearKeyUriToKeyIdMap() {\n keyUriToKeyIdMap = {};\n }\n\n constructor(\n method: string,\n uri: string,\n format: string,\n formatversions: number[] = [1],\n iv: Uint8Array | null = null,\n ) {\n this.method = method;\n this.uri = uri;\n this.keyFormat = format;\n this.keyFormatVersions = formatversions;\n this.iv = iv;\n this.encrypted = method ? method !== 'NONE' : false;\n this.isCommonEncryption = this.encrypted && method !== 'AES-128';\n }\n\n public isSupported(): boolean {\n // If it's Segment encryption or No encryption, just select that key system\n if (this.method) {\n if (this.method === 'AES-128' || this.method === 'NONE') {\n return true;\n }\n if (this.keyFormat === 'identity') {\n // Maintain support for clear SAMPLE-AES with MPEG-3 TS\n return this.method === 'SAMPLE-AES';\n } else if (__USE_EME_DRM__) {\n switch (this.keyFormat) {\n case KeySystemFormats.FAIRPLAY:\n case KeySystemFormats.WIDEVINE:\n case KeySystemFormats.PLAYREADY:\n case KeySystemFormats.CLEARKEY:\n return (\n [\n 'ISO-23001-7',\n 'SAMPLE-AES',\n 'SAMPLE-AES-CENC',\n 'SAMPLE-AES-CTR',\n ].indexOf(this.method) !== -1\n );\n }\n }\n }\n return false;\n }\n\n public getDecryptData(sn: number | 'initSegment'): LevelKey | null {\n if (!this.encrypted || !this.uri) {\n return null;\n }\n\n if (this.method === 'AES-128' && this.uri && !this.iv) {\n if (typeof sn !== 'number') {\n // We are fetching decryption data for a initialization segment\n // If the segment was encrypted with AES-128\n // It must have an IV defined. We cannot substitute the Segment Number in.\n if (this.method === 'AES-128' && !this.iv) {\n logger.warn(\n `missing IV for initialization segment with method=\"${this.method}\" - compliance issue`,\n );\n }\n // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n sn = 0;\n }\n const iv = createInitializationVector(sn);\n const decryptdata = new LevelKey(\n this.method,\n this.uri,\n 'identity',\n this.keyFormatVersions,\n iv,\n );\n return decryptdata;\n }\n\n if (!__USE_EME_DRM__) {\n return this;\n }\n\n // Initialize keyId if possible\n const keyBytes = convertDataUriToArrayBytes(this.uri);\n if (keyBytes) {\n switch (this.keyFormat) {\n case KeySystemFormats.WIDEVINE:\n this.pssh = keyBytes;\n // In case of widevine keyID is embedded in PSSH box. Read Key ID.\n if (keyBytes.length >= 22) {\n this.keyId = keyBytes.subarray(\n keyBytes.length - 22,\n keyBytes.length - 6,\n );\n }\n break;\n case KeySystemFormats.PLAYREADY: {\n const PlayReadyKeySystemUUID = new Uint8Array([\n 0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6,\n 0x5b, 0xe0, 0x88, 0x5f, 0x95,\n ]);\n\n this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);\n\n const keyBytesUtf16 = new Uint16Array(\n keyBytes.buffer,\n keyBytes.byteOffset,\n keyBytes.byteLength / 2,\n );\n const keyByteStr = String.fromCharCode.apply(\n null,\n Array.from(keyBytesUtf16),\n );\n\n // Parse Playready WRMHeader XML\n const xmlKeyBytes = keyByteStr.substring(\n keyByteStr.indexOf('<'),\n keyByteStr.length,\n );\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');\n const keyData = xmlDoc.getElementsByTagName('KID')[0];\n if (keyData) {\n const keyId = keyData.childNodes[0]\n ? keyData.childNodes[0].nodeValue\n : keyData.getAttribute('VALUE');\n if (keyId) {\n const keyIdArray = base64Decode(keyId).subarray(0, 16);\n // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID\n // KID value in tenc is a big endian UUID GUID interpretation of UUID\n changeEndianness(keyIdArray);\n this.keyId = keyIdArray;\n }\n }\n break;\n }\n default: {\n let keydata = keyBytes.subarray(0, 16);\n if (keydata.length !== 16) {\n const padded = new Uint8Array(16);\n padded.set(keydata, 16 - keydata.length);\n keydata = padded;\n }\n this.keyId = keydata;\n break;\n }\n }\n }\n\n // Default behavior: assign a new keyId for each uri\n if (!this.keyId || this.keyId.byteLength !== 16) {\n let keyId = keyUriToKeyIdMap[this.uri];\n if (!keyId) {\n const val =\n Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;\n keyId = new Uint8Array(16);\n const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes\n dv.setUint32(0, val);\n keyUriToKeyIdMap[this.uri] = keyId;\n }\n this.keyId = keyId;\n }\n\n return this;\n }\n}\n\nfunction createInitializationVector(segmentNumber: number): Uint8Array {\n const uint8View = new Uint8Array(16);\n for (let i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> (8 * (15 - i))) & 0xff;\n }\n return uint8View;\n}\n","/**\n * MediaSource helper\n */\n\nexport function getMediaSource(\n preferManagedMediaSource = true,\n): typeof MediaSource | undefined {\n if (typeof self === 'undefined') return undefined;\n const mms =\n (preferManagedMediaSource || !self.MediaSource) &&\n ((self as any).ManagedMediaSource as undefined | typeof MediaSource);\n return (\n mms ||\n self.MediaSource ||\n ((self as any).WebKitMediaSource as typeof MediaSource)\n );\n}\n\nexport function isManagedMediaSource(source: typeof MediaSource | undefined) {\n return (\n typeof self !== 'undefined' && source === (self as any).ManagedMediaSource\n );\n}\n","import { getMediaSource } from './mediasource-helper';\n\n// from http://mp4ra.org/codecs.html\n// values indicate codec selection preference (lower is higher priority)\nconst sampleEntryCodesISO = {\n audio: {\n a3ds: 1,\n 'ac-3': 0.95,\n 'ac-4': 1,\n alac: 0.9,\n alaw: 1,\n dra1: 1,\n 'dts+': 1,\n 'dts-': 1,\n dtsc: 1,\n dtse: 1,\n dtsh: 1,\n 'ec-3': 0.9,\n enca: 1,\n fLaC: 0.9, // MP4-RA listed codec entry for FLAC\n flac: 0.9, // legacy browser codec name for FLAC\n FLAC: 0.9, // some manifests may list \"FLAC\" with Apple's tools\n g719: 1,\n g726: 1,\n m4ae: 1,\n mha1: 1,\n mha2: 1,\n mhm1: 1,\n mhm2: 1,\n mlpa: 1,\n mp4a: 1,\n 'raw ': 1,\n Opus: 1,\n opus: 1, // browsers expect this to be lowercase despite MP4RA says 'Opus'\n samr: 1,\n sawb: 1,\n sawp: 1,\n sevc: 1,\n sqcp: 1,\n ssmv: 1,\n twos: 1,\n ulaw: 1,\n },\n video: {\n avc1: 1,\n avc2: 1,\n avc3: 1,\n avc4: 1,\n avcp: 1,\n av01: 0.8,\n drac: 1,\n dva1: 1,\n dvav: 1,\n dvh1: 0.7,\n dvhe: 0.7,\n encv: 1,\n hev1: 0.75,\n hvc1: 0.75,\n mjp2: 1,\n mp4v: 1,\n mvc1: 1,\n mvc2: 1,\n mvc3: 1,\n mvc4: 1,\n resv: 1,\n rv60: 1,\n s263: 1,\n svc1: 1,\n svc2: 1,\n 'vc-1': 1,\n vp08: 1,\n vp09: 0.9,\n },\n text: {\n stpp: 1,\n wvtt: 1,\n },\n} as const;\n\nexport type CodecType = 'audio' | 'video';\n\nexport function isCodecType(codec: string, type: CodecType): boolean {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && !!typeCodes[codec.slice(0, 4)];\n}\n\nexport function areCodecsMediaSourceSupported(\n codecs: string,\n type: CodecType,\n preferManagedMediaSource = true,\n): boolean {\n return !codecs\n .split(',')\n .some(\n (codec) =>\n !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource),\n );\n}\n\nfunction isCodecMediaSourceSupported(\n codec: string,\n type: CodecType,\n preferManagedMediaSource = true,\n): boolean {\n const MediaSource = getMediaSource(preferManagedMediaSource);\n return MediaSource?.isTypeSupported(mimeTypeForCodec(codec, type)) ?? false;\n}\n\nexport function mimeTypeForCodec(codec: string, type: CodecType): string {\n return `${type}/mp4;codecs=\"${codec}\"`;\n}\n\nexport function videoCodecPreferenceValue(\n videoCodec: string | undefined,\n): number {\n if (videoCodec) {\n const fourCC = videoCodec.substring(0, 4);\n return sampleEntryCodesISO.video[fourCC];\n }\n return 2;\n}\n\nexport function codecsSetSelectionPreferenceValue(codecSet: string): number {\n return codecSet.split(',').reduce((num, fourCC) => {\n const preferenceValue = sampleEntryCodesISO.video[fourCC];\n if (preferenceValue) {\n return (preferenceValue * 2 + num) / (num ? 3 : 2);\n }\n return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);\n }, 0);\n}\n\ninterface CodecNameCache {\n flac?: string;\n opus?: string;\n}\n\nconst CODEC_COMPATIBLE_NAMES: CodecNameCache = {};\n\ntype LowerCaseCodecType = 'flac' | 'opus';\n\nfunction getCodecCompatibleNameLower(\n lowerCaseCodec: LowerCaseCodecType,\n preferManagedMediaSource = true,\n): string {\n if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {\n return CODEC_COMPATIBLE_NAMES[lowerCaseCodec]!;\n }\n\n // Idealy fLaC and Opus would be first (spec-compliant) but\n // some browsers will report that fLaC is supported then fail.\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728\n const codecsToCheck = {\n flac: ['flac', 'fLaC', 'FLAC'],\n opus: ['opus', 'Opus'],\n }[lowerCaseCodec];\n\n for (let i = 0; i < codecsToCheck.length; i++) {\n if (\n isCodecMediaSourceSupported(\n codecsToCheck[i],\n 'audio',\n preferManagedMediaSource,\n )\n ) {\n CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];\n return codecsToCheck[i];\n }\n }\n\n return lowerCaseCodec;\n}\n\nconst AUDIO_CODEC_REGEXP = /flac|opus/i;\nexport function getCodecCompatibleName(\n codec: string,\n preferManagedMediaSource = true,\n): string {\n return codec.replace(AUDIO_CODEC_REGEXP, (m) =>\n getCodecCompatibleNameLower(\n m.toLowerCase() as LowerCaseCodecType,\n preferManagedMediaSource,\n ),\n );\n}\n\nexport function pickMostCompleteCodecName(\n parsedCodec: string,\n levelCodec: string | undefined,\n): string | undefined {\n // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a\n // so use level codec is parsed codec is unavailable or incomplete\n if (parsedCodec && parsedCodec !== 'mp4a') {\n return parsedCodec;\n }\n return levelCodec ? levelCodec.split(',')[0] : levelCodec;\n}\n\nexport function convertAVC1ToAVCOTI(codec: string) {\n // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported\n // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.\n const codecs = codec.split(',');\n for (let i = 0; i < codecs.length; i++) {\n const avcdata = codecs[i].split('.');\n if (avcdata.length > 2) {\n let result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift() as string).toString(16);\n result += (\n '000' + parseInt(avcdata.shift() as string).toString(16)\n ).slice(-4);\n codecs[i] = result;\n }\n }\n return codecs.join(',');\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport { DateRange } from './date-range';\nimport { Fragment, Part } from './fragment';\nimport { LevelDetails } from './level-details';\nimport { LevelKey } from './level-key';\nimport { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport {\n addVariableDefinition,\n hasVariableReferences,\n importVariableDefinition,\n substituteVariables,\n substituteVariablesInAttributes,\n} from '../utils/variable-substitution';\nimport { isCodecType } from '../utils/codecs';\nimport type { CodecType } from '../utils/codecs';\nimport type { MediaPlaylist, MediaAttributes } from '../types/media-playlist';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { LevelAttributes, LevelParsed, VariableMap } from '../types/level';\nimport type { ContentSteeringOptions } from '../types/events';\n\ntype M3U8ParserFragments = Array<Fragment | null>;\n\nexport type ParsedMultivariantPlaylist = {\n contentSteering: ContentSteeringOptions | null;\n levels: LevelParsed[];\n playlistParsingError: Error | null;\n sessionData: Record<string, AttrList> | null;\n sessionKeys: LevelKey[] | null;\n startTimeOffset: number | null;\n variableList: VariableMap | null;\n hasVariableRefs: boolean;\n};\n\ntype ParsedMultivariantMediaOptions = {\n AUDIO?: MediaPlaylist[];\n SUBTITLES?: MediaPlaylist[];\n 'CLOSED-CAPTIONS'?: MediaPlaylist[];\n};\n\nconst MASTER_PLAYLIST_REGEX =\n /#EXT-X-STREAM-INF:([^\\r\\n]*)(?:[\\r\\n](?:#[^\\r\\n]*)?)*([^\\r\\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\\r\\n]*)[\\r\\n]+/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp(\n [\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /(?!#) *(\\S[^\\r\\n]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /#.*/.source, // All other non-segment oriented tags will match with all groups empty\n ].join('|'),\n 'g',\n);\n\nconst LEVEL_PLAYLIST_REGEX_SLOW = new RegExp(\n [\n /#(EXTM3U)/.source,\n /#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/\n .source,\n /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)/\n .source,\n /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,\n /(#)([^:]*):(.*)/.source,\n /(#)(.*)(?:.*)\\r?\\n?/.source,\n ].join('|'),\n);\n\nexport default class M3U8Parser {\n static findGroup(\n groups: (\n | { id?: string; audioCodec?: string }\n | { id?: string; textCodec?: string }\n )[],\n mediaGroupId: string,\n ):\n | { id?: string; audioCodec?: string }\n | { id?: string; textCodec?: string }\n | undefined {\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n return group;\n }\n }\n }\n\n static resolve(url, baseUrl) {\n return buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static isMediaPlaylist(str: string): boolean {\n return IS_MEDIA_PLAYLIST.test(str);\n }\n\n static parseMasterPlaylist(\n string: string,\n baseurl: string,\n ): ParsedMultivariantPlaylist {\n const hasVariableRefs = __USE_VARIABLE_SUBSTITUTION__\n ? hasVariableReferences(string)\n : false;\n const parsed: ParsedMultivariantPlaylist = {\n contentSteering: null,\n levels: [],\n playlistParsingError: null,\n sessionData: null,\n sessionKeys: null,\n startTimeOffset: null,\n variableList: null,\n hasVariableRefs,\n };\n const levelsWithKnownCodecs: LevelParsed[] = [];\n\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n let result: RegExpExecArray | null;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n if (result[1]) {\n // '#EXT-X-STREAM-INF' is found, parse level tag in group 1\n const attrs = new AttrList(result[1]) as LevelAttributes;\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, attrs, [\n 'CODECS',\n 'SUPPLEMENTAL-CODECS',\n 'ALLOWED-CPC',\n 'PATHWAY-ID',\n 'STABLE-VARIANT-ID',\n 'AUDIO',\n 'VIDEO',\n 'SUBTITLES',\n 'CLOSED-CAPTIONS',\n 'NAME',\n ]);\n }\n const uri = __USE_VARIABLE_SUBSTITUTION__\n ? substituteVariables(parsed, result[2])\n : result[2];\n const level: LevelParsed = {\n attrs,\n bitrate:\n attrs.decimalInteger('BANDWIDTH') ||\n attrs.decimalInteger('AVERAGE-BANDWIDTH'),\n name: attrs.NAME,\n url: M3U8Parser.resolve(uri, baseurl),\n };\n\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n\n setCodecs(attrs.CODECS, level);\n\n if (!level.unknownCodecs?.length) {\n levelsWithKnownCodecs.push(level);\n }\n\n parsed.levels.push(level);\n } else if (result[3]) {\n const tag = result[3];\n const attributes = result[4];\n switch (tag) {\n case 'SESSION-DATA': {\n // #EXT-X-SESSION-DATA\n const sessionAttrs = new AttrList(attributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, sessionAttrs, [\n 'DATA-ID',\n 'LANGUAGE',\n 'VALUE',\n 'URI',\n ]);\n }\n const dataId = sessionAttrs['DATA-ID'];\n if (dataId) {\n if (parsed.sessionData === null) {\n parsed.sessionData = {};\n }\n parsed.sessionData[dataId] = sessionAttrs;\n }\n break;\n }\n case 'SESSION-KEY': {\n // #EXT-X-SESSION-KEY\n const sessionKey = parseKey(attributes, baseurl, parsed);\n if (sessionKey.encrypted && sessionKey.isSupported()) {\n if (parsed.sessionKeys === null) {\n parsed.sessionKeys = [];\n }\n parsed.sessionKeys.push(sessionKey);\n } else {\n logger.warn(\n `[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"${attributes}\"`,\n );\n }\n break;\n }\n case 'DEFINE': {\n // #EXT-X-DEFINE\n if (__USE_VARIABLE_SUBSTITUTION__) {\n const variableAttributes = new AttrList(attributes);\n substituteVariablesInAttributes(parsed, variableAttributes, [\n 'NAME',\n 'VALUE',\n 'QUERYPARAM',\n ]);\n addVariableDefinition(parsed, variableAttributes, baseurl);\n }\n break;\n }\n case 'CONTENT-STEERING': {\n // #EXT-X-CONTENT-STEERING\n const contentSteeringAttributes = new AttrList(attributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(\n parsed,\n contentSteeringAttributes,\n ['SERVER-URI', 'PATHWAY-ID'],\n );\n }\n parsed.contentSteering = {\n uri: M3U8Parser.resolve(\n contentSteeringAttributes['SERVER-URI'],\n baseurl,\n ),\n pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.',\n };\n break;\n }\n case 'START': {\n // #EXT-X-START\n parsed.startTimeOffset = parseStartTimeOffset(attributes);\n break;\n }\n default:\n break;\n }\n }\n }\n // Filter out levels with unknown codecs if it does not remove all levels\n const stripUnknownCodecLevels =\n levelsWithKnownCodecs.length > 0 &&\n levelsWithKnownCodecs.length < parsed.levels.length;\n\n parsed.levels = stripUnknownCodecLevels\n ? levelsWithKnownCodecs\n : parsed.levels;\n if (parsed.levels.length === 0) {\n parsed.playlistParsingError = new Error('no levels found in manifest');\n }\n\n return parsed;\n }\n\n static parseMasterPlaylistMedia(\n string: string,\n baseurl: string,\n parsed: ParsedMultivariantPlaylist,\n ): ParsedMultivariantMediaOptions {\n let result: RegExpExecArray | null;\n const results: ParsedMultivariantMediaOptions = {};\n const levels = parsed.levels;\n const groupsByType = {\n AUDIO: levels.map((level: LevelParsed) => ({\n id: level.attrs.AUDIO,\n audioCodec: level.audioCodec,\n })),\n SUBTITLES: levels.map((level: LevelParsed) => ({\n id: level.attrs.SUBTITLES,\n textCodec: level.textCodec,\n })),\n 'CLOSED-CAPTIONS': [],\n };\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const attrs = new AttrList(result[1]) as MediaAttributes;\n const type = attrs.TYPE;\n if (type) {\n const groups: (typeof groupsByType)[keyof typeof groupsByType] =\n groupsByType[type];\n const medias: MediaPlaylist[] = results[type] || [];\n results[type] = medias;\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, attrs, [\n 'URI',\n 'GROUP-ID',\n 'LANGUAGE',\n 'ASSOC-LANGUAGE',\n 'STABLE-RENDITION-ID',\n 'NAME',\n 'INSTREAM-ID',\n 'CHARACTERISTICS',\n 'CHANNELS',\n ]);\n }\n const lang = attrs.LANGUAGE;\n const assocLang = attrs['ASSOC-LANGUAGE'];\n const channels = attrs.CHANNELS;\n const characteristics = attrs.CHARACTERISTICS;\n const instreamId = attrs['INSTREAM-ID'];\n const media: MediaPlaylist = {\n attrs,\n bitrate: 0,\n id: id++,\n groupId: attrs['GROUP-ID'] || '',\n name: attrs.NAME || lang || '',\n type,\n default: attrs.bool('DEFAULT'),\n autoselect: attrs.bool('AUTOSELECT'),\n forced: attrs.bool('FORCED'),\n lang,\n url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : '',\n };\n if (assocLang) {\n media.assocLang = assocLang;\n }\n if (channels) {\n media.channels = channels;\n }\n if (characteristics) {\n media.characteristics = characteristics;\n }\n if (instreamId) {\n media.instreamId = instreamId;\n }\n\n if (groups?.length) {\n // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n const groupCodec =\n M3U8Parser.findGroup(groups, media.groupId as string) || groups[0];\n assignCodec(media, groupCodec, 'audioCodec');\n assignCodec(media, groupCodec, 'textCodec');\n }\n\n medias.push(media);\n }\n }\n return results;\n }\n\n static parseLevelPlaylist(\n string: string,\n baseurl: string,\n id: number,\n type: PlaylistLevelType,\n levelUrlId: number,\n multivariantVariableList: VariableMap | null,\n ): LevelDetails {\n const level = new LevelDetails(baseurl);\n const fragments: M3U8ParserFragments = level.fragments;\n // The most recent init segment seen (applies to all subsequent segments)\n let currentInitSegment: Fragment | null = null;\n let currentSN = 0;\n let currentPart = 0;\n let totalduration = 0;\n let discontinuityCounter = 0;\n let prevFrag: Fragment | null = null;\n let frag: Fragment = new Fragment(type, baseurl);\n let result: RegExpExecArray | RegExpMatchArray | null;\n let i: number;\n let levelkeys: { [key: string]: LevelKey } | undefined;\n let firstPdtIndex = -1;\n let createNextFrag = false;\n let nextByteRange: string | null = null;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n level.m3u8 = string;\n level.hasVariableRefs = __USE_VARIABLE_SUBSTITUTION__\n ? hasVariableReferences(string)\n : false;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n if (createNextFrag) {\n createNextFrag = false;\n frag = new Fragment(type, baseurl);\n // setup the next fragment for part loading\n frag.start = totalduration;\n frag.sn = currentSN;\n frag.cc = discontinuityCounter;\n frag.level = id;\n if (currentInitSegment) {\n frag.initSegment = currentInitSegment;\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n currentInitSegment.rawProgramDateTime = null;\n if (nextByteRange) {\n frag.setByteRange(nextByteRange);\n nextByteRange = null;\n }\n }\n }\n\n const duration = result[1];\n if (duration) {\n // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n } else if (result[3]) {\n // url\n if (Number.isFinite(frag.duration)) {\n frag.start = totalduration;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n frag.sn = currentSN;\n frag.level = id;\n frag.cc = discontinuityCounter;\n fragments.push(frag);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const uri = (' ' + result[3]).slice(1);\n frag.relurl = __USE_VARIABLE_SUBSTITUTION__\n ? substituteVariables(level, uri)\n : uri;\n assignProgramDateTime(frag, prevFrag);\n prevFrag = frag;\n totalduration += frag.duration;\n currentSN++;\n currentPart = 0;\n createNextFrag = true;\n }\n } else if (result[4]) {\n // X-BYTERANGE\n const data = (' ' + result[4]).slice(1);\n if (prevFrag) {\n frag.setByteRange(data, prevFrag);\n } else {\n frag.setByteRange(data);\n }\n } else if (result[5]) {\n // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n if (firstPdtIndex === -1) {\n firstPdtIndex = fragments.length;\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n if (!result) {\n logger.warn('No matches on slow regex match for level playlist!');\n continue;\n }\n for (i = 1; i < result.length; i++) {\n if (typeof result[i] !== 'undefined') {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const tag = (' ' + result[i]).slice(1);\n const value1 = (' ' + result[i + 1]).slice(1);\n const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';\n\n switch (tag) {\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'SKIP': {\n const skipAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, skipAttrs, [\n 'RECENTLY-REMOVED-DATERANGES',\n ]);\n }\n const skippedSegments =\n skipAttrs.decimalInteger('SKIPPED-SEGMENTS');\n if (Number.isFinite(skippedSegments)) {\n level.skippedSegments = skippedSegments;\n // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`\n for (let i = skippedSegments; i--; ) {\n fragments.unshift(null);\n }\n currentSN += skippedSegments;\n }\n const recentlyRemovedDateranges = skipAttrs.enumeratedString(\n 'RECENTLY-REMOVED-DATERANGES',\n );\n if (recentlyRemovedDateranges) {\n level.recentlyRemovedDateranges =\n recentlyRemovedDateranges.split('\\t');\n }\n break;\n }\n case 'TARGETDURATION':\n level.targetduration = Math.max(parseInt(value1), 1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'INDEPENDENT-SEGMENTS':\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case '#':\n if (value1 || value2) {\n frag.tagList.push(value2 ? [value1, value2] : [value1]);\n }\n break;\n case 'DISCONTINUITY':\n discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'GAP':\n frag.gap = true;\n frag.tagList.push([tag]);\n break;\n case 'BITRATE':\n frag.tagList.push([tag, value1]);\n break;\n case 'DATERANGE': {\n const dateRangeAttr = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, dateRangeAttr, [\n 'ID',\n 'CLASS',\n 'START-DATE',\n 'END-DATE',\n 'SCTE35-CMD',\n 'SCTE35-OUT',\n 'SCTE35-IN',\n ]);\n substituteVariablesInAttributes(\n level,\n dateRangeAttr,\n dateRangeAttr.clientAttrs,\n );\n }\n const dateRange = new DateRange(\n dateRangeAttr,\n level.dateRanges[dateRangeAttr.ID],\n );\n if (dateRange.isValid || level.skippedSegments) {\n level.dateRanges[dateRange.id] = dateRange;\n } else {\n logger.warn(`Ignoring invalid DATERANGE tag: \"${value1}\"`);\n }\n // Add to fragment tag list for backwards compatibility (< v1.2.0)\n frag.tagList.push(['EXT-X-DATERANGE', value1]);\n break;\n }\n case 'DEFINE': {\n if (__USE_VARIABLE_SUBSTITUTION__) {\n const variableAttributes = new AttrList(value1);\n substituteVariablesInAttributes(level, variableAttributes, [\n 'NAME',\n 'VALUE',\n 'IMPORT',\n 'QUERYPARAM',\n ]);\n if ('IMPORT' in variableAttributes) {\n importVariableDefinition(\n level,\n variableAttributes,\n multivariantVariableList,\n );\n } else {\n addVariableDefinition(level, variableAttributes, baseurl);\n }\n }\n break;\n }\n\n case 'DISCONTINUITY-SEQUENCE':\n discontinuityCounter = parseInt(value1);\n break;\n case 'KEY': {\n const levelKey = parseKey(value1, baseurl, level);\n if (levelKey.isSupported()) {\n if (levelKey.method === 'NONE') {\n levelkeys = undefined;\n break;\n }\n if (!levelkeys) {\n levelkeys = {};\n }\n if (levelkeys[levelKey.keyFormat]) {\n levelkeys = Object.assign({}, levelkeys);\n }\n levelkeys[levelKey.keyFormat] = levelKey;\n } else {\n logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: \"${value1}\"`);\n }\n break;\n }\n case 'START':\n level.startTimeOffset = parseStartTimeOffset(value1);\n break;\n case 'MAP': {\n const mapAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, mapAttrs, [\n 'BYTERANGE',\n 'URI',\n ]);\n }\n if (frag.duration) {\n // Initial segment tag is after segment duration tag.\n // #EXTINF: 6.0\n // #EXT-X-MAP:URI=\"init.mp4\n const init = new Fragment(type, baseurl);\n setInitSegment(init, mapAttrs, id, levelkeys);\n currentInitSegment = init;\n frag.initSegment = currentInitSegment;\n if (\n currentInitSegment.rawProgramDateTime &&\n !frag.rawProgramDateTime\n ) {\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n }\n } else {\n // Initial segment tag is before segment duration tag\n // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE\n const end = frag.byteRangeEndOffset;\n if (end) {\n const start = frag.byteRangeStartOffset as number;\n nextByteRange = `${end - start}@${start}`;\n } else {\n nextByteRange = null;\n }\n setInitSegment(frag, mapAttrs, id, levelkeys);\n currentInitSegment = frag;\n createNextFrag = true;\n }\n break;\n }\n case 'SERVER-CONTROL': {\n const serverControlAttrs = new AttrList(value1);\n level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');\n level.canSkipUntil = serverControlAttrs.optionalFloat(\n 'CAN-SKIP-UNTIL',\n 0,\n );\n level.canSkipDateRanges =\n level.canSkipUntil > 0 &&\n serverControlAttrs.bool('CAN-SKIP-DATERANGES');\n level.partHoldBack = serverControlAttrs.optionalFloat(\n 'PART-HOLD-BACK',\n 0,\n );\n level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);\n break;\n }\n case 'PART-INF': {\n const partInfAttrs = new AttrList(value1);\n level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');\n break;\n }\n case 'PART': {\n let partList = level.partList;\n if (!partList) {\n partList = level.partList = [];\n }\n const previousFragmentPart =\n currentPart > 0 ? partList[partList.length - 1] : undefined;\n const index = currentPart++;\n const partAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, partAttrs, [\n 'BYTERANGE',\n 'URI',\n ]);\n }\n const part = new Part(\n partAttrs,\n frag,\n baseurl,\n index,\n previousFragmentPart,\n );\n partList.push(part);\n frag.duration += part.duration;\n break;\n }\n case 'PRELOAD-HINT': {\n const preloadHintAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, preloadHintAttrs, ['URI']);\n }\n level.preloadHint = preloadHintAttrs;\n break;\n }\n case 'RENDITION-REPORT': {\n const renditionReportAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, renditionReportAttrs, [\n 'URI',\n ]);\n }\n level.renditionReports = level.renditionReports || [];\n level.renditionReports.push(renditionReportAttrs);\n break;\n }\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n if (prevFrag && !prevFrag.relurl) {\n fragments.pop();\n totalduration -= prevFrag.duration;\n if (level.partList) {\n level.fragmentHint = prevFrag;\n }\n } else if (level.partList) {\n assignProgramDateTime(frag, prevFrag);\n frag.cc = discontinuityCounter;\n level.fragmentHint = frag;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n }\n const fragmentLength = fragments.length;\n const firstFragment = fragments[0];\n const lastFragment = fragments[fragmentLength - 1];\n totalduration += level.skippedSegments * level.targetduration;\n if (totalduration > 0 && fragmentLength && lastFragment) {\n level.averagetargetduration = totalduration / fragmentLength;\n const lastSn = lastFragment.sn;\n level.endSN = lastSn !== 'initSegment' ? lastSn : 0;\n if (!level.live) {\n lastFragment.endList = true;\n }\n if (firstFragment) {\n level.startCC = firstFragment.cc;\n }\n } else {\n level.endSN = 0;\n level.startCC = 0;\n }\n if (level.fragmentHint) {\n totalduration += level.fragmentHint.duration;\n }\n level.totalduration = totalduration;\n level.endCC = discontinuityCounter;\n\n /**\n * Backfill any missing PDT values\n * \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n * one or more Media Segment URIs, the client SHOULD extrapolate\n * backward from that tag (using EXTINF durations and/or media\n * timestamps) to associate dates with those segments.\"\n * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n * computed.\n */\n if (firstPdtIndex > 0) {\n backfillProgramDateTimes(fragments, firstPdtIndex);\n }\n\n return level;\n }\n}\n\nfunction parseKey(\n keyTagAttributes: string,\n baseurl: string,\n parsed: ParsedMultivariantPlaylist | LevelDetails,\n): LevelKey {\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const keyAttrs = new AttrList(keyTagAttributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, keyAttrs, [\n 'KEYFORMAT',\n 'KEYFORMATVERSIONS',\n 'URI',\n 'IV',\n 'URI',\n ]);\n }\n const decryptmethod = keyAttrs.METHOD ?? '';\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat = keyAttrs.KEYFORMAT ?? 'identity';\n\n if (decrypturi && keyAttrs.IV && !decryptiv) {\n logger.error(`Invalid IV: ${keyAttrs.IV}`);\n }\n // If decrypturi is a URI with a scheme, then baseurl will be ignored\n // No uri is allowed when METHOD is NONE\n const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';\n const keyFormatVersions = (\n decryptkeyformatversions ? decryptkeyformatversions : '1'\n )\n .split('/')\n .map(Number)\n .filter(Number.isFinite);\n\n return new LevelKey(\n decryptmethod,\n resolvedUri,\n decryptkeyformat,\n keyFormatVersions,\n decryptiv,\n );\n}\n\nfunction parseStartTimeOffset(startAttributes: string): number | null {\n const startAttrs = new AttrList(startAttributes);\n const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n if (Number.isFinite(startTimeOffset)) {\n return startTimeOffset;\n }\n return null;\n}\n\nfunction setCodecs(\n codecsAttributeValue: string | undefined,\n level: LevelParsed,\n) {\n let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter((c) => c);\n ['video', 'audio', 'text'].forEach((type: CodecType) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n // Comma separated list of all codecs for type\n level[`${type}Codec`] = filtered.join(',');\n // Remove known codecs so that only unknownCodecs are left after iterating through each type\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n level.unknownCodecs = codecs;\n}\n\nfunction assignCodec(\n media: MediaPlaylist,\n groupItem: { audioCodec?: string; textCodec?: string },\n codecProperty: 'audioCodec' | 'textCodec',\n) {\n const codecValue = groupItem[codecProperty];\n if (codecValue) {\n media[codecProperty] = codecValue;\n }\n}\n\nfunction backfillProgramDateTimes(\n fragments: M3U8ParserFragments,\n firstPdtIndex: number,\n) {\n let fragPrev = fragments[firstPdtIndex] as Fragment;\n for (let i = firstPdtIndex; i--; ) {\n const frag = fragments[i];\n // Exit on delta-playlist skipped segments\n if (!frag) {\n return;\n }\n frag.programDateTime =\n (fragPrev.programDateTime as number) - frag.duration * 1000;\n fragPrev = frag;\n }\n}\n\nfunction assignProgramDateTime(frag, prevFrag) {\n if (frag.rawProgramDateTime) {\n frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n } else if (prevFrag?.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n\n if (!Number.isFinite(frag.programDateTime)) {\n frag.programDateTime = null;\n frag.rawProgramDateTime = null;\n }\n}\n\nfunction setInitSegment(\n frag: Fragment,\n mapAttrs: AttrList,\n id: number,\n levelkeys: { [key: string]: LevelKey } | undefined,\n) {\n frag.relurl = mapAttrs.URI;\n if (mapAttrs.BYTERANGE) {\n frag.setByteRange(mapAttrs.BYTERANGE);\n }\n frag.level = id;\n frag.sn = 'initSegment';\n if (levelkeys) {\n frag.levelkeys = levelkeys;\n }\n frag.initSegment = null;\n}\n\nfunction setFragLevelKeys(\n frag: Fragment,\n levelkeys: { [key: string]: LevelKey },\n level: LevelDetails,\n) {\n frag.levelkeys = levelkeys;\n const { encryptedFragments } = level;\n if (\n (!encryptedFragments.length ||\n encryptedFragments[encryptedFragments.length - 1].levelkeys !==\n levelkeys) &&\n Object.keys(levelkeys).some(\n (format) => levelkeys![format].isCommonEncryption,\n )\n ) {\n encryptedFragments.push(frag);\n }\n}\n","import type { LoaderConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { KeyLoaderInfo } from '../loader/key-loader';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { HlsUrlParameters } from './level';\n\nexport interface LoaderContext {\n // target URL\n url: string;\n // loader response type (arraybuffer or default response type for playlist)\n responseType: string;\n // headers\n headers?: Record<string, string>;\n // start byte range offset\n rangeStart?: number;\n // end byte range offset\n rangeEnd?: number;\n // true if onProgress should report partial chunk of loaded content\n progressData?: boolean;\n}\n\nexport interface FragmentLoaderContext extends LoaderContext {\n frag: Fragment;\n part: Part | null;\n resetIV?: boolean;\n}\n\nexport interface KeyLoaderContext extends LoaderContext {\n keyInfo: KeyLoaderInfo;\n frag: Fragment;\n}\n\nexport interface LoaderConfiguration {\n // LoaderConfig policy that overrides required settings\n loadPolicy: LoaderConfig;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry maxNumRetry\n */\n // Max number of load retries\n maxRetry: number;\n /**\n * @deprecated use LoaderConfig maxTimeToFirstByteMs and maxLoadTimeMs\n */\n // Timeout after which `onTimeOut` callback will be triggered\n // when loading has not finished after that delay\n timeout: number;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry retryDelayMs\n */\n // Delay between an I/O error and following connection retry (ms).\n // This to avoid spamming the server\n retryDelay: number;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry maxRetryDelayMs\n */\n // max connection retry delay (ms)\n maxRetryDelay: number;\n // When streaming progressively, this is the minimum chunk size required to emit a PROGRESS event\n highWaterMark?: number;\n}\n\nexport interface LoaderResponse {\n url: string;\n data?: string | ArrayBuffer | Object;\n // Errors can include HTTP status code and error message\n // Successful responses should include status code 200\n code?: number;\n text?: string;\n}\n\nexport interface LoaderStats {\n aborted: boolean;\n loaded: number;\n retry: number;\n total: number;\n chunkCount: number;\n bwEstimate: number;\n loading: HlsProgressivePerformanceTiming;\n parsing: HlsPerformanceTiming;\n buffering: HlsProgressivePerformanceTiming;\n}\n\nexport interface HlsPerformanceTiming {\n start: number;\n end: number;\n}\n\nexport interface HlsChunkPerformanceTiming extends HlsPerformanceTiming {\n executeStart: number;\n executeEnd: number;\n}\n\nexport interface HlsProgressivePerformanceTiming extends HlsPerformanceTiming {\n first: number;\n}\n\nexport type LoaderOnSuccess<T extends LoaderContext> = (\n response: LoaderResponse,\n stats: LoaderStats,\n context: T,\n networkDetails: any,\n) => void;\n\nexport type LoaderOnProgress<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n data: string | ArrayBuffer,\n networkDetails: any,\n) => void;\n\nexport type LoaderOnError<T extends LoaderContext> = (\n error: {\n // error status code\n code: number;\n // error description\n text: string;\n },\n context: T,\n networkDetails: any,\n stats: LoaderStats,\n) => void;\n\nexport type LoaderOnTimeout<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any,\n) => void;\n\nexport type LoaderOnAbort<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any,\n) => void;\n\nexport interface LoaderCallbacks<T extends LoaderContext> {\n onSuccess: LoaderOnSuccess<T>;\n onError: LoaderOnError<T>;\n onTimeout: LoaderOnTimeout<T>;\n onAbort?: LoaderOnAbort<T>;\n onProgress?: LoaderOnProgress<T>;\n}\n\nexport interface Loader<T extends LoaderContext> {\n destroy(): void;\n abort(): void;\n load(\n context: T,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<T>,\n ): void;\n /**\n * `getCacheAge()` is called by hls.js to get the duration that a given object\n * has been sitting in a cache proxy when playing live. If implemented,\n * this should return a value in seconds.\n *\n * For HTTP based loaders, this should return the contents of the \"age\" header.\n *\n * @returns time object being lodaded\n */\n getCacheAge?: () => number | null;\n getResponseHeader?: (name: string) => string | null;\n context: T | null;\n stats: LoaderStats;\n}\n\nexport const enum PlaylistContextType {\n MANIFEST = 'manifest',\n LEVEL = 'level',\n AUDIO_TRACK = 'audioTrack',\n SUBTITLE_TRACK = 'subtitleTrack',\n}\n\nexport const enum PlaylistLevelType {\n MAIN = 'main',\n AUDIO = 'audio',\n SUBTITLE = 'subtitle',\n}\n\nexport interface PlaylistLoaderContext extends LoaderContext {\n type: PlaylistContextType;\n // the level index to load\n level: number | null;\n // level or track id from LevelLoadingData / TrackLoadingData\n id: number | null;\n // Media Playlist Group ID\n groupId?: string;\n // Content Steering Pathway ID (or undefined for default Pathway \".\")\n pathwayId?: string;\n // internal representation of a parsed m3u8 level playlist\n levelDetails?: LevelDetails;\n // Blocking playlist request delivery directives (or null id none were added to playlist url\n deliveryDirectives: HlsUrlParameters | null;\n}\n","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n */\n\nimport { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { logger } from '../utils/logger';\nimport M3U8Parser from './m3u8-parser';\nimport type { LevelParsed, VariableMap } from '../types/level';\nimport type {\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n LoaderResponse,\n LoaderStats,\n PlaylistLoaderContext,\n} from '../types/loader';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { LevelDetails } from './level-details';\nimport { AttrList } from '../utils/attr-list';\nimport type Hls from '../hls';\nimport type {\n ErrorData,\n LevelLoadingData,\n ManifestLoadingData,\n TrackLoadingData,\n} from '../types/events';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { MediaAttributes } from '../types/media-playlist';\nimport type { LoaderConfig, RetryConfig } from '../config';\n\nfunction mapContextToLevelType(\n context: PlaylistLoaderContext,\n): PlaylistLevelType {\n const { type } = context;\n\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n return PlaylistLevelType.AUDIO;\n case PlaylistContextType.SUBTITLE_TRACK:\n return PlaylistLevelType.SUBTITLE;\n default:\n return PlaylistLevelType.MAIN;\n }\n}\n\nfunction getResponseUrl(\n response: LoaderResponse,\n context: PlaylistLoaderContext,\n): string {\n let url = response.url;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n return url;\n}\n\nclass PlaylistLoader implements NetworkComponentAPI {\n private readonly hls: Hls;\n private readonly loaders: {\n [key: string]: Loader<LoaderContext>;\n } = Object.create(null);\n private variableList: VariableMap | null = null;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.registerListeners();\n }\n\n public startLoad(startPosition: number): void {}\n\n public stopLoad(): void {\n this.destroyInternalLoaders();\n }\n\n private registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n }\n\n private unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n */\n private createInternalLoader(\n context: PlaylistLoaderContext,\n ): Loader<LoaderContext> {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n const loader = new InternalLoader(config) as Loader<PlaylistLoaderContext>;\n\n this.loaders[context.type] = loader;\n return loader;\n }\n\n private getInternalLoader(\n context: PlaylistLoaderContext,\n ): Loader<LoaderContext> | undefined {\n return this.loaders[context.type];\n }\n\n private resetInternalLoader(contextType): void {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n private destroyInternalLoaders(): void {\n for (const contextType in this.loaders) {\n const loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n public destroy(): void {\n this.variableList = null;\n this.unregisterListeners();\n this.destroyInternalLoaders();\n }\n\n private onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) {\n const { url } = data;\n this.variableList = null;\n this.load({\n id: null,\n level: 0,\n responseType: 'text',\n type: PlaylistContextType.MANIFEST,\n url,\n deliveryDirectives: null,\n });\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { id, level, pathwayId, url, deliveryDirectives } = data;\n this.load({\n id,\n level,\n pathwayId,\n responseType: 'text',\n type: PlaylistContextType.LEVEL,\n url,\n deliveryDirectives,\n });\n }\n\n private onAudioTrackLoading(\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData,\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.AUDIO_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private onSubtitleTrackLoading(\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData,\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.SUBTITLE_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private load(context: PlaylistLoaderContext): void {\n const config = this.hls.config;\n\n // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context as PlaylistLoaderContext;\n if (\n loaderContext &&\n loaderContext.url === context.url &&\n loaderContext.level === context.level\n ) {\n // same URL can't overlap\n logger.trace('[playlist-loader]: playlist request ongoing');\n return;\n }\n logger.log(\n `[playlist-loader]: aborting previous loader for type: ${context.type}`,\n );\n loader.abort();\n }\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n let loadPolicy: LoaderConfig;\n if (context.type === PlaylistContextType.MANIFEST) {\n loadPolicy = config.manifestLoadPolicy.default;\n } else {\n loadPolicy = Object.assign({}, config.playlistLoadPolicy.default, {\n timeoutRetry: null,\n errorRetry: null,\n });\n }\n loader = this.createInternalLoader(context);\n\n // Override level/track timeout for LL-HLS requests\n // (the default of 10000ms is counter productive to blocking playlist reload requests)\n if (Number.isFinite(context.deliveryDirectives?.part)) {\n let levelDetails: LevelDetails | undefined;\n if (\n context.type === PlaylistContextType.LEVEL &&\n context.level !== null\n ) {\n levelDetails = this.hls.levels[context.level].details;\n } else if (\n context.type === PlaylistContextType.AUDIO_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.audioTracks[context.id].details;\n } else if (\n context.type === PlaylistContextType.SUBTITLE_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.subtitleTracks[context.id].details;\n }\n if (levelDetails) {\n const partTarget = levelDetails.partTarget;\n const targetDuration = levelDetails.targetduration;\n if (partTarget && targetDuration) {\n const maxLowLatencyPlaylistRefresh =\n Math.max(partTarget * 3, targetDuration * 0.8) * 1000;\n loadPolicy = Object.assign({}, loadPolicy, {\n maxTimeToFirstByteMs: Math.min(\n maxLowLatencyPlaylistRefresh,\n loadPolicy.maxTimeToFirstByteMs,\n ),\n maxLoadTimeMs: Math.min(\n maxLowLatencyPlaylistRefresh,\n loadPolicy.maxTimeToFirstByteMs,\n ),\n });\n }\n }\n }\n\n const legacyRetryCompatibility: RetryConfig | Record<string, void> =\n loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0,\n };\n\n const loaderCallbacks: LoaderCallbacks<PlaylistLoaderContext> = {\n onSuccess: (response, stats, context, networkDetails) => {\n const loader = this.getInternalLoader(context) as\n | Loader<PlaylistLoaderContext>\n | undefined;\n this.resetInternalLoader(context.type);\n\n const string = response.data as string;\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this.handleManifestParsingError(\n response,\n context,\n new Error('no EXTM3U delimiter'),\n networkDetails || null,\n stats,\n );\n return;\n }\n\n stats.parsing.start = performance.now();\n if (M3U8Parser.isMediaPlaylist(string)) {\n this.handleTrackOrLevelPlaylist(\n response,\n stats,\n context,\n networkDetails || null,\n loader,\n );\n } else {\n this.handleMasterPlaylist(response, stats, context, networkDetails);\n }\n },\n onError: (response, context, networkDetails, stats) => {\n this.handleNetworkError(\n context,\n networkDetails,\n false,\n response,\n stats,\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.handleNetworkError(\n context,\n networkDetails,\n true,\n undefined,\n stats,\n );\n },\n };\n\n // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n }\n\n private handleMasterPlaylist(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n ): void {\n const hls = this.hls;\n const string = response.data as string;\n\n const url = getResponseUrl(response, context);\n\n const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);\n\n if (parsedResult.playlistParsingError) {\n this.handleManifestParsingError(\n response,\n context,\n parsedResult.playlistParsingError,\n networkDetails,\n stats,\n );\n return;\n }\n\n const {\n contentSteering,\n levels,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList,\n } = parsedResult;\n\n this.variableList = variableList;\n\n const {\n AUDIO: audioTracks = [],\n SUBTITLES: subtitles,\n 'CLOSED-CAPTIONS': captions,\n } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n const embeddedAudioFound: boolean = audioTracks.some(\n (audioTrack) => !audioTrack.url,\n );\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (\n !embeddedAudioFound &&\n levels[0].audioCodec &&\n !levels[0].attrs.AUDIO\n ) {\n logger.log(\n '[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one',\n );\n audioTracks.unshift({\n type: 'main',\n name: 'main',\n groupId: 'main',\n default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: new AttrList({}) as MediaAttributes,\n bitrate: 0,\n url: '',\n });\n }\n }\n\n hls.trigger(Events.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n contentSteering,\n url,\n stats,\n networkDetails,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList,\n });\n }\n\n private handleTrackOrLevelPlaylist(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n loader: Loader<PlaylistLoaderContext> | undefined,\n ): void {\n const hls = this.hls;\n const { id, level, type } = context;\n\n const url = getResponseUrl(response, context);\n const levelUrlId = 0;\n const levelId = Number.isFinite(level as number)\n ? (level as number)\n : Number.isFinite(id as number)\n ? (id as number)\n : 0;\n const levelType = mapContextToLevelType(context);\n const levelDetails: LevelDetails = M3U8Parser.parseLevelPlaylist(\n response.data as string,\n url,\n levelId,\n levelType,\n levelUrlId,\n this.variableList,\n );\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === PlaylistContextType.MANIFEST) {\n const singleLevel: LevelParsed = {\n attrs: new AttrList({}),\n bitrate: 0,\n details: levelDetails,\n name: '',\n url,\n };\n\n hls.trigger(Events.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails,\n sessionData: null,\n sessionKeys: null,\n contentSteering: null,\n startTimeOffset: null,\n variableList: null,\n });\n }\n\n // save parsing time\n stats.parsing.end = performance.now();\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this.handlePlaylistLoaded(\n levelDetails,\n response,\n stats,\n context,\n networkDetails,\n loader,\n );\n }\n\n private handleManifestParsingError(\n response: LoaderResponse,\n context: PlaylistLoaderContext,\n error: Error,\n networkDetails: any,\n stats: LoaderStats,\n ): void {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: context.type === PlaylistContextType.MANIFEST,\n url: response.url,\n err: error,\n error,\n reason: error.message,\n response,\n context,\n networkDetails,\n stats,\n });\n }\n\n private handleNetworkError(\n context: PlaylistLoaderContext,\n networkDetails: any,\n timeout = false,\n response: { code: number; text: string } | undefined,\n stats: LoaderStats,\n ): void {\n let message = `A network ${\n timeout\n ? 'timeout'\n : 'error' + (response ? ' (status ' + response.code + ')' : '')\n } occurred while loading ${context.type}`;\n if (context.type === PlaylistContextType.LEVEL) {\n message += `: ${context.level} id: ${context.id}`;\n } else if (\n context.type === PlaylistContextType.AUDIO_TRACK ||\n context.type === PlaylistContextType.SUBTITLE_TRACK\n ) {\n message += ` id: ${context.id} group-id: \"${context.groupId}\"`;\n }\n const error = new Error(message);\n logger.warn(`[playlist-loader]: ${message}`);\n let details = ErrorDetails.UNKNOWN;\n let fatal = false;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n details = timeout\n ? ErrorDetails.MANIFEST_LOAD_TIMEOUT\n : ErrorDetails.MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case PlaylistContextType.LEVEL:\n details = timeout\n ? ErrorDetails.LEVEL_LOAD_TIMEOUT\n : ErrorDetails.LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.AUDIO_TRACK:\n details = timeout\n ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT\n : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n details = timeout\n ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT\n : ErrorDetails.SUBTITLE_LOAD_ERROR;\n fatal = false;\n break;\n }\n\n if (loader) {\n this.resetInternalLoader(context.type);\n }\n\n const errorData: ErrorData = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: context.url,\n loader,\n context,\n error,\n networkDetails,\n stats,\n };\n\n if (response) {\n const url = networkDetails?.url || context.url;\n errorData.response = { url, data: undefined as any, ...response };\n }\n\n this.hls.trigger(Events.ERROR, errorData);\n }\n\n private handlePlaylistLoaded(\n levelDetails: LevelDetails,\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n loader: Loader<PlaylistLoaderContext> | undefined,\n ): void {\n const hls = this.hls;\n const { type, level, id, groupId, deliveryDirectives } = context;\n const url = getResponseUrl(response, context);\n const parent = mapContextToLevelType(context);\n const levelIndex =\n typeof context.level === 'number' && parent === PlaylistLevelType.MAIN\n ? (level as number)\n : undefined;\n if (!levelDetails.fragments.length) {\n const error = new Error('No Segments found in Playlist');\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url,\n error,\n reason: error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats,\n });\n return;\n }\n if (!levelDetails.targetduration) {\n levelDetails.playlistParsingError = new Error('Missing Target Duration');\n }\n const error = levelDetails.playlistParsingError;\n if (error) {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_PARSING_ERROR,\n fatal: false,\n url,\n error,\n reason: error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats,\n });\n return;\n }\n\n if (levelDetails.live && loader) {\n if (loader.getCacheAge) {\n levelDetails.ageHeader = loader.getCacheAge() || 0;\n }\n if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {\n levelDetails.ageHeader = 0;\n }\n }\n\n switch (type) {\n case PlaylistContextType.MANIFEST:\n case PlaylistContextType.LEVEL:\n hls.trigger(Events.LEVEL_LOADED, {\n details: levelDetails,\n level: levelIndex || 0,\n id: id || 0,\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n case PlaylistContextType.AUDIO_TRACK:\n hls.trigger(Events.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n hls.trigger(Events.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n }\n }\n}\n\nexport default PlaylistLoader;\n","import { logger } from './logger';\n\nexport function sendAddTrackEvent(track: TextTrack, videoEl: HTMLMediaElement) {\n let event: Event;\n try {\n event = new Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n (event as any).track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function addCueToTrack(track: TextTrack, cue: VTTCue) {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues && !track.cues.getCueById(cue.id)) {\n try {\n track.addCue(cue);\n if (!track.cues.getCueById(cue.id)) {\n throw new Error(`addCue is failed for: ${cue}`);\n }\n } catch (err) {\n logger.debug(`[texttrack-utils]: ${err}`);\n try {\n const textTrackCue = new (self.TextTrackCue as any)(\n cue.startTime,\n cue.endTime,\n cue.text,\n );\n textTrackCue.id = cue.id;\n track.addCue(textTrackCue);\n } catch (err2) {\n logger.debug(\n `[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`,\n );\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\nexport function clearCurrentCues(track: TextTrack) {\n // When track.mode is disabled, track.cues will be null.\n // To guarantee the removal of cues, we need to temporarily\n // change the mode to hidden\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues) {\n for (let i = track.cues.length; i--; ) {\n track.removeCue(track.cues[i]);\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\nexport function removeCuesInRange(\n track: TextTrack,\n start: number,\n end: number,\n predicate?: (cue: TextTrackCue) => boolean,\n) {\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n\n if (track.cues && track.cues.length > 0) {\n const cues = getCuesInRange(track.cues, start, end);\n for (let i = 0; i < cues.length; i++) {\n if (!predicate || predicate(cues[i])) {\n track.removeCue(cues[i]);\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\n// Find first cue starting after given time.\n// Modified version of binary search O(log(n)).\nfunction getFirstCueIndexAfterTime(\n cues: TextTrackCueList | TextTrackCue[],\n time: number,\n): number {\n // If first cue starts after time, start there\n if (time < cues[0].startTime) {\n return 0;\n }\n // If the last cue ends before time there is no overlap\n const len = cues.length - 1;\n if (time > cues[len].endTime) {\n return -1;\n }\n\n let left = 0;\n let right = len;\n\n while (left <= right) {\n const mid = Math.floor((right + left) / 2);\n\n if (time < cues[mid].startTime) {\n right = mid - 1;\n } else if (time > cues[mid].startTime && left < len) {\n left = mid + 1;\n } else {\n // If it's not lower or higher, it must be equal.\n return mid;\n }\n }\n // At this point, left and right have swapped.\n // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n return cues[left].startTime - time < time - cues[right].startTime\n ? left\n : right;\n}\n\nexport function getCuesInRange(\n cues: TextTrackCueList | TextTrackCue[],\n start: number,\n end: number,\n): TextTrackCue[] {\n const cuesFound: TextTrackCue[] = [];\n const firstCueInRange = getFirstCueIndexAfterTime(cues, start);\n if (firstCueInRange > -1) {\n for (let i = firstCueInRange, len = cues.length; i < len; i++) {\n const cue = cues[i];\n if (cue.startTime >= start && cue.endTime <= end) {\n cuesFound.push(cue);\n } else if (cue.startTime > end) {\n return cuesFound;\n }\n }\n }\n return cuesFound;\n}\n\nexport function filterSubtitleTracks(\n textTrackList: TextTrackList,\n): TextTrack[] {\n const tracks: TextTrack[] = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if (\n (track.kind === 'subtitles' || track.kind === 'captions') &&\n track.label\n ) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n","import type { RationalTimestamp } from '../utils/timescale-conversion';\n\nexport interface Demuxer {\n demux(\n data: Uint8Array,\n timeOffset: number,\n isSampleAes?: boolean,\n flush?: boolean,\n ): DemuxerResult;\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult>;\n flush(timeOffset?: number): DemuxerResult | Promise<DemuxerResult>;\n destroy(): void;\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n );\n resetTimeStamp(defaultInitPTS?: RationalTimestamp | null): void;\n resetContiguity(): void;\n}\n\nexport interface DemuxerResult {\n audioTrack: DemuxedAudioTrack;\n videoTrack: DemuxedVideoTrackBase;\n id3Track: DemuxedMetadataTrack;\n textTrack: DemuxedUserdataTrack;\n}\n\nexport interface DemuxedTrack {\n type: string;\n id: number;\n pid: number;\n inputTimeScale: number;\n sequenceNumber: number;\n samples:\n | AudioSample[]\n | VideoSample[]\n | MetadataSample[]\n | UserdataSample[]\n | Uint8Array;\n timescale?: number;\n container?: string;\n dropped: number;\n duration?: number;\n pesData?: ElementaryStreamData | null;\n codec?: string;\n}\n\nexport interface PassthroughTrack extends DemuxedTrack {\n sampleDuration: number;\n samples: Uint8Array;\n timescale: number;\n duration: number;\n codec: string;\n}\nexport interface DemuxedAudioTrack extends DemuxedTrack {\n config?: number[] | Uint8Array;\n samplerate?: number;\n segmentCodec?: string;\n channelCount?: number;\n manifestCodec?: string;\n samples: AudioSample[];\n}\n\nexport interface DemuxedVideoTrackBase extends DemuxedTrack {\n width?: number;\n height?: number;\n pixelRatio?: [number, number];\n audFound?: boolean;\n pps?: Uint8Array[];\n sps?: Uint8Array[];\n naluState?: number;\n segmentCodec?: string;\n manifestCodec?: string;\n samples: VideoSample[] | Uint8Array;\n}\n\nexport interface DemuxedVideoTrack extends DemuxedVideoTrackBase {\n samples: VideoSample[];\n}\n\nexport interface DemuxedMetadataTrack extends DemuxedTrack {\n samples: MetadataSample[];\n}\n\nexport interface DemuxedUserdataTrack extends DemuxedTrack {\n samples: UserdataSample[];\n}\n\nexport const enum MetadataSchema {\n audioId3 = 'org.id3',\n dateRange = 'com.apple.quicktime.HLS',\n emsg = 'https://aomedia.org/emsg/ID3',\n}\nexport interface MetadataSample {\n pts: number;\n dts: number;\n duration: number;\n len?: number;\n data: Uint8Array;\n type: MetadataSchema;\n}\n\nexport interface UserdataSample {\n pts: number;\n bytes?: Uint8Array;\n type?: number;\n payloadType?: number;\n uuid?: string;\n userData?: string;\n userDataBytes?: Uint8Array;\n}\n\nexport interface VideoSample {\n dts: number;\n pts: number;\n key: boolean;\n frame: boolean;\n units: VideoSampleUnit[];\n debug: string;\n length: number;\n}\n\nexport interface VideoSampleUnit {\n data: Uint8Array;\n type: number;\n state?: number;\n}\n\nexport type AudioSample = {\n unit: Uint8Array;\n pts: number;\n};\n\nexport type AudioFrame = {\n sample: AudioSample;\n length: number;\n missing: number;\n};\n\nexport interface ElementaryStreamData {\n data: Uint8Array[];\n size: number;\n}\n\nexport interface KeyData {\n method: string;\n key: Uint8Array;\n iv: Uint8Array;\n}\n","import { Events } from '../events';\nimport {\n sendAddTrackEvent,\n clearCurrentCues,\n removeCuesInRange,\n} from '../utils/texttrack-utils';\nimport * as ID3 from '../demux/id3';\nimport {\n DateRange,\n isDateRangeCueAttribute,\n isSCTE35Attribute,\n} from '../loader/date-range';\nimport { MetadataSchema } from '../types/demuxer';\nimport type {\n BufferFlushingData,\n FragParsingMetadataData,\n LevelUpdatedData,\n MediaAttachedData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\n\ndeclare global {\n interface Window {\n WebKitDataCue: VTTCue | void;\n }\n}\n\nconst MIN_CUE_DURATION = 0.25;\n\nfunction getCueClass(): typeof VTTCue | typeof TextTrackCue | undefined {\n if (typeof self === 'undefined') return undefined;\n return self.VTTCue || self.TextTrackCue;\n}\n\nfunction createCueWithDataFields(\n Cue: typeof VTTCue | typeof TextTrackCue,\n startTime: number,\n endTime: number,\n data: Object,\n type?: string,\n): VTTCue | TextTrackCue | undefined {\n let cue = new Cue(startTime, endTime, '');\n try {\n (cue as any).value = data;\n if (type) {\n (cue as any).type = type;\n }\n } catch (e) {\n cue = new Cue(\n startTime,\n endTime,\n JSON.stringify(type ? { type, ...data } : data),\n );\n }\n return cue;\n}\n\n// VTTCue latest draft allows an infinite duration, fallback\n// to MAX_VALUE if necessary\nconst MAX_CUE_ENDTIME = (() => {\n const Cue = getCueClass();\n try {\n Cue && new Cue(0, Number.POSITIVE_INFINITY, '');\n } catch (e) {\n return Number.MAX_VALUE;\n }\n return Number.POSITIVE_INFINITY;\n})();\n\nfunction dateRangeDateToTimelineSeconds(date: Date, offset: number): number {\n return date.getTime() / 1000 - offset;\n}\n\nfunction hexToArrayBuffer(str): ArrayBuffer {\n return Uint8Array.from(\n str\n .replace(/^0x/, '')\n .replace(/([\\da-fA-F]{2}) ?/g, '0x$1 ')\n .replace(/ +$/, '')\n .split(' '),\n ).buffer;\n}\nclass ID3TrackController implements ComponentAPI {\n private hls: Hls;\n private id3Track: TextTrack | null = null;\n private media: HTMLMediaElement | null = null;\n private dateRangeCuesAppended: Record<\n string,\n {\n cues: Record<string, VTTCue | TextTrackCue>;\n dateRange: DateRange;\n durationKnown: boolean;\n }\n > = {};\n\n constructor(hls) {\n this.hls = hls;\n this._registerListeners();\n }\n\n destroy() {\n this._unregisterListeners();\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n // @ts-ignore\n this.hls = null;\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n // Add ID3 metatadata text track.\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ): void {\n this.media = data.media;\n }\n\n protected onMediaDetaching(): void {\n if (!this.id3Track) {\n return;\n }\n clearCurrentCues(this.id3Track);\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n }\n\n private onManifestLoading() {\n this.dateRangeCuesAppended = {};\n }\n\n createTrack(media: HTMLMediaElement): TextTrack {\n const track = this.getID3Track(media.textTracks) as TextTrack;\n track.mode = 'hidden';\n return track;\n }\n\n getID3Track(textTracks: TextTrackList): TextTrack | void {\n if (!this.media) {\n return;\n }\n for (let i = 0; i < textTracks.length; i++) {\n const textTrack: TextTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n }\n\n onFragParsingMetadata(\n event: Events.FRAG_PARSING_METADATA,\n data: FragParsingMetadataData,\n ) {\n if (!this.media) {\n return;\n }\n\n const {\n hls: {\n config: { enableEmsgMetadataCues, enableID3MetadataCues },\n },\n } = this;\n if (!enableEmsgMetadataCues && !enableID3MetadataCues) {\n return;\n }\n\n const { samples } = data;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const Cue = getCueClass();\n if (!Cue) {\n return;\n }\n\n for (let i = 0; i < samples.length; i++) {\n const type = samples[i].type;\n if (\n (type === MetadataSchema.emsg && !enableEmsgMetadataCues) ||\n !enableID3MetadataCues\n ) {\n continue;\n }\n\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n const startTime = samples[i].pts;\n let endTime: number = startTime + samples[i].duration;\n\n if (endTime > MAX_CUE_ENDTIME) {\n endTime = MAX_CUE_ENDTIME;\n }\n\n const timeDiff = endTime - startTime;\n if (timeDiff <= 0) {\n endTime = startTime + MIN_CUE_DURATION;\n }\n\n for (let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n // add a bounds to any unbounded cues\n this.updateId3CueEnds(startTime, type);\n const cue = createCueWithDataFields(\n Cue,\n startTime,\n endTime,\n frame,\n type,\n );\n if (cue) {\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n }\n\n updateId3CueEnds(startTime: number, type: MetadataSchema) {\n const cues = this.id3Track?.cues;\n if (cues) {\n for (let i = cues.length; i--; ) {\n const cue = cues[i] as any;\n if (\n cue.type === type &&\n cue.startTime < startTime &&\n cue.endTime === MAX_CUE_ENDTIME\n ) {\n cue.endTime = startTime;\n }\n }\n }\n }\n\n onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { startOffset, endOffset, type }: BufferFlushingData,\n ) {\n const { id3Track, hls } = this;\n if (!hls) {\n return;\n }\n\n const {\n config: { enableEmsgMetadataCues, enableID3MetadataCues },\n } = hls;\n if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {\n let predicate;\n\n if (type === 'audio') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues;\n } else if (type === 'video') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues;\n } else {\n predicate = (cue) =>\n ((cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues) ||\n ((cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues);\n }\n removeCuesInRange(id3Track, startOffset, endOffset, predicate);\n }\n }\n\n onLevelUpdated(event: Events.LEVEL_UPDATED, { details }: LevelUpdatedData) {\n if (\n !this.media ||\n !details.hasProgramDateTime ||\n !this.hls.config.enableDateRangeMetadataCues\n ) {\n return;\n }\n const { dateRangeCuesAppended, id3Track } = this;\n const { dateRanges } = details;\n const ids = Object.keys(dateRanges);\n // Remove cues from track not found in details.dateRanges\n if (id3Track) {\n const idsToRemove = Object.keys(dateRangeCuesAppended).filter(\n (id) => !ids.includes(id),\n );\n for (let i = idsToRemove.length; i--; ) {\n const id = idsToRemove[i];\n Object.keys(dateRangeCuesAppended[id].cues).forEach((key) => {\n id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);\n });\n delete dateRangeCuesAppended[id];\n }\n }\n // Exit if the playlist does not have Date Ranges or does not have Program Date Time\n const lastFragment = details.fragments[details.fragments.length - 1];\n if (ids.length === 0 || !Number.isFinite(lastFragment?.programDateTime)) {\n return;\n }\n\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const dateTimeOffset =\n (lastFragment.programDateTime as number) / 1000 - lastFragment.start;\n const Cue = getCueClass();\n\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i];\n const dateRange = dateRanges[id];\n const startTime = dateRangeDateToTimelineSeconds(\n dateRange.startDate,\n dateTimeOffset,\n );\n\n // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)\n const appendedDateRangeCues = dateRangeCuesAppended[id];\n const cues = appendedDateRangeCues?.cues || {};\n let durationKnown = appendedDateRangeCues?.durationKnown || false;\n let endTime = MAX_CUE_ENDTIME;\n const endDate = dateRange.endDate;\n if (endDate) {\n endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);\n durationKnown = true;\n } else if (dateRange.endOnNext && !durationKnown) {\n const nextDateRangeWithSameClass = ids.reduce(\n (candidateDateRange: DateRange | null, id) => {\n if (id !== dateRange.id) {\n const otherDateRange = dateRanges[id];\n if (\n otherDateRange.class === dateRange.class &&\n otherDateRange.startDate > dateRange.startDate &&\n (!candidateDateRange ||\n dateRange.startDate < candidateDateRange.startDate)\n ) {\n return otherDateRange;\n }\n }\n return candidateDateRange;\n },\n null,\n );\n if (nextDateRangeWithSameClass) {\n endTime = dateRangeDateToTimelineSeconds(\n nextDateRangeWithSameClass.startDate,\n dateTimeOffset,\n );\n durationKnown = true;\n }\n }\n\n // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)\n // This is to emulate Safari HLS playback handling of DateRange tags\n const attributes = Object.keys(dateRange.attr);\n for (let j = 0; j < attributes.length; j++) {\n const key = attributes[j];\n if (!isDateRangeCueAttribute(key)) {\n continue;\n }\n const cue = cues[key];\n if (cue) {\n if (durationKnown && !appendedDateRangeCues.durationKnown) {\n cue.endTime = endTime;\n }\n } else if (Cue) {\n let data = dateRange.attr[key];\n if (isSCTE35Attribute(key)) {\n data = hexToArrayBuffer(data);\n }\n const cue = createCueWithDataFields(\n Cue,\n startTime,\n endTime,\n { key, data },\n MetadataSchema.dateRange,\n );\n if (cue) {\n cue.id = id;\n this.id3Track.addCue(cue);\n cues[key] = cue;\n }\n }\n }\n\n // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes\n dateRangeCuesAppended[id] = {\n cues,\n dateRange,\n durationKnown,\n };\n }\n }\n}\n\nexport default ID3TrackController;\n","import { LevelDetails } from '../loader/level-details';\nimport { ErrorDetails } from '../errors';\nimport { Events } from '../events';\nimport type {\n ErrorData,\n LevelUpdatedData,\n MediaAttachingData,\n} from '../types/events';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\n\nexport default class LatencyController implements ComponentAPI {\n private hls: Hls;\n private readonly config: HlsConfig;\n private media: HTMLMediaElement | null = null;\n private levelDetails: LevelDetails | null = null;\n private currentTime: number = 0;\n private stallCount: number = 0;\n private _latency: number | null = null;\n private timeupdateHandler = () => this.timeupdate();\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n\n get latency(): number {\n return this._latency || 0;\n }\n\n get maxLatency(): number {\n const { config, levelDetails } = this;\n if (config.liveMaxLatencyDuration !== undefined) {\n return config.liveMaxLatencyDuration;\n }\n return levelDetails\n ? config.liveMaxLatencyDurationCount * levelDetails.targetduration\n : 0;\n }\n\n get targetLatency(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n const { holdBack, partHoldBack, targetduration } = levelDetails;\n const { liveSyncDuration, liveSyncDurationCount, lowLatencyMode } =\n this.config;\n const userConfig = this.hls.userConfig;\n let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;\n if (\n userConfig.liveSyncDuration ||\n userConfig.liveSyncDurationCount ||\n targetLatency === 0\n ) {\n targetLatency =\n liveSyncDuration !== undefined\n ? liveSyncDuration\n : liveSyncDurationCount * targetduration;\n }\n const maxLiveSyncOnStallIncrease = targetduration;\n const liveSyncOnStallIncrease = 1.0;\n return (\n targetLatency +\n Math.min(\n this.stallCount * liveSyncOnStallIncrease,\n maxLiveSyncOnStallIncrease,\n )\n );\n }\n\n get liveSyncPosition(): number | null {\n const liveEdge = this.estimateLiveEdge();\n const targetLatency = this.targetLatency;\n const levelDetails = this.levelDetails;\n if (liveEdge === null || targetLatency === null || levelDetails === null) {\n return null;\n }\n const edge = levelDetails.edge;\n const syncPosition = liveEdge - targetLatency - this.edgeStalled;\n const min = edge - levelDetails.totalduration;\n const max =\n edge -\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration);\n return Math.min(Math.max(min, syncPosition), max);\n }\n\n get drift(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 1;\n }\n return levelDetails.drift;\n }\n\n get edgeStalled(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 0;\n }\n const maxLevelUpdateAge =\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration) * 3;\n return Math.max(levelDetails.age - maxLevelUpdateAge, 0);\n }\n\n private get forwardBufferLength(): number {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return 0;\n }\n const bufferedRanges = media.buffered.length;\n return (\n (bufferedRanges\n ? media.buffered.end(bufferedRanges - 1)\n : levelDetails.edge) - this.currentTime\n );\n }\n\n public destroy(): void {\n this.unregisterListeners();\n this.onMediaDetaching();\n this.levelDetails = null;\n // @ts-ignore\n this.hls = this.timeupdateHandler = null;\n }\n\n private registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n this.hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n this.hls.off(Events.ERROR, this.onError, this);\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachingData,\n ) {\n this.media = data.media;\n this.media.addEventListener('timeupdate', this.timeupdateHandler);\n }\n\n private onMediaDetaching() {\n if (this.media) {\n this.media.removeEventListener('timeupdate', this.timeupdateHandler);\n this.media = null;\n }\n }\n\n private onManifestLoading() {\n this.levelDetails = null;\n this._latency = null;\n this.stallCount = 0;\n }\n\n private onLevelUpdated(\n event: Events.LEVEL_UPDATED,\n { details }: LevelUpdatedData,\n ) {\n this.levelDetails = details;\n if (details.advanced) {\n this.timeupdate();\n }\n if (!details.live && this.media) {\n this.media.removeEventListener('timeupdate', this.timeupdateHandler);\n }\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {\n return;\n }\n this.stallCount++;\n if (this.levelDetails?.live) {\n logger.warn(\n '[playback-rate-controller]: Stall detected, adjusting target latency',\n );\n }\n }\n\n private timeupdate() {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return;\n }\n this.currentTime = media.currentTime;\n\n const latency = this.computeLatency();\n if (latency === null) {\n return;\n }\n this._latency = latency;\n\n // Adapt playbackRate to meet target latency in low-latency mode\n const { lowLatencyMode, maxLiveSyncPlaybackRate } = this.config;\n if (\n !lowLatencyMode ||\n maxLiveSyncPlaybackRate === 1 ||\n !levelDetails.live\n ) {\n return;\n }\n const targetLatency = this.targetLatency;\n if (targetLatency === null) {\n return;\n }\n const distanceFromTarget = latency - targetLatency;\n // Only adjust playbackRate when within one target duration of targetLatency\n // and more than one second from under-buffering.\n // Playback further than one target duration from target can be considered DVR playback.\n const liveMinLatencyDuration = Math.min(\n this.maxLatency,\n targetLatency + levelDetails.targetduration,\n );\n const inLiveRange = distanceFromTarget < liveMinLatencyDuration;\n\n if (\n inLiveRange &&\n distanceFromTarget > 0.05 &&\n this.forwardBufferLength > 1\n ) {\n const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));\n const rate =\n Math.round(\n (2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled))) *\n 20,\n ) / 20;\n media.playbackRate = Math.min(max, Math.max(1, rate));\n } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {\n media.playbackRate = 1;\n }\n }\n\n private estimateLiveEdge(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n return levelDetails.edge + levelDetails.age;\n }\n\n private computeLatency(): number | null {\n const liveEdge = this.estimateLiveEdge();\n if (liveEdge === null) {\n return null;\n }\n return liveEdge - this.currentTime;\n }\n}\n","import type { MediaPlaylist } from './media-playlist';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { AttrList } from '../utils/attr-list';\nimport type { MediaDecodingInfo } from '../utils/mediacapabilities-helper';\n\nexport interface LevelParsed {\n attrs: LevelAttributes;\n audioCodec?: string;\n bitrate: number;\n details?: LevelDetails;\n height?: number;\n id?: number;\n name: string;\n textCodec?: string;\n unknownCodecs?: string[];\n url: string;\n videoCodec?: string;\n width?: number;\n}\n\nexport interface LevelAttributes extends AttrList {\n 'ALLOWED-CPC'?: string;\n AUDIO?: string;\n 'AVERAGE-BANDWIDTH'?: string;\n BANDWIDTH?: string;\n 'CLOSED-CAPTIONS'?: string;\n CODECS?: string;\n 'FRAME-RATE'?: string;\n 'HDCP-LEVEL'?: 'TYPE-0' | 'TYPE-1' | 'NONE';\n 'PATHWAY-ID'?: string;\n RESOLUTION?: string;\n SCORE?: string;\n 'STABLE-VARIANT-ID'?: string;\n SUBTITLES?: string;\n 'SUPPLEMENTAL-CODECS'?: string;\n VIDEO?: string;\n 'VIDEO-RANGE'?: VideoRange;\n}\n\nexport const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null] as const;\nexport type HdcpLevel = (typeof HdcpLevels)[number];\n\nexport function isHdcpLevel(value: any): value is HdcpLevel {\n return HdcpLevels.indexOf(value) > -1;\n}\n\nexport const VideoRangeValues = ['SDR', 'PQ', 'HLG'] as const;\nexport type VideoRange = (typeof VideoRangeValues)[number];\n\nexport function isVideoRange(value: any): value is VideoRange {\n return !!value && VideoRangeValues.indexOf(value) > -1;\n}\n\nexport type VariableMap = Record<string, string>;\n\nexport const enum HlsSkip {\n No = '',\n Yes = 'YES',\n v2 = 'v2',\n}\n\nexport function getSkipValue(details: LevelDetails): HlsSkip {\n const { canSkipUntil, canSkipDateRanges, age } = details;\n // A Client SHOULD NOT request a Playlist Delta Update unless it already\n // has a version of the Playlist that is no older than one-half of the Skip Boundary.\n // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7\n const playlistRecentEnough = age < canSkipUntil / 2;\n if (canSkipUntil && playlistRecentEnough) {\n if (canSkipDateRanges) {\n return HlsSkip.v2;\n }\n return HlsSkip.Yes;\n }\n return HlsSkip.No;\n}\n\nexport class HlsUrlParameters {\n msn?: number;\n part?: number;\n skip?: HlsSkip;\n\n constructor(msn?: number, part?: number, skip?: HlsSkip) {\n this.msn = msn;\n this.part = part;\n this.skip = skip;\n }\n\n addDirectives(uri: string): string | never {\n const url: URL = new self.URL(uri);\n if (this.msn !== undefined) {\n url.searchParams.set('_HLS_msn', this.msn.toString());\n }\n if (this.part !== undefined) {\n url.searchParams.set('_HLS_part', this.part.toString());\n }\n if (this.skip) {\n url.searchParams.set('_HLS_skip', this.skip);\n }\n return url.href;\n }\n}\n\nexport class Level {\n public readonly _attrs: LevelAttributes[];\n public readonly audioCodec: string | undefined;\n public readonly bitrate: number;\n public readonly codecSet: string;\n public readonly url: string[];\n public readonly frameRate: number;\n public readonly height: number;\n public readonly id: number;\n public readonly name: string;\n public readonly videoCodec: string | undefined;\n public readonly width: number;\n public details?: LevelDetails;\n public fragmentError: number = 0;\n public loadError: number = 0;\n public loaded?: { bytes: number; duration: number };\n public realBitrate: number = 0;\n public supportedPromise?: Promise<MediaDecodingInfo>;\n public supportedResult?: MediaDecodingInfo;\n private _avgBitrate: number = 0;\n private _audioGroups?: (string | undefined)[];\n private _subtitleGroups?: (string | undefined)[];\n // Deprecated (retained for backwards compatibility)\n private readonly _urlId: number = 0;\n\n constructor(data: LevelParsed | MediaPlaylist) {\n this.url = [data.url];\n this._attrs = [data.attrs];\n this.bitrate = data.bitrate;\n if (data.details) {\n this.details = data.details;\n }\n this.id = data.id || 0;\n this.name = data.name;\n this.width = data.width || 0;\n this.height = data.height || 0;\n this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);\n this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');\n this.audioCodec = data.audioCodec;\n this.videoCodec = data.videoCodec;\n this.codecSet = [data.videoCodec, data.audioCodec]\n .filter((c) => !!c)\n .map((s: string) => s.substring(0, 4))\n .join(',');\n this.addGroupId('audio', data.attrs.AUDIO);\n this.addGroupId('text', data.attrs.SUBTITLES);\n }\n\n get maxBitrate(): number {\n return Math.max(this.realBitrate, this.bitrate);\n }\n\n get averageBitrate(): number {\n return this._avgBitrate || this.realBitrate || this.bitrate;\n }\n\n get attrs(): LevelAttributes {\n return this._attrs[0];\n }\n\n get codecs(): string {\n return this.attrs.CODECS || '';\n }\n\n get pathwayId(): string {\n return this.attrs['PATHWAY-ID'] || '.';\n }\n\n get videoRange(): VideoRange {\n return this.attrs['VIDEO-RANGE'] || 'SDR';\n }\n\n get score(): number {\n return this.attrs.optionalFloat('SCORE', 0);\n }\n\n get uri(): string {\n return this.url[0] || '';\n }\n\n hasAudioGroup(groupId: string | undefined): boolean {\n return hasGroup(this._audioGroups, groupId);\n }\n\n hasSubtitleGroup(groupId: string | undefined): boolean {\n return hasGroup(this._subtitleGroups, groupId);\n }\n\n get audioGroups(): (string | undefined)[] | undefined {\n return this._audioGroups;\n }\n\n get subtitleGroups(): (string | undefined)[] | undefined {\n return this._subtitleGroups;\n }\n\n addGroupId(type: string, groupId: string | undefined) {\n if (!groupId) {\n return;\n }\n if (type === 'audio') {\n let audioGroups = this._audioGroups;\n if (!audioGroups) {\n audioGroups = this._audioGroups = [];\n }\n if (audioGroups.indexOf(groupId) === -1) {\n audioGroups.push(groupId);\n }\n } else if (type === 'text') {\n let subtitleGroups = this._subtitleGroups;\n if (!subtitleGroups) {\n subtitleGroups = this._subtitleGroups = [];\n }\n if (subtitleGroups.indexOf(groupId) === -1) {\n subtitleGroups.push(groupId);\n }\n }\n }\n\n // Deprecated methods (retained for backwards compatibility)\n get urlId(): number {\n return 0;\n }\n\n set urlId(value: number) {}\n\n get audioGroupIds(): (string | undefined)[] | undefined {\n return this.audioGroups ? [this.audioGroupId] : undefined;\n }\n\n get textGroupIds(): (string | undefined)[] | undefined {\n return this.subtitleGroups ? [this.textGroupId] : undefined;\n }\n\n get audioGroupId(): string | undefined {\n return this.audioGroups?.[0];\n }\n\n get textGroupId(): string | undefined {\n return this.subtitleGroups?.[0];\n }\n\n addFallback() {}\n}\n\nfunction hasGroup(\n groups: (string | undefined)[] | undefined,\n groupId: string | undefined,\n): boolean {\n if (!groupId || !groups) {\n return false;\n }\n return groups.indexOf(groupId) !== -1;\n}\n","/**\n * Provides methods dealing with playlist sliding and drift\n */\n\nimport { logger } from './logger';\nimport { Fragment, Part } from '../loader/fragment';\nimport { LevelDetails } from '../loader/level-details';\nimport type { Level } from '../types/level';\nimport { DateRange } from '../loader/date-range';\n\ntype FragmentIntersection = (oldFrag: Fragment, newFrag: Fragment) => void;\ntype PartIntersection = (oldPart: Part, newPart: Part) => void;\n\nexport function updatePTS(\n fragments: Fragment[],\n fromIdx: number,\n toIdx: number,\n): void {\n const fragFrom = fragments[fromIdx];\n const fragTo = fragments[toIdx];\n updateFromToPTS(fragFrom, fragTo);\n}\n\nfunction updateFromToPTS(fragFrom: Fragment, fragTo: Fragment) {\n const fragToPTS = fragTo.startPTS as number;\n // if we know startPTS[toIdx]\n if (Number.isFinite(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n let duration: number = 0;\n let frag: Fragment;\n if (fragTo.sn > fragFrom.sn) {\n duration = fragToPTS - fragFrom.start;\n frag = fragFrom;\n } else {\n duration = fragFrom.start - fragToPTS;\n frag = fragTo;\n }\n if (frag.duration !== duration) {\n frag.duration = duration;\n }\n // we dont know startPTS[toIdx]\n } else if (fragTo.sn > fragFrom.sn) {\n const contiguous = fragFrom.cc === fragTo.cc;\n // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS\n if (contiguous && fragFrom.minEndPTS) {\n fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);\n } else {\n fragTo.start = fragFrom.start + fragFrom.duration;\n }\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n}\n\nexport function updateFragPTSDTS(\n details: LevelDetails | undefined,\n frag: Fragment,\n startPTS: number,\n endPTS: number,\n startDTS: number,\n endDTS: number,\n): number {\n const parsedMediaDuration = endPTS - startPTS;\n if (parsedMediaDuration <= 0) {\n logger.warn('Fragment should have a positive duration', frag);\n endPTS = startPTS + frag.duration;\n endDTS = startDTS + frag.duration;\n }\n let maxStartPTS = startPTS;\n let minEndPTS = endPTS;\n const fragStartPts = frag.startPTS as number;\n const fragEndPts = frag.endPTS as number;\n if (Number.isFinite(fragStartPts)) {\n // delta PTS between audio and video\n const deltaPTS = Math.abs(fragStartPts - startPTS);\n if (!Number.isFinite(frag.deltaPTS as number)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS as number);\n }\n\n maxStartPTS = Math.max(startPTS, fragStartPts);\n startPTS = Math.min(startPTS, fragStartPts);\n startDTS = Math.min(startDTS, frag.startDTS);\n\n minEndPTS = Math.min(endPTS, fragEndPts);\n endPTS = Math.max(endPTS, fragEndPts);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n if (frag.start !== 0) {\n frag.start = startPTS;\n }\n frag.duration = endPTS - frag.start;\n frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.startDTS = startDTS;\n frag.endPTS = endPTS;\n frag.minEndPTS = minEndPTS;\n frag.endDTS = endDTS;\n\n const sn = frag.sn as number; // 'initSegment'\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n let i;\n const fragIdx = sn - details.startSN;\n const fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updateFromToPTS(fragments[i], fragments[i - 1]);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updateFromToPTS(fragments[i], fragments[i + 1]);\n }\n if (details.fragmentHint) {\n updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);\n }\n\n details.PTSKnown = details.alignedSliding = true;\n return drift;\n}\n\nexport function mergeDetails(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n): void {\n // Track the last initSegment processed. Initialize it to the last one on the timeline.\n let currentInitSegment: Fragment | null = null;\n const oldFragments = oldDetails.fragments;\n for (let i = oldFragments.length - 1; i >= 0; i--) {\n const oldInit = oldFragments[i].initSegment;\n if (oldInit) {\n currentInitSegment = oldInit;\n break;\n }\n }\n\n if (oldDetails.fragmentHint) {\n // prevent PTS and duration from being adjusted on the next hint\n delete oldDetails.fragmentHint.endPTS;\n }\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n let ccOffset = 0;\n let PTSFrag;\n mapFragmentIntersection(\n oldDetails,\n newDetails,\n (oldFrag: Fragment, newFrag: Fragment) => {\n if (oldFrag.relurl) {\n // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.\n // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end\n // of the playlist.\n ccOffset = oldFrag.cc - newFrag.cc;\n }\n if (\n Number.isFinite(oldFrag.startPTS) &&\n Number.isFinite(oldFrag.endPTS)\n ) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS as number;\n newFrag.startDTS = oldFrag.startDTS;\n newFrag.maxStartPTS = oldFrag.maxStartPTS;\n\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.endDTS = oldFrag.endDTS;\n newFrag.minEndPTS = oldFrag.minEndPTS;\n newFrag.duration =\n (oldFrag.endPTS as number) - (oldFrag.startPTS as number);\n\n if (newFrag.duration) {\n PTSFrag = newFrag;\n }\n\n // PTS is known when any segment has startPTS and endPTS\n newDetails.PTSKnown = newDetails.alignedSliding = true;\n }\n newFrag.elementaryStreams = oldFrag.elementaryStreams;\n newFrag.loader = oldFrag.loader;\n newFrag.stats = oldFrag.stats;\n if (oldFrag.initSegment) {\n newFrag.initSegment = oldFrag.initSegment;\n currentInitSegment = oldFrag.initSegment;\n }\n },\n );\n\n if (currentInitSegment) {\n const fragmentsToCheck = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n fragmentsToCheck.forEach((frag) => {\n if (\n frag &&\n (!frag.initSegment ||\n frag.initSegment.relurl === currentInitSegment?.relurl)\n ) {\n frag.initSegment = currentInitSegment;\n }\n });\n }\n\n if (newDetails.skippedSegments) {\n newDetails.deltaUpdateFailed = newDetails.fragments.some((frag) => !frag);\n if (newDetails.deltaUpdateFailed) {\n logger.warn(\n '[level-helper] Previous playlist missing segments skipped in delta playlist',\n );\n for (let i = newDetails.skippedSegments; i--; ) {\n newDetails.fragments.shift();\n }\n newDetails.startSN = newDetails.fragments[0].sn as number;\n newDetails.startCC = newDetails.fragments[0].cc;\n } else if (newDetails.canSkipDateRanges) {\n newDetails.dateRanges = mergeDateRanges(\n oldDetails.dateRanges,\n newDetails.dateRanges,\n newDetails.recentlyRemovedDateranges,\n );\n }\n }\n\n const newFragments = newDetails.fragments;\n if (ccOffset) {\n logger.warn('discontinuity sliding from playlist, take drift into account');\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n if (newDetails.skippedSegments) {\n newDetails.startCC = newDetails.fragments[0].cc;\n }\n\n // Merge parts\n mapPartIntersection(\n oldDetails.partList,\n newDetails.partList,\n (oldPart: Part, newPart: Part) => {\n newPart.elementaryStreams = oldPart.elementaryStreams;\n newPart.stats = oldPart.stats;\n },\n );\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(\n newDetails,\n PTSFrag,\n PTSFrag.startPTS,\n PTSFrag.endPTS,\n PTSFrag.startDTS,\n PTSFrag.endDTS,\n );\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n\n if (newFragments.length) {\n newDetails.totalduration = newDetails.edge - newFragments[0].start;\n }\n\n newDetails.driftStartTime = oldDetails.driftStartTime;\n newDetails.driftStart = oldDetails.driftStart;\n const advancedDateTime = newDetails.advancedDateTime;\n if (newDetails.advanced && advancedDateTime) {\n const edge = newDetails.edge;\n if (!newDetails.driftStart) {\n newDetails.driftStartTime = advancedDateTime;\n newDetails.driftStart = edge;\n }\n newDetails.driftEndTime = advancedDateTime;\n newDetails.driftEnd = edge;\n } else {\n newDetails.driftEndTime = oldDetails.driftEndTime;\n newDetails.driftEnd = oldDetails.driftEnd;\n newDetails.advancedDateTime = oldDetails.advancedDateTime;\n }\n}\n\nfunction mergeDateRanges(\n oldDateRanges: Record<string, DateRange>,\n deltaDateRanges: Record<string, DateRange>,\n recentlyRemovedDateranges: string[] | undefined,\n): Record<string, DateRange> {\n const dateRanges = Object.assign({}, oldDateRanges);\n if (recentlyRemovedDateranges) {\n recentlyRemovedDateranges.forEach((id) => {\n delete dateRanges[id];\n });\n }\n Object.keys(deltaDateRanges).forEach((id) => {\n const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);\n if (dateRange.isValid) {\n dateRanges[id] = dateRange;\n } else {\n logger.warn(\n `Ignoring invalid Playlist Delta Update DATERANGE tag: \"${JSON.stringify(\n deltaDateRanges[id].attr,\n )}\"`,\n );\n }\n });\n return dateRanges;\n}\n\nexport function mapPartIntersection(\n oldParts: Part[] | null,\n newParts: Part[] | null,\n intersectionFn: PartIntersection,\n) {\n if (oldParts && newParts) {\n let delta = 0;\n for (let i = 0, len = oldParts.length; i <= len; i++) {\n const oldPart = oldParts[i];\n const newPart = newParts[i + delta];\n if (\n oldPart &&\n newPart &&\n oldPart.index === newPart.index &&\n oldPart.fragment.sn === newPart.fragment.sn\n ) {\n intersectionFn(oldPart, newPart);\n } else {\n delta--;\n }\n }\n }\n}\n\nexport function mapFragmentIntersection(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n intersectionFn: FragmentIntersection,\n): void {\n const skippedSegments = newDetails.skippedSegments;\n const start =\n Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;\n const end =\n (oldDetails.fragmentHint ? 1 : 0) +\n (skippedSegments\n ? newDetails.endSN\n : Math.min(oldDetails.endSN, newDetails.endSN)) -\n newDetails.startSN;\n const delta = newDetails.startSN - oldDetails.startSN;\n const newFrags = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n const oldFrags = oldDetails.fragmentHint\n ? oldDetails.fragments.concat(oldDetails.fragmentHint)\n : oldDetails.fragments;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldFrags[delta + i];\n let newFrag = newFrags[i];\n if (skippedSegments && !newFrag && i < skippedSegments) {\n // Fill in skipped segments in delta playlist\n newFrag = newDetails.fragments[i] = oldFrag;\n }\n if (oldFrag && newFrag) {\n intersectionFn(oldFrag, newFrag);\n }\n }\n}\n\nexport function adjustSliding(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n): void {\n const delta =\n newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;\n const oldFragments = oldDetails.fragments;\n if (delta < 0 || delta >= oldFragments.length) {\n return;\n }\n addSliding(newDetails, oldFragments[delta].start);\n}\n\nexport function addSliding(details: LevelDetails, start: number) {\n if (start) {\n const fragments = details.fragments;\n for (let i = details.skippedSegments; i < fragments.length; i++) {\n fragments[i].start += start;\n }\n if (details.fragmentHint) {\n details.fragmentHint.start += start;\n }\n }\n}\n\nexport function computeReloadInterval(\n newDetails: LevelDetails,\n distanceToLiveEdgeMs: number = Infinity,\n): number {\n let reloadInterval = 1000 * newDetails.targetduration;\n\n if (newDetails.updated) {\n // Use last segment duration when shorter than target duration and near live edge\n const fragments = newDetails.fragments;\n const liveEdgeMaxTargetDurations = 4;\n if (\n fragments.length &&\n reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs\n ) {\n const lastSegmentDuration =\n fragments[fragments.length - 1].duration * 1000;\n if (lastSegmentDuration < reloadInterval) {\n reloadInterval = lastSegmentDuration;\n }\n }\n } else {\n // estimate = 'miss half average';\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval /= 2;\n }\n\n return Math.round(reloadInterval);\n}\n\nexport function getFragmentWithSN(\n level: Level,\n sn: number,\n fragCurrent: Fragment | null,\n): Fragment | null {\n if (!level?.details) {\n return null;\n }\n const levelDetails = level.details;\n let fragment: Fragment | undefined =\n levelDetails.fragments[sn - levelDetails.startSN];\n if (fragment) {\n return fragment;\n }\n fragment = levelDetails.fragmentHint;\n if (fragment && fragment.sn === sn) {\n return fragment;\n }\n if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {\n return fragCurrent;\n }\n return null;\n}\n\nexport function getPartWith(\n level: Level,\n sn: number,\n partIndex: number,\n): Part | null {\n if (!level?.details) {\n return null;\n }\n return findPart(level.details?.partList, sn, partIndex);\n}\n\nexport function findPart(\n partList: Part[] | null | undefined,\n sn: number,\n partIndex: number,\n): Part | null {\n if (partList) {\n for (let i = partList.length; i--; ) {\n const part = partList[i];\n if (part.index === partIndex && part.fragment.sn === sn) {\n return part;\n }\n }\n }\n return null;\n}\n\nexport function reassignFragmentLevelIndexes(levels: Level[]) {\n levels.forEach((level, index) => {\n const { details } = level;\n if (details?.fragments) {\n details.fragments.forEach((fragment) => {\n fragment.level = index;\n });\n }\n });\n}\n","import { ErrorDetails } from '../errors';\nimport type { LoadPolicy, LoaderConfig, RetryConfig } from '../config';\nimport type { ErrorData } from '../types/events';\nimport type { LoaderResponse } from '../types/loader';\n\nexport function isTimeoutError(error: ErrorData): boolean {\n switch (error.details) {\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.MANIFEST_LOAD_TIMEOUT:\n return true;\n }\n return false;\n}\n\nexport function getRetryConfig(\n loadPolicy: LoadPolicy,\n error: ErrorData,\n): RetryConfig | null {\n const isTimeout = isTimeoutError(error);\n return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];\n}\n\nexport function getRetryDelay(\n retryConfig: RetryConfig,\n retryCount: number,\n): number {\n // exponential backoff capped to max retry delay\n const backoffFactor =\n retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);\n return Math.min(\n backoffFactor * retryConfig.retryDelayMs,\n retryConfig.maxRetryDelayMs,\n );\n}\n\nexport function getLoaderConfigWithoutReties(\n loderConfig: LoaderConfig,\n): LoaderConfig {\n return {\n ...loderConfig,\n ...{\n errorRetry: null,\n timeoutRetry: null,\n },\n };\n}\n\nexport function shouldRetry(\n retryConfig: RetryConfig | null | undefined,\n retryCount: number,\n isTimeout: boolean,\n loaderResponse?: LoaderResponse | undefined,\n): retryConfig is RetryConfig & boolean {\n if (!retryConfig) {\n return false;\n }\n const httpStatus = loaderResponse?.code;\n const retry =\n retryCount < retryConfig.maxNumRetry &&\n (retryForHttpStatus(httpStatus) || !!isTimeout);\n return retryConfig.shouldRetry\n ? retryConfig.shouldRetry(\n retryConfig,\n retryCount,\n isTimeout,\n loaderResponse,\n retry,\n )\n : retry;\n}\n\nexport function retryForHttpStatus(httpStatus: number | undefined) {\n // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)\n return (\n (httpStatus === 0 && navigator.onLine === false) ||\n (!!httpStatus && (httpStatus < 400 || httpStatus > 499))\n );\n}\n","type BinarySearchComparison<T> = (candidate: T) => -1 | 0 | 1;\n\nconst BinarySearch = {\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param list The array to search.\n * @param comparisonFn\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @returns the object if found, otherwise returns null\n */\n search: function <T>(\n list: T[],\n comparisonFn: BinarySearchComparison<T>,\n ): T | null {\n let minIndex: number = 0;\n let maxIndex: number = list.length - 1;\n let currentIndex: number | null = null;\n let currentElement: T | null = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = ((minIndex + maxIndex) / 2) | 0;\n currentElement = list[currentIndex];\n\n const comparisonResult = comparisonFn(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n },\n};\n\nexport default BinarySearch;\n","import BinarySearch from '../utils/binary-search';\nimport { Fragment } from '../loader/fragment';\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT, or null.\n * @param fragments - The array of candidate fragments\n * @param PDTValue - The PDT value which must be exceeded\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n */\nexport function findFragmentByPDT(\n fragments: Array<Fragment>,\n PDTValue: number | null,\n maxFragLookUpTolerance: number,\n): Fragment | null {\n if (\n PDTValue === null ||\n !Array.isArray(fragments) ||\n !fragments.length ||\n !Number.isFinite(PDTValue)\n ) {\n return null;\n }\n\n // if less than start\n const startPDT = fragments[0].programDateTime;\n if (PDTValue < (startPDT || 0)) {\n return null;\n }\n\n const endPDT = fragments[fragments.length - 1].endProgramDateTime;\n if (PDTValue >= (endPDT || 0)) {\n return null;\n }\n\n maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n for (let seg = 0; seg < fragments.length; ++seg) {\n const frag = fragments[seg];\n if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n return frag;\n }\n }\n\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param fragPrevious - The last frag successfully appended\n * @param fragments - The array of candidate fragments\n * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns a matching fragment or null\n */\nexport function findFragmentByPTS(\n fragPrevious: Fragment | null,\n fragments: Array<Fragment>,\n bufferEnd: number = 0,\n maxFragLookUpTolerance: number = 0,\n nextFragLookupTolerance: number = 0.005,\n): Fragment | null {\n let fragNext: Fragment | null = null;\n if (fragPrevious) {\n fragNext =\n fragments[\n (fragPrevious.sn as number) - (fragments[0].sn as number) + 1\n ] || null;\n // check for buffer-end rounding error\n const bufferEdgeError = fragPrevious.endDTS - bufferEnd;\n if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {\n bufferEnd += 0.0000015;\n }\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (\n fragNext &&\n (((!fragPrevious || fragPrevious.level === fragNext.level) &&\n fragmentWithinToleranceTest(\n bufferEnd,\n maxFragLookUpTolerance,\n fragNext,\n ) === 0) ||\n fragmentWithinFastStartSwitch(\n fragNext,\n fragPrevious,\n Math.min(nextFragLookupTolerance, maxFragLookUpTolerance),\n ))\n ) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(\n fragments,\n fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance),\n );\n if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\n}\n\nfunction fragmentWithinFastStartSwitch(\n fragNext: Fragment,\n fragPrevious: Fragment | null,\n nextFragLookupTolerance: number,\n): boolean {\n if (\n fragPrevious &&\n fragPrevious.start === 0 &&\n fragPrevious.level < fragNext.level &&\n (fragPrevious.endPTS || 0) > 0\n ) {\n const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {\n if (tag[0] === 'INF') {\n duration += parseFloat(tag[1]);\n }\n return duration;\n }, nextFragLookupTolerance);\n return fragNext.start <= firstDuration;\n }\n return false;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param candidate - The fragment to test\n * @param bufferEnd - The end of the current buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest(\n bufferEnd = 0,\n maxFragLookUpTolerance = 0,\n candidate: Fragment,\n) {\n // eagerly accept an accurate match (no tolerance)\n if (\n candidate.start <= bufferEnd &&\n candidate.start + candidate.duration > bufferEnd\n ) {\n return 0;\n }\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n const candidateLookupTolerance = Math.min(\n maxFragLookUpTolerance,\n candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0),\n );\n if (\n candidate.start + candidate.duration - candidateLookupTolerance <=\n bufferEnd\n ) {\n return 1;\n } else if (\n candidate.start - candidateLookupTolerance > bufferEnd &&\n candidate.start\n ) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/**\n * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n * This function tests the candidate's program date time values, as represented in Unix time\n * @param candidate - The fragment to test\n * @param pdtBufferEnd - The Unix time representing the end of the current buffered range\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns true if contiguous, false otherwise\n */\nexport function pdtWithinToleranceTest(\n pdtBufferEnd: number,\n maxFragLookUpTolerance: number,\n candidate: Fragment,\n): boolean {\n const candidateLookupTolerance =\n Math.min(\n maxFragLookUpTolerance,\n candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0),\n ) * 1000;\n\n // endProgramDateTime can be null, default to zero\n const endProgramDateTime = candidate.endProgramDateTime || 0;\n return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\n\nexport function findFragWithCC(\n fragments: Fragment[],\n cc: number,\n): Fragment | null {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < cc) {\n return 1;\n } else if (candidate.cc > cc) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n","import { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport {\n getRetryConfig,\n isTimeoutError,\n shouldRetry,\n} from '../utils/error-helper';\nimport { findFragmentByPTS } from './fragment-finders';\nimport { HdcpLevel, HdcpLevels } from '../types/level';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { RetryConfig } from '../config';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { ErrorData } from '../types/events';\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../loader/level-details';\n\nexport const enum NetworkErrorAction {\n DoNothing = 0,\n SendEndCallback = 1, // Reserved for future use\n SendAlternateToPenaltyBox = 2,\n RemoveAlternatePermanently = 3, // Reserved for future use\n InsertDiscontinuity = 4, // Reserved for future use\n RetryRequest = 5,\n}\n\nexport const enum ErrorActionFlags {\n None = 0,\n MoveAllAlternatesMatchingHost = 1,\n MoveAllAlternatesMatchingHDCP = 1 << 1,\n SwitchToSDR = 1 << 2, // Reserved for future use\n}\n\nexport type IErrorAction = {\n action: NetworkErrorAction;\n flags: ErrorActionFlags;\n retryCount?: number;\n retryConfig?: RetryConfig;\n hdcpLevel?: HdcpLevel;\n nextAutoLevel?: number;\n resolved?: boolean;\n};\n\ntype PenalizedRendition = {\n lastErrorPerfMs: number;\n errors: ErrorData[];\n details?: LevelDetails;\n};\n\ntype PenalizedRenditions = { [key: number]: PenalizedRendition };\n\nexport default class ErrorController implements NetworkComponentAPI {\n private readonly hls: Hls;\n private playlistError: number = 0;\n private penalizedRenditions: PenalizedRenditions = {};\n private log: (msg: any) => void;\n private warn: (msg: any) => void;\n private error: (msg: any) => void;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.log = logger.log.bind(logger, `[info]:`);\n this.warn = logger.warn.bind(logger, `[warning]:`);\n this.error = logger.error.bind(logger, `[error]:`);\n this.registerListeners();\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.ERROR, this.onErrorOut, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n destroy() {\n this.unregisterListeners();\n // @ts-ignore\n this.hls = null;\n this.penalizedRenditions = {};\n }\n\n startLoad(startPosition: number): void {}\n\n stopLoad(): void {\n this.playlistError = 0;\n }\n\n private getVariantLevelIndex(frag: Fragment | undefined): number {\n return frag?.type === PlaylistLevelType.MAIN\n ? frag.level\n : this.hls.loadLevel;\n }\n\n private onManifestLoading() {\n this.playlistError = 0;\n this.penalizedRenditions = {};\n }\n\n private onLevelUpdated() {\n this.playlistError = 0;\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n return;\n }\n const hls = this.hls;\n const context = data.context;\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n return;\n case ErrorDetails.FRAG_PARSING_ERROR:\n // ignore empty segment errors marked as gap\n if (data.frag?.gap) {\n data.errorAction = {\n action: NetworkErrorAction.DoNothing,\n flags: ErrorActionFlags.None,\n };\n return;\n }\n // falls through\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_DECRYPT_ERROR: {\n // Switch level if possible, otherwise allow retry count to reach max error retries\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;\n return;\n }\n case ErrorDetails.LEVEL_EMPTY_ERROR:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n {\n // Only retry when empty and live\n const levelIndex =\n data.parent === PlaylistLevelType.MAIN\n ? (data.level as number)\n : hls.loadLevel;\n if (\n data.details === ErrorDetails.LEVEL_EMPTY_ERROR &&\n !!data.context?.levelDetails?.live\n ) {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n levelIndex,\n );\n } else {\n // Escalate to fatal if not retrying or switching\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n }\n }\n return;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (typeof context?.level === 'number') {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n context.level,\n );\n }\n return;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.SUBTITLE_LOAD_ERROR:\n case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:\n if (context) {\n const level = hls.levels[hls.loadLevel];\n if (\n level &&\n ((context.type === PlaylistContextType.AUDIO_TRACK &&\n level.hasAudioGroup(context.groupId)) ||\n (context.type === PlaylistContextType.SUBTITLE_TRACK &&\n level.hasSubtitleGroup(context.groupId)))\n ) {\n // Perform Pathway switch or Redundant failover if possible for fastest recovery\n // otherwise allow playlist retry count to reach max error retries\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n hls.loadLevel,\n );\n data.errorAction.action =\n NetworkErrorAction.SendAlternateToPenaltyBox;\n data.errorAction.flags =\n ErrorActionFlags.MoveAllAlternatesMatchingHost;\n return;\n }\n }\n return;\n case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:\n {\n const level = hls.levels[hls.loadLevel];\n const restrictedHdcpLevel = level?.attrs['HDCP-LEVEL'];\n if (restrictedHdcpLevel) {\n data.errorAction = {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,\n hdcpLevel: restrictedHdcpLevel,\n };\n } else {\n this.keySystemError(data);\n }\n }\n return;\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.REMUX_ALLOC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n data.errorAction = this.getLevelSwitchAction(\n data,\n data.level ?? hls.loadLevel,\n );\n return;\n case ErrorDetails.INTERNAL_EXCEPTION:\n case ErrorDetails.BUFFER_APPENDING_ERROR:\n case ErrorDetails.BUFFER_FULL_ERROR:\n case ErrorDetails.LEVEL_SWITCH_ERROR:\n case ErrorDetails.BUFFER_STALLED_ERROR:\n case ErrorDetails.BUFFER_SEEK_OVER_HOLE:\n case ErrorDetails.BUFFER_NUDGE_ON_STALL:\n data.errorAction = {\n action: NetworkErrorAction.DoNothing,\n flags: ErrorActionFlags.None,\n };\n return;\n }\n\n if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {\n this.keySystemError(data);\n }\n }\n\n private keySystemError(data: ErrorData) {\n const levelIndex = this.getVariantLevelIndex(data.frag);\n // Do not retry level. Escalate to fatal if switching levels fails.\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n }\n\n private getPlaylistRetryOrSwitchAction(\n data: ErrorData,\n levelIndex: number | null | undefined,\n ): IErrorAction {\n const hls = this.hls;\n const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);\n const retryCount = this.playlistError++;\n const retry = shouldRetry(\n retryConfig,\n retryCount,\n isTimeoutError(data),\n data.response,\n );\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount,\n };\n }\n const errorAction = this.getLevelSwitchAction(data, levelIndex);\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = retryCount;\n }\n return errorAction;\n }\n\n private getFragRetryOrSwitchAction(data: ErrorData): IErrorAction {\n const hls = this.hls;\n // Share fragment error count accross media options (main, audio, subs)\n // This allows for level based rendition switching when media option assets fail\n const variantLevelIndex = this.getVariantLevelIndex(data.frag);\n const level = hls.levels[variantLevelIndex];\n const { fragLoadPolicy, keyLoadPolicy } = hls.config;\n const retryConfig = getRetryConfig(\n data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy,\n data,\n );\n const fragmentErrors = hls.levels.reduce(\n (acc, level) => acc + level.fragmentError,\n 0,\n );\n // Switch levels when out of retried or level index out of bounds\n if (level) {\n if (data.details !== ErrorDetails.FRAG_GAP) {\n level.fragmentError++;\n }\n const retry = shouldRetry(\n retryConfig,\n fragmentErrors,\n isTimeoutError(data),\n data.response,\n );\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount: fragmentErrors,\n };\n }\n }\n // Reach max retry count, or Missing level reference\n // Switch to valid index\n const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);\n // Add retry details to allow skipping of FRAG_PARSING_ERROR\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = fragmentErrors;\n }\n return errorAction;\n }\n\n private getLevelSwitchAction(\n data: ErrorData,\n levelIndex: number | null | undefined,\n ): IErrorAction {\n const hls = this.hls;\n if (levelIndex === null || levelIndex === undefined) {\n levelIndex = hls.loadLevel;\n }\n const level = this.hls.levels[levelIndex];\n if (level) {\n const errorDetails = data.details;\n level.loadError++;\n if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {\n level.fragmentError++;\n }\n // Search for next level to retry\n let nextLevel = -1;\n const { levels, loadLevel, minAutoLevel, maxAutoLevel } = hls;\n if (!hls.autoLevelEnabled) {\n hls.loadLevel = -1;\n }\n const fragErrorType = data.frag?.type;\n // Find alternate audio codec if available on audio codec error\n const isAudioCodecError =\n (fragErrorType === PlaylistLevelType.AUDIO &&\n errorDetails === ErrorDetails.FRAG_PARSING_ERROR) ||\n (data.sourceBufferName === 'audio' &&\n (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR ||\n errorDetails === ErrorDetails.BUFFER_APPEND_ERROR));\n const findAudioCodecAlternate =\n isAudioCodecError &&\n levels.some(({ audioCodec }) => level.audioCodec !== audioCodec);\n // Find alternate video codec if available on video codec error\n const isVideoCodecError =\n data.sourceBufferName === 'video' &&\n (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR ||\n errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);\n const findVideoCodecAlternate =\n isVideoCodecError &&\n levels.some(\n ({ codecSet, audioCodec }) =>\n level.codecSet !== codecSet && level.audioCodec === audioCodec,\n );\n const { type: playlistErrorType, groupId: playlistErrorGroupId } =\n data.context ?? {};\n for (let i = levels.length; i--; ) {\n const candidate = (i + loadLevel) % levels.length;\n if (\n candidate !== loadLevel &&\n candidate >= minAutoLevel &&\n candidate <= maxAutoLevel &&\n levels[candidate].loadError === 0\n ) {\n const levelCandidate = levels[candidate];\n // Skip level switch if GAP tag is found in next level at same position\n if (\n errorDetails === ErrorDetails.FRAG_GAP &&\n fragErrorType === PlaylistLevelType.MAIN &&\n data.frag\n ) {\n const levelDetails = levels[candidate].details;\n if (levelDetails) {\n const fragCandidate = findFragmentByPTS(\n data.frag,\n levelDetails.fragments,\n data.frag.start,\n );\n if (fragCandidate?.gap) {\n continue;\n }\n }\n } else if (\n (playlistErrorType === PlaylistContextType.AUDIO_TRACK &&\n levelCandidate.hasAudioGroup(playlistErrorGroupId)) ||\n (playlistErrorType === PlaylistContextType.SUBTITLE_TRACK &&\n levelCandidate.hasSubtitleGroup(playlistErrorGroupId))\n ) {\n // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over\n continue;\n } else if (\n (fragErrorType === PlaylistLevelType.AUDIO &&\n level.audioGroups?.some((groupId) =>\n levelCandidate.hasAudioGroup(groupId),\n )) ||\n (fragErrorType === PlaylistLevelType.SUBTITLE &&\n level.subtitleGroups?.some((groupId) =>\n levelCandidate.hasSubtitleGroup(groupId),\n )) ||\n (findAudioCodecAlternate &&\n level.audioCodec === levelCandidate.audioCodec) ||\n (!findAudioCodecAlternate &&\n level.audioCodec !== levelCandidate.audioCodec) ||\n (findVideoCodecAlternate &&\n level.codecSet === levelCandidate.codecSet)\n ) {\n // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over\n continue;\n }\n nextLevel = candidate;\n break;\n }\n }\n if (nextLevel > -1 && hls.loadLevel !== nextLevel) {\n data.levelRetry = true;\n this.playlistError = 0;\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.None,\n nextAutoLevel: nextLevel,\n };\n }\n }\n // No levels to switch / Manual level selection / Level not found\n // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHost,\n };\n }\n\n public onErrorOut(event: Events.ERROR, data: ErrorData) {\n switch (data.errorAction?.action) {\n case NetworkErrorAction.DoNothing:\n break;\n case NetworkErrorAction.SendAlternateToPenaltyBox:\n this.sendAlternateToPenaltyBox(data);\n if (\n !data.errorAction.resolved &&\n data.details !== ErrorDetails.FRAG_GAP\n ) {\n data.fatal = true;\n } else if (/MediaSource readyState: ended/.test(data.error.message)) {\n this.warn(\n `MediaSource ended after \"${data.sourceBufferName}\" sourceBuffer append error. Attempting to recover from media error.`,\n );\n this.hls.recoverMediaError();\n }\n break;\n case NetworkErrorAction.RetryRequest:\n // handled by stream and playlist/level controllers\n break;\n }\n\n if (data.fatal) {\n this.hls.stopLoad();\n return;\n }\n }\n\n private sendAlternateToPenaltyBox(data: ErrorData) {\n const hls = this.hls;\n const errorAction = data.errorAction;\n if (!errorAction) {\n return;\n }\n const { flags, hdcpLevel, nextAutoLevel } = errorAction;\n\n switch (flags) {\n case ErrorActionFlags.None:\n this.switchLevel(data, nextAutoLevel);\n break;\n case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:\n if (hdcpLevel) {\n hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];\n errorAction.resolved = true;\n }\n this.warn(\n `Restricting playback to HDCP-LEVEL of \"${hls.maxHdcpLevel}\" or lower`,\n );\n break;\n }\n // If not resolved by previous actions try to switch to next level\n if (!errorAction.resolved) {\n this.switchLevel(data, nextAutoLevel);\n }\n }\n\n private switchLevel(data: ErrorData, levelIndex: number | undefined) {\n if (levelIndex !== undefined && data.errorAction) {\n this.warn(`switching to level ${levelIndex} after ${data.details}`);\n this.hls.nextAutoLevel = levelIndex;\n data.errorAction.resolved = true;\n // Stream controller is responsible for this but won't switch on false start\n this.hls.nextLoadLevel = this.hls.nextAutoLevel;\n }\n }\n}\n","import type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport { getSkipValue, HlsSkip, HlsUrlParameters, Level } from '../types/level';\nimport { computeReloadInterval, mergeDetails } from '../utils/level-helper';\nimport { ErrorData } from '../types/events';\nimport { getRetryDelay, isTimeoutError } from '../utils/error-helper';\nimport { NetworkErrorAction } from './error-controller';\nimport { logger } from '../utils/logger';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport type {\n AudioTrackLoadedData,\n LevelLoadedData,\n TrackLoadedData,\n} from '../types/events';\n\nexport default class BasePlaylistController implements NetworkComponentAPI {\n protected hls: Hls;\n protected timer: number = -1;\n protected requestScheduled: number = -1;\n protected canLoad: boolean = false;\n protected log: (msg: any) => void;\n protected warn: (msg: any) => void;\n\n constructor(hls: Hls, logPrefix: string) {\n this.log = logger.log.bind(logger, `${logPrefix}:`);\n this.warn = logger.warn.bind(logger, `${logPrefix}:`);\n this.hls = hls;\n }\n\n public destroy(): void {\n this.clearTimer();\n // @ts-ignore\n this.hls = this.log = this.warn = null;\n }\n\n protected clearTimer(): void {\n if (this.timer !== -1) {\n self.clearTimeout(this.timer);\n this.timer = -1;\n }\n }\n\n public startLoad(): void {\n this.canLoad = true;\n this.requestScheduled = -1;\n this.loadPlaylist();\n }\n\n public stopLoad(): void {\n this.canLoad = false;\n this.clearTimer();\n }\n\n protected switchParams(\n playlistUri: string,\n previous: LevelDetails | undefined,\n current: LevelDetails | undefined,\n ): HlsUrlParameters | undefined {\n const renditionReports = previous?.renditionReports;\n if (renditionReports) {\n let foundIndex = -1;\n for (let i = 0; i < renditionReports.length; i++) {\n const attr = renditionReports[i];\n let uri: string;\n try {\n uri = new self.URL(attr.URI, previous.url).href;\n } catch (error) {\n logger.warn(\n `Could not construct new URL for Rendition Report: ${error}`,\n );\n uri = attr.URI || '';\n }\n // Use exact match. Otherwise, the last partial match, if any, will be used\n // (Playlist URI includes a query string that the Rendition Report does not)\n if (uri === playlistUri) {\n foundIndex = i;\n break;\n } else if (uri === playlistUri.substring(0, uri.length)) {\n foundIndex = i;\n }\n }\n if (foundIndex !== -1) {\n const attr = renditionReports[foundIndex];\n const msn = parseInt(attr['LAST-MSN']) || previous?.lastPartSn;\n let part = parseInt(attr['LAST-PART']) || previous?.lastPartIndex;\n if (this.hls.config.lowLatencyMode) {\n const currentGoal = Math.min(\n previous.age - previous.partTarget,\n previous.targetduration,\n );\n if (part >= 0 && currentGoal > previous.partTarget) {\n part += 1;\n }\n }\n const skip = current && getSkipValue(current);\n return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);\n }\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n if (this.requestScheduled === -1) {\n this.requestScheduled = self.performance.now();\n }\n // Loading is handled by the subclasses\n }\n\n protected shouldLoadPlaylist(\n playlist: Level | MediaPlaylist | null | undefined,\n ): boolean {\n return (\n this.canLoad &&\n !!playlist &&\n !!playlist.url &&\n (!playlist.details || playlist.details.live)\n );\n }\n\n protected shouldReloadPlaylist(\n playlist: Level | MediaPlaylist | null | undefined,\n ): boolean {\n return (\n this.timer === -1 &&\n this.requestScheduled === -1 &&\n this.shouldLoadPlaylist(playlist)\n );\n }\n\n protected playlistLoaded(\n index: number,\n data: LevelLoadedData | AudioTrackLoadedData | TrackLoadedData,\n previousDetails?: LevelDetails,\n ) {\n const { details, stats } = data;\n\n // Set last updated date-time\n const now = self.performance.now();\n const elapsed = stats.loading.first\n ? Math.max(0, now - stats.loading.first)\n : 0;\n details.advancedDateTime = Date.now() - elapsed;\n\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live || previousDetails?.live) {\n details.reloaded(previousDetails);\n if (previousDetails) {\n this.log(\n `live playlist ${index} ${\n details.advanced\n ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex\n : details.updated\n ? 'UPDATED'\n : 'MISSED'\n }`,\n );\n }\n // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments\n if (previousDetails && details.fragments.length > 0) {\n mergeDetails(previousDetails, details);\n }\n if (!this.canLoad || !details.live) {\n return;\n }\n let deliveryDirectives: HlsUrlParameters | undefined;\n let msn: number | undefined = undefined;\n let part: number | undefined = undefined;\n if (details.canBlockReload && details.endSN && details.advanced) {\n // Load level with LL-HLS delivery directives\n const lowLatencyMode = this.hls.config.lowLatencyMode;\n const lastPartSn = details.lastPartSn;\n const endSn = details.endSN;\n const lastPartIndex = details.lastPartIndex;\n const hasParts = lastPartIndex !== -1;\n const lastPart = lastPartSn === endSn;\n // When low latency mode is disabled, we'll skip part requests once the last part index is found\n const nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;\n if (hasParts) {\n msn = lastPart ? endSn + 1 : lastPartSn;\n part = lastPart ? nextSnStartIndex : lastPartIndex + 1;\n } else {\n msn = endSn + 1;\n }\n // Low-Latency CDN Tune-in: \"age\" header and time since load indicates we're behind by more than one part\n // Update directives to obtain the Playlist that has the estimated additional duration of media\n const lastAdvanced = details.age;\n const cdnAge = lastAdvanced + details.ageHeader;\n let currentGoal = Math.min(\n cdnAge - details.partTarget,\n details.targetduration * 1.5,\n );\n if (currentGoal > 0) {\n if (previousDetails && currentGoal > previousDetails.tuneInGoal) {\n // If we attempted to get the next or latest playlist update, but currentGoal increased,\n // then we either can't catchup, or the \"age\" header cannot be trusted.\n this.warn(\n `CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`,\n );\n currentGoal = 0;\n } else {\n const segments = Math.floor(currentGoal / details.targetduration);\n msn += segments;\n if (part !== undefined) {\n const parts = Math.round(\n (currentGoal % details.targetduration) / details.partTarget,\n );\n part += parts;\n }\n this.log(\n `CDN Tune-in age: ${\n details.ageHeader\n }s last advanced ${lastAdvanced.toFixed(\n 2,\n )}s goal: ${currentGoal} skip sn ${segments} to part ${part}`,\n );\n }\n details.tuneInGoal = currentGoal;\n }\n deliveryDirectives = this.getDeliveryDirectives(\n details,\n data.deliveryDirectives,\n msn,\n part,\n );\n if (lowLatencyMode || !lastPart) {\n this.loadPlaylist(deliveryDirectives);\n return;\n }\n } else if (details.canBlockReload || details.canSkipUntil) {\n deliveryDirectives = this.getDeliveryDirectives(\n details,\n data.deliveryDirectives,\n msn,\n part,\n );\n }\n const bufferInfo = this.hls.mainForwardBufferInfo;\n const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;\n const distanceToLiveEdgeMs = (details.edge - position) * 1000;\n const reloadInterval = computeReloadInterval(\n details,\n distanceToLiveEdgeMs,\n );\n if (details.updated && now > this.requestScheduled + reloadInterval) {\n this.requestScheduled = stats.loading.start;\n }\n\n if (msn !== undefined && details.canBlockReload) {\n this.requestScheduled =\n stats.loading.first +\n reloadInterval -\n (details.partTarget * 1000 || 1000);\n } else if (\n this.requestScheduled === -1 ||\n this.requestScheduled + reloadInterval < now\n ) {\n this.requestScheduled = now;\n } else if (this.requestScheduled - now <= 0) {\n this.requestScheduled += reloadInterval;\n }\n let estimatedTimeUntilUpdate = this.requestScheduled - now;\n estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);\n this.log(\n `reload live playlist ${index} in ${Math.round(\n estimatedTimeUntilUpdate,\n )} ms`,\n );\n // this.log(\n // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}\n // reload in ${estimatedTimeUntilUpdate / 1000}\n // round trip ${(stats.loading.end - stats.loading.start) / 1000}\n // diff ${\n // (reloadInterval -\n // (estimatedTimeUntilUpdate +\n // stats.loading.end -\n // stats.loading.start)) /\n // 1000\n // }\n // reload interval ${reloadInterval / 1000}\n // target duration ${details.targetduration}\n // distance to edge ${distanceToLiveEdgeMs / 1000}`\n // );\n\n this.timer = self.setTimeout(\n () => this.loadPlaylist(deliveryDirectives),\n estimatedTimeUntilUpdate,\n );\n } else {\n this.clearTimer();\n }\n }\n\n private getDeliveryDirectives(\n details: LevelDetails,\n previousDeliveryDirectives: HlsUrlParameters | null,\n msn?: number,\n part?: number,\n ): HlsUrlParameters {\n let skip = getSkipValue(details);\n if (previousDeliveryDirectives?.skip && details.deltaUpdateFailed) {\n msn = previousDeliveryDirectives.msn;\n part = previousDeliveryDirectives.part;\n skip = HlsSkip.No;\n }\n return new HlsUrlParameters(msn, part, skip);\n }\n\n protected checkRetry(errorEvent: ErrorData): boolean {\n const errorDetails = errorEvent.details;\n const isTimeout = isTimeoutError(errorEvent);\n const errorAction = errorEvent.errorAction;\n const { action, retryCount = 0, retryConfig } = errorAction || {};\n const retry =\n !!errorAction &&\n !!retryConfig &&\n (action === NetworkErrorAction.RetryRequest ||\n (!errorAction.resolved &&\n action === NetworkErrorAction.SendAlternateToPenaltyBox));\n if (retry) {\n this.requestScheduled = -1;\n if (retryCount >= retryConfig.maxNumRetry) {\n return false;\n }\n if (isTimeout && errorEvent.context?.deliveryDirectives) {\n // The LL-HLS request already timed out so retry immediately\n this.warn(\n `Retrying playlist loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } after \"${errorDetails}\" without delivery-directives`,\n );\n this.loadPlaylist();\n } else {\n const delay = getRetryDelay(retryConfig, retryCount);\n // Schedule level/track reload\n this.timer = self.setTimeout(() => this.loadPlaylist(), delay);\n this.warn(\n `Retrying playlist loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } after \"${errorDetails}\" in ${delay}ms`,\n );\n }\n // `levelRetry = true` used to inform other controllers that a retry is happening\n errorEvent.levelRetry = true;\n errorAction.resolved = true;\n }\n return retry;\n }\n}\n","/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n public readonly halfLife: number;\n private alpha_: number;\n private estimate_: number;\n private totalWeight_: number;\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor(halfLife: number, estimate: number = 0, weight: number = 0) {\n this.halfLife = halfLife;\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = estimate;\n this.totalWeight_ = weight;\n }\n\n sample(weight: number, value: number) {\n const adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight(): number {\n return this.totalWeight_;\n }\n\n getEstimate(): number {\n if (this.alpha_) {\n const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n if (zeroFactor) {\n return this.estimate_ / zeroFactor;\n }\n }\n return this.estimate_;\n }\n}\n\nexport default EWMA;\n","/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\nclass EwmaBandWidthEstimator {\n private defaultEstimate_: number;\n private minWeight_: number;\n private minDelayMs_: number;\n private slow_: EWMA;\n private fast_: EWMA;\n private defaultTTFB_: number;\n private ttfb_: EWMA;\n\n constructor(\n slow: number,\n fast: number,\n defaultEstimate: number,\n defaultTTFB: number = 100,\n ) {\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n this.defaultTTFB_ = defaultTTFB;\n this.ttfb_ = new EWMA(slow);\n }\n\n update(slow: number, fast: number) {\n const { slow_, fast_, ttfb_ } = this;\n if (slow_.halfLife !== slow) {\n this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());\n }\n if (fast_.halfLife !== fast) {\n this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());\n }\n if (ttfb_.halfLife !== slow) {\n this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());\n }\n }\n\n sample(durationMs: number, numBytes: number) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n const numBits = 8 * numBytes;\n // weight is duration in seconds\n const durationS = durationMs / 1000;\n // value is bandwidth in bits/s\n const bandwidthInBps = numBits / durationS;\n this.fast_.sample(durationS, bandwidthInBps);\n this.slow_.sample(durationS, bandwidthInBps);\n }\n\n sampleTTFB(ttfb: number) {\n // weight is frequency curve applied to TTFB in seconds\n // (longer times have less weight with expected input under 1 second)\n const seconds = ttfb / 1000;\n const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);\n this.ttfb_.sample(weight, Math.max(ttfb, 5));\n }\n\n canEstimate(): boolean {\n return this.fast_.getTotalWeight() >= this.minWeight_;\n }\n\n getEstimate(): number {\n if (this.canEstimate()) {\n // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n getEstimateTTFB(): number {\n if (this.ttfb_.getTotalWeight() >= this.minWeight_) {\n return this.ttfb_.getEstimate();\n } else {\n return this.defaultTTFB_;\n }\n }\n\n destroy() {}\n}\nexport default EwmaBandWidthEstimator;\n","import { type VideoRange, VideoRangeValues } from '../types/level';\nimport type { VideoSelectionOption } from '../types/media-playlist';\n\n/**\n * @returns Whether we can detect and validate HDR capability within the window context\n */\nexport function isHdrSupported() {\n if (typeof matchMedia === 'function') {\n const mediaQueryList = matchMedia('(dynamic-range: high)');\n const badQuery = matchMedia('bad query');\n if (mediaQueryList.media !== badQuery.media) {\n return mediaQueryList.matches === true;\n }\n }\n return false;\n}\n\n/**\n * Sanitizes inputs to return the active video selection options for HDR/SDR.\n * When both inputs are null:\n *\n * `{ preferHDR: false, allowedVideoRanges: [] }`\n *\n * When `currentVideoRange` non-null, maintain the active range:\n *\n * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`\n *\n * When VideoSelectionOption non-null:\n *\n * - Allow all video ranges if `allowedVideoRanges` unspecified.\n * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.\n * - Else check window for HDR support and set `preferHDR` to the result.\n *\n * @param currentVideoRange\n * @param videoPreference\n */\nexport function getVideoSelectionOptions(\n currentVideoRange: VideoRange | undefined,\n videoPreference: VideoSelectionOption | undefined,\n) {\n let preferHDR = false;\n let allowedVideoRanges: Array<VideoRange> = [];\n\n if (currentVideoRange) {\n preferHDR = currentVideoRange !== 'SDR';\n allowedVideoRanges = [currentVideoRange];\n }\n\n if (videoPreference) {\n allowedVideoRanges =\n videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);\n preferHDR =\n videoPreference.preferHDR !== undefined\n ? videoPreference.preferHDR\n : isHdrSupported();\n\n if (preferHDR) {\n allowedVideoRanges = allowedVideoRanges.filter(\n (range: VideoRange) => range !== 'SDR',\n );\n } else {\n allowedVideoRanges = ['SDR'];\n }\n }\n\n return {\n preferHDR,\n allowedVideoRanges,\n };\n}\n","import { codecsSetSelectionPreferenceValue } from './codecs';\nimport { getVideoSelectionOptions } from './hdr';\nimport { logger } from './logger';\nimport type { Level, VideoRange } from '../types/level';\nimport type {\n AudioSelectionOption,\n MediaPlaylist,\n SubtitleSelectionOption,\n VideoSelectionOption,\n} from '../types/media-playlist';\n\nexport type CodecSetTier = {\n minBitrate: number;\n minHeight: number;\n minFramerate: number;\n maxScore: number;\n videoRanges: Record<string, number>;\n channels: Record<string, number>;\n hasDefaultAudio: boolean;\n fragmentError: number;\n};\n\ntype AudioTrackGroup = {\n tracks: MediaPlaylist[];\n channels: Record<string, number>;\n hasDefault: boolean;\n hasAutoSelect: boolean;\n};\ntype StartParameters = {\n codecSet: string | undefined;\n videoRanges: Array<VideoRange>;\n preferHDR: boolean;\n minFramerate: number;\n minBitrate: number;\n};\n\nexport function getStartCodecTier(\n codecTiers: Record<string, CodecSetTier>,\n currentVideoRange: VideoRange | undefined,\n currentBw: number,\n audioPreference: AudioSelectionOption | undefined,\n videoPreference: VideoSelectionOption | undefined,\n): StartParameters {\n const codecSets = Object.keys(codecTiers);\n const channelsPreference = audioPreference?.channels;\n const audioCodecPreference = audioPreference?.audioCodec;\n const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;\n // Use first level set to determine stereo, and minimum resolution and framerate\n let hasStereo = true;\n let hasCurrentVideoRange = false;\n let minHeight = Infinity;\n let minFramerate = Infinity;\n let minBitrate = Infinity;\n let selectedScore = 0;\n let videoRanges: Array<VideoRange> = [];\n\n const { preferHDR, allowedVideoRanges } = getVideoSelectionOptions(\n currentVideoRange,\n videoPreference,\n );\n\n for (let i = codecSets.length; i--; ) {\n const tier = codecTiers[codecSets[i]];\n hasStereo = tier.channels[2] > 0;\n minHeight = Math.min(minHeight, tier.minHeight);\n minFramerate = Math.min(minFramerate, tier.minFramerate);\n minBitrate = Math.min(minBitrate, tier.minBitrate);\n const matchingVideoRanges = allowedVideoRanges.filter(\n (range) => tier.videoRanges[range] > 0,\n );\n if (matchingVideoRanges.length > 0) {\n hasCurrentVideoRange = true;\n videoRanges = matchingVideoRanges;\n }\n }\n minHeight = Number.isFinite(minHeight) ? minHeight : 0;\n minFramerate = Number.isFinite(minFramerate) ? minFramerate : 0;\n const maxHeight = Math.max(1080, minHeight);\n const maxFramerate = Math.max(30, minFramerate);\n minBitrate = Number.isFinite(minBitrate) ? minBitrate : currentBw;\n currentBw = Math.max(minBitrate, currentBw);\n // If there are no variants with matching preference, set currentVideoRange to undefined\n if (!hasCurrentVideoRange) {\n currentVideoRange = undefined;\n videoRanges = [];\n }\n const codecSet = codecSets.reduce(\n (selected: string | undefined, candidate: string) => {\n // Remove candiates which do not meet bitrate, default audio, stereo or channels preference, 1080p or lower, 30fps or lower, or SDR/HDR selection if present\n const candidateTier = codecTiers[candidate];\n if (candidate === selected) {\n return selected;\n }\n if (candidateTier.minBitrate > currentBw) {\n logStartCodecCandidateIgnored(\n candidate,\n `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`,\n );\n return selected;\n }\n if (!candidateTier.hasDefaultAudio) {\n logStartCodecCandidateIgnored(\n candidate,\n `no renditions with default or auto-select sound found`,\n );\n return selected;\n }\n if (\n audioCodecPreference &&\n candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0\n ) {\n logStartCodecCandidateIgnored(\n candidate,\n `audio codec preference \"${audioCodecPreference}\" not found`,\n );\n return selected;\n }\n if (channelsPreference && !preferStereo) {\n if (!candidateTier.channels[channelsPreference]) {\n logStartCodecCandidateIgnored(\n candidate,\n `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(\n candidateTier.channels,\n )})`,\n );\n return selected;\n }\n } else if (\n (!audioCodecPreference || preferStereo) &&\n hasStereo &&\n candidateTier.channels['2'] === 0\n ) {\n logStartCodecCandidateIgnored(\n candidate,\n `no renditions with stereo sound found`,\n );\n return selected;\n }\n if (candidateTier.minHeight > maxHeight) {\n logStartCodecCandidateIgnored(\n candidate,\n `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`,\n );\n return selected;\n }\n if (candidateTier.minFramerate > maxFramerate) {\n logStartCodecCandidateIgnored(\n candidate,\n `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`,\n );\n return selected;\n }\n if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) {\n logStartCodecCandidateIgnored(\n candidate,\n `no variants with VIDEO-RANGE of ${JSON.stringify(\n videoRanges,\n )} found`,\n );\n return selected;\n }\n if (candidateTier.maxScore < selectedScore) {\n logStartCodecCandidateIgnored(\n candidate,\n `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`,\n );\n return selected;\n }\n // Remove candiates with less preferred codecs or more errors\n if (\n selected &&\n (codecsSetSelectionPreferenceValue(candidate) >=\n codecsSetSelectionPreferenceValue(selected) ||\n candidateTier.fragmentError > codecTiers[selected].fragmentError)\n ) {\n return selected;\n }\n selectedScore = candidateTier.maxScore;\n return candidate;\n },\n undefined,\n );\n return {\n codecSet,\n videoRanges,\n preferHDR,\n minFramerate,\n minBitrate,\n };\n}\n\nfunction logStartCodecCandidateIgnored(codeSet: string, reason: string) {\n logger.log(\n `[abr] start candidates with \"${codeSet}\" ignored because ${reason}`,\n );\n}\n\nexport type AudioTracksByGroup = {\n hasDefaultAudio: boolean;\n hasAutoSelectAudio: boolean;\n groups: Record<string, AudioTrackGroup>;\n};\n\nexport function getAudioTracksByGroup(allAudioTracks: MediaPlaylist[]) {\n return allAudioTracks.reduce(\n (audioTracksByGroup: AudioTracksByGroup, track) => {\n let trackGroup = audioTracksByGroup.groups[track.groupId];\n if (!trackGroup) {\n trackGroup = audioTracksByGroup.groups[track.groupId] = {\n tracks: [],\n channels: { 2: 0 },\n hasDefault: false,\n hasAutoSelect: false,\n };\n }\n trackGroup.tracks.push(track);\n const channelsKey = track.channels || '2';\n trackGroup.channels[channelsKey] =\n (trackGroup.channels[channelsKey] || 0) + 1;\n trackGroup.hasDefault = trackGroup.hasDefault || track.default;\n trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;\n if (trackGroup.hasDefault) {\n audioTracksByGroup.hasDefaultAudio = true;\n }\n if (trackGroup.hasAutoSelect) {\n audioTracksByGroup.hasAutoSelectAudio = true;\n }\n return audioTracksByGroup;\n },\n {\n hasDefaultAudio: false,\n hasAutoSelectAudio: false,\n groups: {},\n },\n );\n}\n\nexport function getCodecTiers(\n levels: Level[],\n audioTracksByGroup: AudioTracksByGroup,\n minAutoLevel: number,\n maxAutoLevel: number,\n): Record<string, CodecSetTier> {\n return levels\n .slice(minAutoLevel, maxAutoLevel + 1)\n .reduce((tiers: Record<string, CodecSetTier>, level) => {\n if (!level.codecSet) {\n return tiers;\n }\n const audioGroups = level.audioGroups;\n let tier = tiers[level.codecSet];\n if (!tier) {\n tiers[level.codecSet] = tier = {\n minBitrate: Infinity,\n minHeight: Infinity,\n minFramerate: Infinity,\n maxScore: 0,\n videoRanges: { SDR: 0 },\n channels: { '2': 0 },\n hasDefaultAudio: !audioGroups,\n fragmentError: 0,\n };\n }\n tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);\n const lesserWidthOrHeight = Math.min(level.height, level.width);\n tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);\n tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);\n tier.maxScore = Math.max(tier.maxScore, level.score);\n tier.fragmentError += level.fragmentError;\n tier.videoRanges[level.videoRange] =\n (tier.videoRanges[level.videoRange] || 0) + 1;\n if (__USE_ALT_AUDIO__ && audioGroups) {\n audioGroups.forEach((audioGroupId) => {\n if (!audioGroupId) {\n return;\n }\n const audioGroup = audioTracksByGroup.groups[audioGroupId];\n if (!audioGroup) {\n return;\n }\n // Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants\n tier.hasDefaultAudio =\n tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio\n ? audioGroup.hasDefault\n : audioGroup.hasAutoSelect ||\n (!audioTracksByGroup.hasDefaultAudio &&\n !audioTracksByGroup.hasAutoSelectAudio);\n Object.keys(audioGroup.channels).forEach((channels) => {\n tier.channels[channels] =\n (tier.channels[channels] || 0) + audioGroup.channels[channels];\n });\n });\n }\n return tiers;\n }, {});\n}\n\nexport function findMatchingOption(\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n tracks: MediaPlaylist[],\n matchPredicate?: (\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n track: MediaPlaylist,\n ) => boolean,\n): number {\n if ('attrs' in option) {\n const index = tracks.indexOf(option);\n if (index !== -1) {\n return index;\n }\n }\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (matchesOption(option, track, matchPredicate)) {\n return i;\n }\n }\n return -1;\n}\n\nexport function matchesOption(\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n track: MediaPlaylist,\n matchPredicate?: (\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n track: MediaPlaylist,\n ) => boolean,\n): boolean {\n const {\n groupId,\n name,\n lang,\n assocLang,\n characteristics,\n default: isDefault,\n } = option;\n const forced = (option as SubtitleSelectionOption).forced;\n return (\n (groupId === undefined || track.groupId === groupId) &&\n (name === undefined || track.name === name) &&\n (lang === undefined || track.lang === lang) &&\n (lang === undefined || track.assocLang === assocLang) &&\n (isDefault === undefined || track.default === isDefault) &&\n (forced === undefined || track.forced === forced) &&\n (characteristics === undefined ||\n characteristicsMatch(characteristics, track.characteristics)) &&\n (matchPredicate === undefined || matchPredicate(option, track))\n );\n}\n\nfunction characteristicsMatch(\n characteristicsA: string,\n characteristicsB: string = '',\n): boolean {\n const arrA = characteristicsA.split(',');\n const arrB = characteristicsB.split(',');\n // Expects each item to be unique:\n return (\n arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1)\n );\n}\n\nexport function audioMatchPredicate(\n option: MediaPlaylist | AudioSelectionOption,\n track: MediaPlaylist,\n) {\n const { audioCodec, channels } = option;\n return (\n (audioCodec === undefined ||\n (track.audioCodec || '').substring(0, 4) ===\n audioCodec.substring(0, 4)) &&\n (channels === undefined || channels === (track.channels || '2'))\n );\n}\n\nexport function findClosestLevelWithAudioGroup(\n option: MediaPlaylist | AudioSelectionOption,\n levels: Level[],\n allAudioTracks: MediaPlaylist[],\n searchIndex: number,\n matchPredicate: (\n option: MediaPlaylist | AudioSelectionOption,\n track: MediaPlaylist,\n ) => boolean,\n): number {\n const currentLevel = levels[searchIndex];\n // Are there variants with same URI as current level?\n // If so, find a match that does not require any level URI change\n const variants = levels.reduce(\n (variantMap: { [uri: string]: number[] }, level, index) => {\n const uri = level.uri;\n const renditions = variantMap[uri] || (variantMap[uri] = []);\n renditions.push(index);\n return variantMap;\n },\n {},\n );\n const renditions = variants[currentLevel.uri];\n if (renditions.length > 1) {\n searchIndex = Math.max.apply(Math, renditions);\n }\n // Find best match\n const currentVideoRange = currentLevel.videoRange;\n const currentFrameRate = currentLevel.frameRate;\n const currentVideoCodec = currentLevel.codecSet.substring(0, 4);\n const matchingVideo = searchDownAndUpList(\n levels,\n searchIndex,\n (level: Level) => {\n if (\n level.videoRange !== currentVideoRange ||\n level.frameRate !== currentFrameRate ||\n level.codecSet.substring(0, 4) !== currentVideoCodec\n ) {\n return false;\n }\n const audioGroups = level.audioGroups;\n const tracks = allAudioTracks.filter(\n (track): boolean =>\n !audioGroups || audioGroups.indexOf(track.groupId) !== -1,\n );\n return findMatchingOption(option, tracks, matchPredicate) > -1;\n },\n );\n if (matchingVideo > -1) {\n return matchingVideo;\n }\n return searchDownAndUpList(levels, searchIndex, (level: Level) => {\n const audioGroups = level.audioGroups;\n const tracks = allAudioTracks.filter(\n (track): boolean =>\n !audioGroups || audioGroups.indexOf(track.groupId) !== -1,\n );\n return findMatchingOption(option, tracks, matchPredicate) > -1;\n });\n}\n\nfunction searchDownAndUpList(\n arr: any[],\n searchIndex: number,\n predicate: (item: any) => boolean,\n): number {\n for (let i = searchIndex; i; i--) {\n if (predicate(arr[i])) {\n return i;\n }\n }\n for (let i = searchIndex + 1; i < arr.length; i++) {\n if (predicate(arr[i])) {\n return i;\n }\n }\n return -1;\n}\n","import EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\nimport { Events } from '../events';\nimport { ErrorDetails } from '../errors';\nimport { PlaylistLevelType } from '../types/loader';\nimport { logger } from '../utils/logger';\nimport {\n SUPPORTED_INFO_DEFAULT,\n getMediaDecodingInfoPromise,\n requiresMediaCapabilitiesDecodingInfo,\n} from '../utils/mediacapabilities-helper';\nimport {\n getAudioTracksByGroup,\n getCodecTiers,\n getStartCodecTier,\n type AudioTracksByGroup,\n type CodecSetTier,\n} from '../utils/rendition-helper';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { Level, VideoRange } from '../types/level';\nimport type { LoaderStats } from '../types/loader';\nimport type Hls from '../hls';\nimport type {\n FragLoadingData,\n FragLoadedData,\n FragBufferedData,\n LevelLoadedData,\n LevelSwitchingData,\n ManifestLoadingData,\n ErrorData,\n} from '../types/events';\nimport type { AbrComponentAPI } from '../types/component-api';\n\nclass AbrController implements AbrComponentAPI {\n protected hls: Hls;\n private lastLevelLoadSec: number = 0;\n private lastLoadedFragLevel: number = -1;\n private firstSelection: number = -1;\n private _nextAutoLevel: number = -1;\n private nextAutoLevelKey: string = '';\n private audioTracksByGroup: AudioTracksByGroup | null = null;\n private codecTiers: Record<string, CodecSetTier> | null = null;\n private timer: number = -1;\n private fragCurrent: Fragment | null = null;\n private partCurrent: Part | null = null;\n private bitrateTestDelay: number = 0;\n\n public bwEstimator: EwmaBandWidthEstimator;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.bwEstimator = this.initEstimator();\n this.registerListeners();\n }\n\n public resetEstimator(abrEwmaDefaultEstimate?: number) {\n if (abrEwmaDefaultEstimate) {\n logger.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);\n this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;\n }\n this.firstSelection = -1;\n this.bwEstimator = this.initEstimator();\n }\n\n private initEstimator(): EwmaBandWidthEstimator {\n const config = this.hls.config;\n return new EwmaBandWidthEstimator(\n config.abrEwmaSlowVoD,\n config.abrEwmaFastVoD,\n config.abrEwmaDefaultEstimate,\n );\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n protected unregisterListeners() {\n const { hls } = this;\n if (!hls) {\n return;\n }\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this.unregisterListeners();\n this.clearTimer();\n // @ts-ignore\n this.hls = this._abandonRulesCheck = null;\n this.fragCurrent = this.partCurrent = null;\n }\n\n protected onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) {\n this.lastLoadedFragLevel = -1;\n this.firstSelection = -1;\n this.lastLevelLoadSec = 0;\n this.fragCurrent = this.partCurrent = null;\n this.onLevelsUpdated();\n this.clearTimer();\n }\n\n private onLevelsUpdated() {\n if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {\n this.lastLoadedFragLevel = this.fragCurrent.level;\n }\n this._nextAutoLevel = -1;\n this.onMaxAutoLevelUpdated();\n this.codecTiers = null;\n this.audioTracksByGroup = null;\n }\n\n private onMaxAutoLevelUpdated() {\n this.firstSelection = -1;\n this.nextAutoLevelKey = '';\n }\n\n protected onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {\n const frag = data.frag;\n if (this.ignoreFragment(frag)) {\n return;\n }\n if (!frag.bitrateTest) {\n this.fragCurrent = frag;\n this.partCurrent = data.part ?? null;\n }\n this.clearTimer();\n this.timer = self.setInterval(this._abandonRulesCheck, 100);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData,\n ): void {\n this.clearTimer();\n }\n\n protected onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n return;\n }\n switch (data.details) {\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n // Reset last loaded level so that a new selection can be made after calling recoverMediaError\n this.lastLoadedFragLevel = -1;\n this.firstSelection = -1;\n break;\n case ErrorDetails.FRAG_LOAD_TIMEOUT: {\n const frag = data.frag;\n const { fragCurrent, partCurrent: part } = this;\n if (\n frag &&\n fragCurrent &&\n frag.sn === fragCurrent.sn &&\n frag.level === fragCurrent.level\n ) {\n const now = performance.now();\n const stats: LoaderStats = part ? part.stats : frag.stats;\n const timeLoading = now - stats.loading.start;\n const ttfb = stats.loading.first\n ? stats.loading.first - stats.loading.start\n : -1;\n const loadedFirstByte = stats.loaded && ttfb > -1;\n if (loadedFirstByte) {\n const ttfbEstimate = this.bwEstimator.getEstimateTTFB();\n this.bwEstimator.sample(\n timeLoading - Math.min(ttfbEstimate, ttfb),\n stats.loaded,\n );\n } else {\n this.bwEstimator.sampleTTFB(timeLoading);\n }\n }\n break;\n }\n }\n }\n\n private getTimeToLoadFrag(\n timeToFirstByteSec: number,\n bandwidth: number,\n fragSizeBits: number,\n isSwitch: boolean,\n ): number {\n const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;\n const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;\n return fragLoadSec + playlistLoadSec;\n }\n\n protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const config = this.hls.config;\n const { loading } = data.stats;\n const timeLoadingMs = loading.end - loading.start;\n if (Number.isFinite(timeLoadingMs)) {\n this.lastLevelLoadSec = timeLoadingMs / 1000;\n }\n if (data.details.live) {\n this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);\n } else {\n this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);\n }\n }\n\n /*\n This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load\n quickly enough to prevent underbuffering\n */\n private _abandonRulesCheck = () => {\n const { fragCurrent: frag, partCurrent: part, hls } = this;\n const { autoLevelEnabled, media } = hls;\n if (!frag || !media) {\n return;\n }\n\n const now = performance.now();\n const stats: LoaderStats = part ? part.stats : frag.stats;\n const duration = part ? part.duration : frag.duration;\n const timeLoading = now - stats.loading.start;\n const minAutoLevel = hls.minAutoLevel;\n // If frag loading is aborted, complete, or from lowest level, stop timer and return\n if (\n stats.aborted ||\n (stats.loaded && stats.loaded === stats.total) ||\n frag.level <= minAutoLevel\n ) {\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n\n // This check only runs if we're in ABR mode and actually playing\n if (\n !autoLevelEnabled ||\n media.paused ||\n !media.playbackRate ||\n !media.readyState\n ) {\n return;\n }\n\n const bufferInfo = hls.mainForwardBufferInfo;\n if (bufferInfo === null) {\n return;\n }\n\n const ttfbEstimate = this.bwEstimator.getEstimateTTFB();\n const playbackRate = Math.abs(media.playbackRate);\n // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed\n if (\n timeLoading <=\n Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))\n ) {\n return;\n }\n\n // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer\n const bufferStarvationDelay = bufferInfo.len / playbackRate;\n const ttfb = stats.loading.first\n ? stats.loading.first - stats.loading.start\n : -1;\n const loadedFirstByte = stats.loaded && ttfb > -1;\n const bwEstimate: number = this.getBwEstimate();\n const levels = hls.levels;\n const level = levels[frag.level];\n const expectedLen =\n stats.total ||\n Math.max(stats.loaded, Math.round((duration * level.averageBitrate) / 8));\n let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;\n if (timeStreaming < 1 && loadedFirstByte) {\n timeStreaming = Math.min(timeLoading, (stats.loaded * 8) / bwEstimate);\n }\n const loadRate = loadedFirstByte\n ? (stats.loaded * 1000) / timeStreaming\n : 0;\n // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment\n const fragLoadedDelay = loadRate\n ? (expectedLen - stats.loaded) / loadRate\n : (expectedLen * 8) / bwEstimate + ttfbEstimate / 1000;\n // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left\n if (fragLoadedDelay <= bufferStarvationDelay) {\n return;\n }\n\n const bwe = loadRate ? loadRate * 8 : bwEstimate;\n let fragLevelNextLoadedDelay: number = Number.POSITIVE_INFINITY;\n let nextLoadLevel: number;\n // Iterate through lower level and try to find the largest one that avoids rebuffering\n for (\n nextLoadLevel = frag.level - 1;\n nextLoadLevel > minAutoLevel;\n nextLoadLevel--\n ) {\n // compute time to load next fragment at lower level\n // 8 = bits per byte (bps/Bps)\n const levelNextBitrate = levels[nextLoadLevel].maxBitrate;\n fragLevelNextLoadedDelay = this.getTimeToLoadFrag(\n ttfbEstimate / 1000,\n bwe,\n duration * levelNextBitrate,\n !levels[nextLoadLevel].details,\n );\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n break;\n }\n }\n // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing\n // to load the current one\n if (fragLevelNextLoadedDelay >= fragLoadedDelay) {\n return;\n }\n\n // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down\n if (fragLevelNextLoadedDelay > duration * 10) {\n return;\n }\n hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;\n if (loadedFirstByte) {\n // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time\n this.bwEstimator.sample(\n timeLoading - Math.min(ttfbEstimate, ttfb),\n stats.loaded,\n );\n } else {\n // If there has been no loading progress, sample TTFB\n this.bwEstimator.sampleTTFB(timeLoading);\n }\n const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;\n if (\n this.getBwEstimate() * this.hls.config.abrBandWidthUpFactor >\n nextLoadLevelBitrate\n ) {\n this.resetEstimator(nextLoadLevelBitrate);\n }\n\n this.clearTimer();\n logger.warn(`[abr] Fragment ${frag.sn}${\n part ? ' part ' + part.index : ''\n } of level ${frag.level} is loading too slowly;\n Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s\n Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s\n Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(\n 3,\n )} s\n TTFB estimate: ${ttfb | 0} ms\n Current BW estimate: ${\n Number.isFinite(bwEstimate) ? bwEstimate | 0 : 'Unknown'\n } bps\n New BW estimate: ${this.getBwEstimate() | 0} bps\n Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);\n hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, { frag, part, stats });\n };\n\n protected onFragLoaded(\n event: Events.FRAG_LOADED,\n { frag, part }: FragLoadedData,\n ) {\n const stats = part ? part.stats : frag.stats;\n if (frag.type === PlaylistLevelType.MAIN) {\n this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n if (frag.level === this._nextAutoLevel) {\n this._nextAutoLevel = -1;\n }\n this.firstSelection = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const duration = part ? part.duration : frag.duration;\n const level = this.hls.levels[frag.level];\n const loadedBytes =\n (level.loaded ? level.loaded.bytes : 0) + stats.loaded;\n const loadedDuration =\n (level.loaded ? level.loaded.duration : 0) + duration;\n level.loaded = { bytes: loadedBytes, duration: loadedDuration };\n level.realBitrate = Math.round((8 * loadedBytes) / loadedDuration);\n }\n if (frag.bitrateTest) {\n const fragBufferedData: FragBufferedData = {\n stats,\n frag,\n part,\n id: frag.type,\n };\n this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);\n frag.bitrateTest = false;\n } else {\n // store level id after successful fragment load for playback\n this.lastLoadedFragLevel = frag.level;\n }\n }\n\n protected onFragBuffered(\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData,\n ) {\n const { frag, part } = data;\n const stats = part?.stats.loaded ? part.stats : frag.stats;\n\n if (stats.aborted) {\n return;\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;\n // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch\n // is used. If we used buffering in that case, our BW estimate sample will be very large.\n const processingMs =\n stats.parsing.end -\n stats.loading.start -\n Math.min(\n stats.loading.first - stats.loading.start,\n this.bwEstimator.getEstimateTTFB(),\n );\n this.bwEstimator.sample(processingMs, stats.loaded);\n stats.bwEstimate = this.getBwEstimate();\n if (frag.bitrateTest) {\n this.bitrateTestDelay = processingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n\n private ignoreFragment(frag: Fragment): boolean {\n // Only count non-alt-audio frags which were actually buffered in our BW calculations\n return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';\n }\n\n public clearTimer() {\n if (this.timer > -1) {\n self.clearInterval(this.timer);\n this.timer = -1;\n }\n }\n\n public get firstAutoLevel(): number {\n const { maxAutoLevel, minAutoLevel } = this.hls;\n const bwEstimate = this.getBwEstimate();\n const maxStartDelay = this.hls.config.maxStarvationDelay;\n const abrAutoLevel = this.findBestLevel(\n bwEstimate,\n minAutoLevel,\n maxAutoLevel,\n 0,\n maxStartDelay,\n 1,\n 1,\n );\n if (abrAutoLevel > -1) {\n return abrAutoLevel;\n }\n const firstLevel = this.hls.firstLevel;\n const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);\n logger.warn(\n `[abr] Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`,\n );\n return clamped;\n }\n\n public get forcedAutoLevel(): number {\n if (this.nextAutoLevelKey) {\n return -1;\n }\n return this._nextAutoLevel;\n }\n\n // return next auto level\n public get nextAutoLevel(): number {\n const forcedAutoLevel = this.forcedAutoLevel;\n const bwEstimator = this.bwEstimator;\n const useEstimate = bwEstimator.canEstimate();\n const loadedFirstFrag = this.lastLoadedFragLevel > -1;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (\n forcedAutoLevel !== -1 &&\n (!useEstimate ||\n !loadedFirstFrag ||\n this.nextAutoLevelKey === this.getAutoLevelKey())\n ) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n const nextABRAutoLevel =\n useEstimate && loadedFirstFrag\n ? this.getNextABRAutoLevel()\n : this.firstAutoLevel;\n\n // use forced auto level while it hasn't errored more than ABR selection\n if (forcedAutoLevel !== -1) {\n const levels = this.hls.levels;\n if (\n levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) &&\n levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError\n ) {\n return forcedAutoLevel;\n }\n }\n\n // save result until state has changed\n this._nextAutoLevel = nextABRAutoLevel;\n this.nextAutoLevelKey = this.getAutoLevelKey();\n\n return nextABRAutoLevel;\n }\n\n private getAutoLevelKey(): string {\n return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;\n }\n\n private getNextABRAutoLevel(): number {\n const { fragCurrent, partCurrent, hls } = this;\n const { maxAutoLevel, config, minAutoLevel } = hls;\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n const avgbw = this.getBwEstimate();\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferStarvationDelay = this.getStarvationDelay();\n\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n if (bufferStarvationDelay) {\n const bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay,\n 0,\n bwFactor,\n bwUpFactor,\n );\n if (bestLevel >= 0) {\n return bestLevel;\n }\n }\n // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering\n let maxStarvationDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxStarvationDelay)\n : config.maxStarvationDelay;\n\n if (!bufferStarvationDelay) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n const bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxLoadingDelay)\n : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.info(\n `[abr] bitrate test took ${Math.round(\n 1000 * bitrateTestDelay,\n )}ms, set first fragment max fetchDuration to ${Math.round(\n 1000 * maxStarvationDelay,\n )} ms`,\n );\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n const bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay,\n maxStarvationDelay,\n bwFactor,\n bwUpFactor,\n );\n logger.info(\n `[abr] ${\n bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'\n }, optimal quality level ${bestLevel}`,\n );\n if (bestLevel > -1) {\n return bestLevel;\n }\n // If no matching level found, see if min auto level would be a better option\n const minLevel = hls.levels[minAutoLevel];\n const autoLevel = hls.levels[hls.loadLevel];\n if (minLevel?.bitrate < autoLevel?.bitrate) {\n return minAutoLevel;\n }\n // or if bitrate is not lower, continue to use loadLevel\n return hls.loadLevel;\n }\n\n private getStarvationDelay(): number {\n const hls = this.hls;\n const media = hls.media;\n if (!media) {\n return Infinity;\n }\n // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n const playbackRate =\n media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;\n const bufferInfo = hls.mainForwardBufferInfo;\n return (bufferInfo ? bufferInfo.len : 0) / playbackRate;\n }\n\n private getBwEstimate(): number {\n return this.bwEstimator.canEstimate()\n ? this.bwEstimator.getEstimate()\n : this.hls.config.abrEwmaDefaultEstimate;\n }\n\n private findBestLevel(\n currentBw: number,\n minAutoLevel: number,\n maxAutoLevel: number,\n bufferStarvationDelay: number,\n maxStarvationDelay: number,\n bwFactor: number,\n bwUpFactor: number,\n ): number {\n const maxFetchDuration: number = bufferStarvationDelay + maxStarvationDelay;\n const lastLoadedFragLevel = this.lastLoadedFragLevel;\n const selectionBaseLevel =\n lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;\n const { fragCurrent, partCurrent } = this;\n const { levels, allAudioTracks, loadLevel, config } = this.hls;\n if (levels.length === 1) {\n return 0;\n }\n const level: Level | undefined = levels[selectionBaseLevel];\n const live = !!level?.details?.live;\n const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;\n let currentCodecSet: string | undefined;\n let currentVideoRange: VideoRange | undefined = 'SDR';\n let currentFrameRate = level?.frameRate || 0;\n\n const { audioPreference, videoPreference } = config;\n const audioTracksByGroup =\n this.audioTracksByGroup ||\n (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));\n if (firstSelection) {\n if (this.firstSelection !== -1) {\n return this.firstSelection;\n }\n const codecTiers =\n this.codecTiers ||\n (this.codecTiers = getCodecTiers(\n levels,\n audioTracksByGroup,\n minAutoLevel,\n maxAutoLevel,\n ));\n const startTier = getStartCodecTier(\n codecTiers,\n currentVideoRange,\n currentBw,\n audioPreference,\n videoPreference,\n );\n const { codecSet, videoRanges, minFramerate, minBitrate, preferHDR } =\n startTier;\n currentCodecSet = codecSet;\n currentVideoRange = preferHDR\n ? videoRanges[videoRanges.length - 1]\n : videoRanges[0];\n currentFrameRate = minFramerate;\n currentBw = Math.max(currentBw, minBitrate);\n logger.log(`[abr] picked start tier ${JSON.stringify(startTier)}`);\n } else {\n currentCodecSet = level?.codecSet;\n currentVideoRange = level?.videoRange;\n }\n\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n\n const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;\n const levelsSkipped: number[] = [];\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n const levelInfo = levels[i];\n const upSwitch = i > selectionBaseLevel;\n if (!levelInfo) {\n continue;\n }\n if (\n __USE_MEDIA_CAPABILITIES__ &&\n config.useMediaCapabilities &&\n !levelInfo.supportedResult &&\n !levelInfo.supportedPromise\n ) {\n const mediaCapabilities = navigator.mediaCapabilities as\n | MediaCapabilities\n | undefined;\n if (\n typeof mediaCapabilities?.decodingInfo === 'function' &&\n requiresMediaCapabilitiesDecodingInfo(\n levelInfo,\n audioTracksByGroup,\n currentVideoRange,\n currentFrameRate,\n currentBw,\n audioPreference,\n )\n ) {\n levelInfo.supportedPromise = getMediaDecodingInfoPromise(\n levelInfo,\n audioTracksByGroup,\n mediaCapabilities,\n );\n levelInfo.supportedPromise.then((decodingInfo) => {\n if (!this.hls) {\n return;\n }\n levelInfo.supportedResult = decodingInfo;\n const levels = this.hls.levels;\n const index = levels.indexOf(levelInfo);\n if (decodingInfo.error) {\n logger.warn(\n `[abr] MediaCapabilities decodingInfo error: \"${\n decodingInfo.error\n }\" for level ${index} ${JSON.stringify(decodingInfo)}`,\n );\n } else if (!decodingInfo.supported) {\n logger.warn(\n `[abr] Unsupported MediaCapabilities decodingInfo result for level ${index} ${JSON.stringify(\n decodingInfo,\n )}`,\n );\n if (index > -1 && levels.length > 1) {\n logger.log(`[abr] Removing unsupported level ${index}`);\n this.hls.removeLevel(index);\n }\n }\n });\n } else {\n levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;\n }\n }\n\n // skip candidates which change codec-family or video-range,\n // and which decrease or increase frame-rate for up and down-switch respectfully\n if (\n (currentCodecSet && levelInfo.codecSet !== currentCodecSet) ||\n (currentVideoRange && levelInfo.videoRange !== currentVideoRange) ||\n (upSwitch && currentFrameRate > levelInfo.frameRate) ||\n (!upSwitch &&\n currentFrameRate > 0 &&\n currentFrameRate < levelInfo.frameRate) ||\n (levelInfo.supportedResult &&\n !levelInfo.supportedResult.decodingInfoResults?.[0].smooth)\n ) {\n levelsSkipped.push(i);\n continue;\n }\n\n const levelDetails = levelInfo.details;\n const avgDuration =\n (partCurrent\n ? levelDetails?.partTarget\n : levelDetails?.averagetargetduration) || currentFragDuration;\n\n let adjustedbw: number;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (!upSwitch) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)\n const bitrate: number =\n currentFragDuration &&\n bufferStarvationDelay >= currentFragDuration * 2 &&\n maxStarvationDelay === 0\n ? levels[i].averageBitrate\n : levels[i].maxBitrate;\n const fetchDuration: number = this.getTimeToLoadFrag(\n ttfbEstimateSec,\n adjustedbw,\n bitrate * avgDuration,\n levelDetails === undefined,\n );\n\n const canSwitchWithinTolerance =\n // if adjusted bw is greater than level bitrate AND\n adjustedbw >= bitrate &&\n // no level change, or new level has no error history\n (i === lastLoadedFragLevel ||\n (levelInfo.loadError === 0 && levelInfo.fragmentError === 0)) &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1\n (fetchDuration <= ttfbEstimateSec ||\n !Number.isFinite(fetchDuration) ||\n (live && !this.bitrateTestDelay) ||\n fetchDuration < maxFetchDuration);\n if (canSwitchWithinTolerance) {\n const forcedAutoLevel = this.forcedAutoLevel;\n if (\n i !== loadLevel &&\n (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)\n ) {\n if (levelsSkipped.length) {\n logger.trace(\n `[abr] Skipped level(s) ${levelsSkipped.join(\n ',',\n )} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:\"${\n levels[levelsSkipped[0]].codecs\n }\" ${levels[levelsSkipped[0]].videoRange}; not compatible with \"${\n level.codecs\n }\" ${currentVideoRange}`,\n );\n }\n logger.info(\n `[abr] switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(\n adjustedbw,\n )})-bitrate=${Math.round(\n adjustedbw - bitrate,\n )} ttfb:${ttfbEstimateSec.toFixed(\n 1,\n )} avgDuration:${avgDuration.toFixed(\n 1,\n )} maxFetchDuration:${maxFetchDuration.toFixed(\n 1,\n )} fetchDuration:${fetchDuration.toFixed(\n 1,\n )} firstSelection:${firstSelection} codecSet:${currentCodecSet} videoRange:${currentVideoRange} hls.loadLevel:${loadLevel}`,\n );\n }\n if (firstSelection) {\n this.firstSelection = i;\n }\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n public set nextAutoLevel(nextLevel: number) {\n const { maxAutoLevel, minAutoLevel } = this.hls;\n const value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);\n if (this._nextAutoLevel !== value) {\n this.nextAutoLevelKey = '';\n this._nextAutoLevel = value;\n }\n }\n}\n\nexport default AbrController;\n","/**\n * Provides methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n */\n\nimport { logger } from './logger';\n\ntype BufferTimeRange = {\n start: number;\n end: number;\n};\n\nexport type Bufferable = {\n buffered: TimeRanges;\n};\n\nexport type BufferInfo = {\n len: number;\n start: number;\n end: number;\n nextStart?: number;\n};\n\nconst noopBuffered: TimeRanges = {\n length: 0,\n start: () => 0,\n end: () => 0,\n};\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n */\n static isBuffered(media: Bufferable, position: number): boolean {\n try {\n if (media) {\n const buffered = BufferHelper.getBuffered(media);\n for (let i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo(\n media: Bufferable | null,\n pos: number,\n maxHoleDuration: number,\n ): BufferInfo {\n try {\n if (media) {\n const vbuffered = BufferHelper.getBuffered(media);\n const buffered: BufferTimeRange[] = [];\n let i: number;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });\n }\n\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo(\n buffered: BufferTimeRange[],\n pos: number,\n maxHoleDuration: number,\n ): {\n len: number;\n start: number;\n end: number;\n nextStart?: number;\n } {\n pos = Math.max(0, pos);\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n buffered.sort(function (a, b) {\n const diff = a.start - b.start;\n if (diff) {\n return diff;\n } else {\n return b.end - a.end;\n }\n });\n\n let buffered2: BufferTimeRange[] = [];\n if (maxHoleDuration) {\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (let i = 0; i < buffered.length; i++) {\n const buf2len = buffered2.length;\n if (buf2len) {\n const buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if (buffered[i].start - buf2end < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if (buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n } else {\n buffered2 = buffered;\n }\n\n let bufferLen = 0;\n\n // bufferStartNext can possibly be undefined based on the conditional logic below\n let bufferStartNext: number | undefined;\n\n // bufferStart and bufferEnd are buffer boundaries around current video position\n let bufferStart: number = pos;\n let bufferEnd: number = pos;\n for (let i = 0; i < buffered2.length; i++) {\n const start = buffered2[i].start;\n const end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if (pos + maxHoleDuration >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if (pos + maxHoleDuration < start) {\n bufferStartNext = start;\n break;\n }\n }\n return {\n len: bufferLen,\n start: bufferStart || 0,\n end: bufferEnd || 0,\n nextStart: bufferStartNext,\n };\n }\n\n /**\n * Safe method to get buffered property.\n * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource\n */\n static getBuffered(media: Bufferable): TimeRanges {\n try {\n return media.buffered;\n } catch (e) {\n logger.log('failed to get media.buffered', e);\n return noopBuffered;\n }\n }\n}\n","import { logger } from '../utils/logger';\nimport type {\n BufferOperation,\n BufferOperationQueues,\n SourceBuffers,\n SourceBufferName,\n} from '../types/buffer';\n\nexport default class BufferOperationQueue {\n private buffers: SourceBuffers;\n private queues: BufferOperationQueues = {\n video: [],\n audio: [],\n audiovideo: [],\n };\n\n constructor(sourceBufferReference: SourceBuffers) {\n this.buffers = sourceBufferReference;\n }\n\n public append(\n operation: BufferOperation,\n type: SourceBufferName,\n pending?: boolean,\n ) {\n const queue = this.queues[type];\n queue.push(operation);\n if (queue.length === 1 && !pending) {\n this.executeNext(type);\n }\n }\n\n public insertAbort(operation: BufferOperation, type: SourceBufferName) {\n const queue = this.queues[type];\n queue.unshift(operation);\n this.executeNext(type);\n }\n\n public appendBlocker(type: SourceBufferName): Promise<{}> {\n let execute;\n const promise: Promise<{}> = new Promise((resolve) => {\n execute = resolve;\n });\n const operation: BufferOperation = {\n execute,\n onStart: () => {},\n onComplete: () => {},\n onError: () => {},\n };\n\n this.append(operation, type);\n return promise;\n }\n\n public executeNext(type: SourceBufferName) {\n const queue = this.queues[type];\n if (queue.length) {\n const operation: BufferOperation = queue[0];\n try {\n // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations\n // which do not end with this event must call _onSBUpdateEnd manually\n operation.execute();\n } catch (error) {\n logger.warn(\n `[buffer-operation-queue]: Exception executing \"${type}\" SourceBuffer operation: ${error}`,\n );\n operation.onError(error);\n\n // Only shift the current operation off, otherwise the updateend handler will do this for us\n const sb = this.buffers[type];\n if (!sb?.updating) {\n this.shiftAndExecuteNext(type);\n }\n }\n }\n }\n\n public shiftAndExecuteNext(type: SourceBufferName) {\n this.queues[type].shift();\n this.executeNext(type);\n }\n\n public current(type: SourceBufferName) {\n return this.queues[type][0];\n }\n}\n","import { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport {\n getCodecCompatibleName,\n pickMostCompleteCodecName,\n} from '../utils/codecs';\nimport {\n getMediaSource,\n isManagedMediaSource,\n} from '../utils/mediasource-helper';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport type { TrackSet } from '../types/track';\nimport BufferOperationQueue from './buffer-operation-queue';\nimport {\n BufferOperation,\n SourceBuffers,\n SourceBufferName,\n SourceBufferListeners,\n} from '../types/buffer';\nimport type {\n LevelUpdatedData,\n BufferAppendingData,\n MediaAttachingData,\n ManifestParsedData,\n BufferCodecsData,\n BufferEOSData,\n BufferFlushingData,\n FragParsedData,\n FragChangedData,\n ErrorData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { ChunkMetadata } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { HlsConfig } from '../config';\n\nconst VIDEO_CODEC_PROFILE_REPLACE =\n /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\\.[^.,]+)+/;\n\ninterface BufferedChangeEvent extends Event {\n readonly addedRanges?: TimeRanges;\n readonly removedRanges?: TimeRanges;\n}\n\nexport default class BufferController implements ComponentAPI {\n // The level details used to determine duration, target-duration and live\n private details: LevelDetails | null = null;\n // cache the self generated object url to detect hijack of video tag\n private _objectUrl: string | null = null;\n // A queue of buffer operations which require the SourceBuffer to not be updating upon execution\n private operationQueue!: BufferOperationQueue;\n // References to event listeners for each SourceBuffer, so that they can be referenced for event removal\n private listeners!: SourceBufferListeners;\n\n private hls: Hls;\n\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n public bufferCodecEventsExpected: number = 0;\n\n // The total number of BUFFER_CODEC events received\n private _bufferCodecEventsTotal: number = 0;\n\n // A reference to the attached media element\n public media: HTMLMediaElement | null = null;\n\n // A reference to the active media source\n public mediaSource: MediaSource | null = null;\n\n // Last MP3 audio chunk appended\n private lastMpegAudioChunk: ChunkMetadata | null = null;\n\n private appendSource: boolean;\n\n // counters\n public appendErrors = {\n audio: 0,\n video: 0,\n audiovideo: 0,\n };\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer!: SourceBuffers;\n\n protected log: (msg: any) => void;\n protected warn: (msg: any, obj?: any) => void;\n protected error: (msg: any, obj?: any) => void;\n\n constructor(hls: Hls) {\n this.hls = hls;\n const logPrefix = '[buffer-controller]';\n this.appendSource = isManagedMediaSource(\n getMediaSource(hls.config.preferManagedMediaSource),\n );\n this.log = logger.log.bind(logger, logPrefix);\n this.warn = logger.warn.bind(logger, logPrefix);\n this.error = logger.error.bind(logger, logPrefix);\n this._initSourceBuffer();\n this.registerListeners();\n }\n\n public hasSourceTypes(): boolean {\n return (\n this.getSourceBufferTypes().length > 0 ||\n Object.keys(this.pendingTracks).length > 0\n );\n }\n\n public destroy() {\n this.unregisterListeners();\n this.details = null;\n this.lastMpegAudioChunk = null;\n // @ts-ignore\n this.hls = null;\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.on(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);\n }\n\n protected unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.off(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);\n }\n\n private _initSourceBuffer() {\n this.sourceBuffer = {};\n this.operationQueue = new BufferOperationQueue(this.sourceBuffer);\n this.listeners = {\n audio: [],\n video: [],\n audiovideo: [],\n };\n this.appendErrors = {\n audio: 0,\n video: 0,\n audiovideo: 0,\n };\n this.lastMpegAudioChunk = null;\n }\n\n private onManifestLoading() {\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;\n this.details = null;\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n let codecEvents: number = 2;\n if ((data.audio && !data.video) || !data.altAudio || !__USE_ALT_AUDIO__) {\n codecEvents = 1;\n }\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) {\n const media = (this.media = data.media);\n const MediaSource = getMediaSource(this.appendSource);\n\n if (media && MediaSource) {\n const ms = (this.mediaSource = new MediaSource());\n this.log(`created media source: ${ms.constructor?.name}`);\n // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\n if (this.appendSource) {\n ms.addEventListener('startstreaming', this._onStartStreaming);\n ms.addEventListener('endstreaming', this._onEndStreaming);\n }\n\n // cache the locally generated object url\n const objectUrl = (this._objectUrl = self.URL.createObjectURL(ms));\n // link video and media Source\n if (this.appendSource) {\n try {\n media.removeAttribute('src');\n // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives\n const MMS = (self as any).ManagedMediaSource;\n media.disableRemotePlayback =\n media.disableRemotePlayback || (MMS && ms instanceof MMS);\n removeSourceChildren(media);\n addSource(media, objectUrl);\n media.load();\n } catch (error) {\n media.src = objectUrl;\n }\n } else {\n media.src = objectUrl;\n }\n media.addEventListener('emptied', this._onMediaEmptied);\n }\n }\n private _onEndStreaming = (event) => {\n if (!this.hls) {\n return;\n }\n this.hls.pauseBuffering();\n };\n private _onStartStreaming = (event) => {\n if (!this.hls) {\n return;\n }\n this.hls.resumeBuffering();\n };\n\n protected onMediaDetaching() {\n const { media, mediaSource, _objectUrl } = this;\n if (mediaSource) {\n this.log('media source detaching');\n if (mediaSource.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n mediaSource.endOfStream();\n } catch (err) {\n this.warn(\n `onMediaDetaching: ${err.message} while calling endOfStream`,\n );\n }\n }\n // Clean up the SourceBuffers by invoking onBufferReset\n this.onBufferReset();\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);\n mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);\n if (this.appendSource) {\n mediaSource.removeEventListener(\n 'startstreaming',\n this._onStartStreaming,\n );\n mediaSource.removeEventListener('endstreaming', this._onEndStreaming);\n }\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n if (_objectUrl) {\n self.URL.revokeObjectURL(_objectUrl);\n }\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.mediaSrc === _objectUrl) {\n media.removeAttribute('src');\n if (this.appendSource) {\n removeSourceChildren(media);\n }\n media.load();\n } else {\n this.warn(\n 'media|source.src was changed by a third party - skip cleanup',\n );\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = null;\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n this.pendingTracks = {};\n this.tracks = {};\n }\n\n this.hls.trigger(Events.MEDIA_DETACHED, undefined);\n }\n\n protected onBufferReset() {\n this.getSourceBufferTypes().forEach((type) => {\n this.resetBuffer(type);\n });\n this._initSourceBuffer();\n }\n\n private resetBuffer(type: SourceBufferName) {\n const sb = this.sourceBuffer[type];\n try {\n if (sb) {\n this.removeBufferListeners(type);\n // Synchronously remove the SB from the map before the next call in order to prevent an async function from\n // accessing it\n this.sourceBuffer[type] = undefined;\n if (this.mediaSource?.sourceBuffers.length) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n }\n } catch (err) {\n this.warn(`onBufferReset ${type}`, err);\n }\n }\n\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData,\n ) {\n const sourceBufferCount = this.getSourceBufferTypes().length;\n const trackNames = Object.keys(data);\n trackNames.forEach((trackName) => {\n if (sourceBufferCount) {\n // check if SourceBuffer codec needs to change\n const track = this.tracks[trackName];\n if (track && typeof track.buffer.changeType === 'function') {\n const { id, codec, levelCodec, container, metadata } =\n data[trackName];\n const currentCodecFull = pickMostCompleteCodecName(\n track.codec,\n track.levelCodec,\n );\n const currentCodec = currentCodecFull?.replace(\n VIDEO_CODEC_PROFILE_REPLACE,\n '$1',\n );\n let trackCodec = pickMostCompleteCodecName(codec, levelCodec);\n const nextCodec = trackCodec?.replace(\n VIDEO_CODEC_PROFILE_REPLACE,\n '$1',\n );\n if (trackCodec && currentCodec !== nextCodec) {\n if (trackName.slice(0, 5) === 'audio') {\n trackCodec = getCodecCompatibleName(\n trackCodec,\n this.appendSource,\n );\n }\n const mimeType = `${container};codecs=${trackCodec}`;\n this.appendChangeType(trackName, mimeType);\n this.log(`switching codec ${currentCodecFull} to ${trackCodec}`);\n this.tracks[trackName] = {\n buffer: track.buffer,\n codec,\n container,\n levelCodec,\n metadata,\n id,\n };\n }\n }\n } else {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n this.pendingTracks[trackName] = data[trackName];\n }\n });\n\n // if sourcebuffers already created, do nothing ...\n if (sourceBufferCount) {\n return;\n }\n\n const bufferCodecEventsExpected = Math.max(\n this.bufferCodecEventsExpected - 1,\n 0,\n );\n if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) {\n this.log(\n `${bufferCodecEventsExpected} bufferCodec event(s) expected ${trackNames.join(\n ',',\n )}`,\n );\n this.bufferCodecEventsExpected = bufferCodecEventsExpected;\n }\n if (this.mediaSource && this.mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n protected appendChangeType(type, mimeType) {\n const { operationQueue } = this;\n const operation: BufferOperation = {\n execute: () => {\n const sb = this.sourceBuffer[type];\n if (sb) {\n this.log(`changing ${type} sourceBuffer type to ${mimeType}`);\n sb.changeType(mimeType);\n }\n operationQueue.shiftAndExecuteNext(type);\n },\n onStart: () => {},\n onComplete: () => {},\n onError: (error: Error) => {\n this.warn(`Failed to change ${type} SourceBuffer type`, error);\n },\n };\n\n operationQueue.append(operation, type, !!this.pendingTracks[type]);\n }\n\n protected onBufferAppending(\n event: Events.BUFFER_APPENDING,\n eventData: BufferAppendingData,\n ) {\n const { hls, operationQueue, tracks } = this;\n const { data, type, frag, part, chunkMeta } = eventData;\n const chunkStats = chunkMeta.buffering[type];\n\n const bufferAppendingStart = self.performance.now();\n chunkStats.start = bufferAppendingStart;\n const fragBuffering = frag.stats.buffering;\n const partBuffering = part ? part.stats.buffering : null;\n if (fragBuffering.start === 0) {\n fragBuffering.start = bufferAppendingStart;\n }\n if (partBuffering && partBuffering.start === 0) {\n partBuffering.start = bufferAppendingStart;\n }\n\n // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n const audioTrack = tracks.audio;\n let checkTimestampOffset = false;\n if (type === 'audio' && audioTrack?.container === 'audio/mpeg') {\n checkTimestampOffset =\n !this.lastMpegAudioChunk ||\n chunkMeta.id === 1 ||\n this.lastMpegAudioChunk.sn !== chunkMeta.sn;\n this.lastMpegAudioChunk = chunkMeta;\n }\n\n const fragStart = frag.start;\n const operation: BufferOperation = {\n execute: () => {\n chunkStats.executeStart = self.performance.now();\n if (checkTimestampOffset) {\n const sb = this.sourceBuffer[type];\n if (sb) {\n const delta = fragStart - sb.timestampOffset;\n if (Math.abs(delta) >= 0.1) {\n this.log(\n `Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${frag.sn})`,\n );\n sb.timestampOffset = fragStart;\n }\n }\n }\n this.appendExecutor(data, type);\n },\n onStart: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);\n const end = self.performance.now();\n chunkStats.executeEnd = chunkStats.end = end;\n if (fragBuffering.first === 0) {\n fragBuffering.first = end;\n }\n if (partBuffering && partBuffering.first === 0) {\n partBuffering.first = end;\n }\n\n const { sourceBuffer } = this;\n const timeRanges = {};\n for (const type in sourceBuffer) {\n timeRanges[type] = BufferHelper.getBuffered(sourceBuffer[type]);\n }\n this.appendErrors[type] = 0;\n if (type === 'audio' || type === 'video') {\n this.appendErrors.audiovideo = 0;\n } else {\n this.appendErrors.audio = 0;\n this.appendErrors.video = 0;\n }\n this.hls.trigger(Events.BUFFER_APPENDED, {\n type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n timeRanges,\n });\n },\n onError: (error: Error) => {\n // in case any error occured while appending, put back segment in segments table\n const event: ErrorData = {\n type: ErrorTypes.MEDIA_ERROR,\n parent: frag.type,\n details: ErrorDetails.BUFFER_APPEND_ERROR,\n sourceBufferName: type,\n frag,\n part,\n chunkMeta,\n error,\n err: error,\n fatal: false,\n };\n\n if ((error as DOMException).code === DOMException.QUOTA_EXCEEDED_ERR) {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n } else {\n const appendErrorCount = ++this.appendErrors[type];\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. Retrying can help recover.\n */\n this.warn(\n `Failed ${appendErrorCount}/${hls.config.appendErrorMaxRetry} times to append segment in \"${type}\" sourceBuffer`,\n );\n if (appendErrorCount >= hls.config.appendErrorMaxRetry) {\n event.fatal = true;\n }\n }\n hls.trigger(Events.ERROR, event);\n },\n };\n operationQueue.append(operation, type, !!this.pendingTracks[type]);\n }\n\n protected onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData,\n ) {\n const { operationQueue } = this;\n const flushOperation = (type: SourceBufferName): BufferOperation => ({\n execute: this.removeExecutor.bind(\n this,\n type,\n data.startOffset,\n data.endOffset,\n ),\n onStart: () => {\n // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n this.hls.trigger(Events.BUFFER_FLUSHED, { type });\n },\n onError: (error: Error) => {\n this.warn(`Failed to remove from ${type} SourceBuffer`, error);\n },\n });\n\n if (data.type) {\n operationQueue.append(flushOperation(data.type), data.type);\n } else {\n this.getSourceBufferTypes().forEach((type: SourceBufferName) => {\n operationQueue.append(flushOperation(type), type);\n });\n }\n }\n\n protected onFragParsed(event: Events.FRAG_PARSED, data: FragParsedData) {\n const { frag, part } = data;\n const buffersAppendedTo: Array<SourceBufferName> = [];\n const elementaryStreams = part\n ? part.elementaryStreams\n : frag.elementaryStreams;\n if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {\n buffersAppendedTo.push('audiovideo');\n } else {\n if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {\n buffersAppendedTo.push('audio');\n }\n if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {\n buffersAppendedTo.push('video');\n }\n }\n\n const onUnblocked = () => {\n const now = self.performance.now();\n frag.stats.buffering.end = now;\n if (part) {\n part.stats.buffering.end = now;\n }\n const stats = part ? part.stats : frag.stats;\n this.hls.trigger(Events.FRAG_BUFFERED, {\n frag,\n part,\n stats,\n id: frag.type,\n });\n };\n\n if (buffersAppendedTo.length === 0) {\n this.warn(\n `Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`,\n );\n }\n\n this.blockBuffers(onUnblocked, buffersAppendedTo);\n }\n\n private onFragChanged(event: Events.FRAG_CHANGED, data: FragChangedData) {\n this.trimBuffers();\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n // an undefined data.type will mark all buffers as EOS.\n protected onBufferEos(event: Events.BUFFER_EOS, data: BufferEOSData) {\n const ended = this.getSourceBufferTypes().reduce((acc, type) => {\n const sb = this.sourceBuffer[type];\n if (sb && (!data.type || data.type === type)) {\n sb.ending = true;\n if (!sb.ended) {\n sb.ended = true;\n this.log(`${type} sourceBuffer now EOS`);\n }\n }\n return acc && !!(!sb || sb.ended);\n }, true);\n\n if (ended) {\n this.log(`Queueing mediaSource.endOfStream()`);\n this.blockBuffers(() => {\n this.getSourceBufferTypes().forEach((type) => {\n const sb = this.sourceBuffer[type];\n if (sb) {\n sb.ending = false;\n }\n });\n const { mediaSource } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n if (mediaSource) {\n this.log(\n `Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`,\n );\n }\n return;\n }\n this.log(`Calling mediaSource.endOfStream()`);\n // Allow this to throw and be caught by the enqueueing function\n mediaSource.endOfStream();\n });\n }\n }\n\n protected onLevelUpdated(\n event: Events.LEVEL_UPDATED,\n { details }: LevelUpdatedData,\n ) {\n if (!details.fragments.length) {\n return;\n }\n this.details = details;\n\n if (this.getSourceBufferTypes().length) {\n this.blockBuffers(this.updateMediaElementDuration.bind(this));\n } else {\n this.updateMediaElementDuration();\n }\n }\n\n trimBuffers() {\n const { hls, details, media } = this;\n if (!media || details === null) {\n return;\n }\n\n const sourceBufferTypes = this.getSourceBufferTypes();\n if (!sourceBufferTypes.length) {\n return;\n }\n\n const config: Readonly<HlsConfig> = hls.config;\n const currentTime = media.currentTime;\n const targetDuration = details.levelTargetDuration;\n\n // Support for deprecated liveBackBufferLength\n const backBufferLength =\n details.live && config.liveBackBufferLength !== null\n ? config.liveBackBufferLength\n : config.backBufferLength;\n\n if (Number.isFinite(backBufferLength) && backBufferLength > 0) {\n const maxBackBufferLength = Math.max(backBufferLength, targetDuration);\n const targetBackBufferPosition =\n Math.floor(currentTime / targetDuration) * targetDuration -\n maxBackBufferLength;\n\n this.flushBackBuffer(\n currentTime,\n targetDuration,\n targetBackBufferPosition,\n );\n }\n\n if (\n Number.isFinite(config.frontBufferFlushThreshold) &&\n config.frontBufferFlushThreshold > 0\n ) {\n const frontBufferLength = Math.max(\n config.maxBufferLength,\n config.frontBufferFlushThreshold,\n );\n\n const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);\n const targetFrontBufferPosition =\n Math.floor(currentTime / targetDuration) * targetDuration +\n maxFrontBufferLength;\n\n this.flushFrontBuffer(\n currentTime,\n targetDuration,\n targetFrontBufferPosition,\n );\n }\n }\n\n flushBackBuffer(\n currentTime: number,\n targetDuration: number,\n targetBackBufferPosition: number,\n ) {\n const { details, sourceBuffer } = this;\n const sourceBufferTypes = this.getSourceBufferTypes();\n\n sourceBufferTypes.forEach((type: SourceBufferName) => {\n const sb = sourceBuffer[type];\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n // when target buffer start exceeds actual buffer start\n if (\n buffered.length > 0 &&\n targetBackBufferPosition > buffered.start(0)\n ) {\n this.hls.trigger(Events.BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n\n // Support for deprecated event:\n if (details?.live) {\n this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n } else if (\n sb.ended &&\n buffered.end(buffered.length - 1) - currentTime < targetDuration * 2\n ) {\n this.log(\n `Cannot flush ${type} back buffer while SourceBuffer is in ended state`,\n );\n return;\n }\n\n this.hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: targetBackBufferPosition,\n type,\n });\n }\n }\n });\n }\n\n flushFrontBuffer(\n currentTime: number,\n targetDuration: number,\n targetFrontBufferPosition: number,\n ) {\n const { sourceBuffer } = this;\n const sourceBufferTypes = this.getSourceBufferTypes();\n\n sourceBufferTypes.forEach((type: SourceBufferName) => {\n const sb = sourceBuffer[type];\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n const numBufferedRanges = buffered.length;\n // The buffer is either empty or contiguous\n if (numBufferedRanges < 2) {\n return;\n }\n const bufferStart = buffered.start(numBufferedRanges - 1);\n const bufferEnd = buffered.end(numBufferedRanges - 1);\n // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position\n if (\n targetFrontBufferPosition > bufferStart ||\n (currentTime >= bufferStart && currentTime <= bufferEnd)\n ) {\n return;\n } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) {\n this.log(\n `Cannot flush ${type} front buffer while SourceBuffer is in ended state`,\n );\n return;\n }\n\n this.hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: bufferStart,\n endOffset: Infinity,\n type,\n });\n }\n });\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n private updateMediaElementDuration() {\n if (\n !this.details ||\n !this.media ||\n !this.mediaSource ||\n this.mediaSource.readyState !== 'open'\n ) {\n return;\n }\n const { details, hls, media, mediaSource } = this;\n const levelDuration = details.fragments[0].start + details.totalduration;\n const mediaDuration = media.duration;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : 0;\n\n if (details.live && hls.config.liveDurationInfinity) {\n // Override duration to Infinity\n mediaSource.duration = Infinity;\n this.updateSeekableRange(details);\n } else if (\n (levelDuration > msDuration && levelDuration > mediaDuration) ||\n !Number.isFinite(mediaDuration)\n ) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n this.log(`Updating Media Source duration to ${levelDuration.toFixed(3)}`);\n mediaSource.duration = levelDuration;\n }\n }\n\n updateSeekableRange(levelDetails) {\n const mediaSource = this.mediaSource;\n const fragments = levelDetails.fragments;\n const len = fragments.length;\n if (len && levelDetails.live && mediaSource?.setLiveSeekableRange) {\n const start = Math.max(0, fragments[0].start);\n const end = Math.max(start, start + levelDetails.totalduration);\n this.log(\n `Media Source duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`,\n );\n mediaSource.setLiveSeekableRange(start, end);\n }\n }\n\n protected checkPendingTracks() {\n const { bufferCodecEventsExpected, operationQueue, pendingTracks } = this;\n\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n const pendingTracksCount = Object.keys(pendingTracks).length;\n if (\n pendingTracksCount &&\n (!bufferCodecEventsExpected ||\n pendingTracksCount === 2 ||\n 'audiovideo' in pendingTracks)\n ) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n const buffers = this.getSourceBufferTypes();\n if (buffers.length) {\n this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks });\n buffers.forEach((type: SourceBufferName) => {\n operationQueue.executeNext(type);\n });\n } else {\n const error = new Error(\n 'could not create source buffer for media codec(s)',\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n error,\n reason: error.message,\n });\n }\n }\n }\n\n protected createSourceBuffers(tracks: TrackSet) {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource) {\n throw Error('createSourceBuffers called when mediaSource was null');\n }\n for (const trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n const track = tracks[trackName as keyof TrackSet];\n if (!track) {\n throw Error(\n `source buffer exists for track ${trackName}, however track does not`,\n );\n }\n // use levelCodec as first priority unless it contains multiple comma-separated codec values\n let codec =\n track.levelCodec?.indexOf(',') === -1\n ? track.levelCodec\n : track.codec;\n if (codec) {\n if (trackName.slice(0, 5) === 'audio') {\n codec = getCodecCompatibleName(codec, this.appendSource);\n }\n }\n const mimeType = `${track.container};codecs=${codec}`;\n this.log(`creating sourceBuffer(${mimeType})`);\n try {\n const sb = (sourceBuffer[trackName] =\n mediaSource.addSourceBuffer(mimeType));\n const sbName = trackName as SourceBufferName;\n this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);\n this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);\n this.addBufferListener(sbName, 'error', this._onSBUpdateError);\n // ManagedSourceBuffer bufferedchange event\n if (this.appendSource) {\n this.addBufferListener(\n sbName,\n 'bufferedchange',\n (type: SourceBufferName, event: BufferedChangeEvent) => {\n // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.\n const removedRanges = event.removedRanges;\n if (removedRanges?.length) {\n this.hls.trigger(Events.BUFFER_FLUSHED, {\n type: trackName as SourceBufferName,\n });\n }\n },\n );\n }\n\n this.tracks[trackName] = {\n buffer: sb,\n codec: codec,\n container: track.container,\n levelCodec: track.levelCodec,\n metadata: track.metadata,\n id: track.id,\n };\n } catch (err) {\n this.error(`error while trying to add sourceBuffer: ${err.message}`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,\n fatal: false,\n error: err,\n sourceBufferName: trackName as SourceBufferName,\n mimeType: mimeType,\n });\n }\n }\n }\n }\n\n // Keep as arrow functions so that we can directly reference these functions directly as event listeners\n private _onMediaSourceOpen = () => {\n const { media, mediaSource } = this;\n this.log('Media source opened');\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n this.updateMediaElementDuration();\n this.hls.trigger(Events.MEDIA_ATTACHED, {\n media,\n mediaSource: mediaSource as MediaSource,\n });\n }\n\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n }\n this.checkPendingTracks();\n };\n\n private _onMediaSourceClose = () => {\n this.log('Media source closed');\n };\n\n private _onMediaSourceEnded = () => {\n this.log('Media source ended');\n };\n\n private _onMediaEmptied = () => {\n const { mediaSrc, _objectUrl } = this;\n if (mediaSrc !== _objectUrl) {\n logger.error(\n `Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`,\n );\n }\n };\n\n private get mediaSrc(): string | undefined {\n const media = this.media?.querySelector?.('source') || this.media;\n return media?.src;\n }\n\n private _onSBUpdateStart(type: SourceBufferName) {\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onStart();\n }\n\n private _onSBUpdateEnd(type: SourceBufferName) {\n if (this.mediaSource?.readyState === 'closed') {\n this.resetBuffer(type);\n return;\n }\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onComplete();\n operationQueue.shiftAndExecuteNext(type);\n }\n\n private _onSBUpdateError(type: SourceBufferName, event: Event) {\n const error = new Error(\n `${type} SourceBuffer error. MediaSource readyState: ${this.mediaSource?.readyState}`,\n );\n this.error(`${error}`, event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_APPENDING_ERROR,\n sourceBufferName: type,\n error,\n fatal: false,\n });\n // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue\n const operation = this.operationQueue.current(type);\n if (operation) {\n operation.onError(error);\n }\n }\n\n // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually\n private removeExecutor(\n type: SourceBufferName,\n startOffset: number,\n endOffset: number,\n ) {\n const { media, mediaSource, operationQueue, sourceBuffer } = this;\n const sb = sourceBuffer[type];\n if (!media || !mediaSource || !sb) {\n this.warn(\n `Attempting to remove from the ${type} SourceBuffer, but it does not exist`,\n );\n operationQueue.shiftAndExecuteNext(type);\n return;\n }\n const mediaDuration = Number.isFinite(media.duration)\n ? media.duration\n : Infinity;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : Infinity;\n const removeStart = Math.max(0, startOffset);\n const removeEnd = Math.min(endOffset, mediaDuration, msDuration);\n if (removeEnd > removeStart && (!sb.ending || sb.ended)) {\n sb.ended = false;\n this.log(\n `Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`,\n );\n sb.remove(removeStart, removeEnd);\n } else {\n // Cycle the queue\n operationQueue.shiftAndExecuteNext(type);\n }\n }\n\n // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually\n private appendExecutor(data: Uint8Array, type: SourceBufferName) {\n const sb = this.sourceBuffer[type];\n if (!sb) {\n if (!this.pendingTracks[type]) {\n throw new Error(\n `Attempting to append to the ${type} SourceBuffer, but it does not exist`,\n );\n }\n return;\n }\n\n sb.ended = false;\n sb.appendBuffer(data);\n }\n\n // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises\n // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue\n // upon completion, since we already do it here\n private blockBuffers(\n onUnblocked: () => void,\n buffers: Array<SourceBufferName> = this.getSourceBufferTypes(),\n ) {\n if (!buffers.length) {\n this.log('Blocking operation requested, but no SourceBuffers exist');\n Promise.resolve().then(onUnblocked);\n return;\n }\n const { operationQueue } = this;\n\n // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);\n const blockingOperations = buffers.map((type) =>\n operationQueue.appendBlocker(type as SourceBufferName),\n );\n Promise.all(blockingOperations).then(() => {\n // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);\n onUnblocked();\n buffers.forEach((type) => {\n const sb = this.sourceBuffer[type];\n // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to\n // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)\n // While this is a workaround, it's probably useful to have around\n if (!sb?.updating) {\n operationQueue.shiftAndExecuteNext(type);\n }\n });\n });\n }\n\n private getSourceBufferTypes(): Array<SourceBufferName> {\n return Object.keys(this.sourceBuffer) as Array<SourceBufferName>;\n }\n\n private addBufferListener(\n type: SourceBufferName,\n event: string,\n fn: Function,\n ) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n const listener = fn.bind(this, type);\n this.listeners[type].push({ event, listener });\n buffer.addEventListener(event, listener);\n }\n\n private removeBufferListeners(type: SourceBufferName) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n this.listeners[type].forEach((l) => {\n buffer.removeEventListener(l.event, l.listener);\n });\n }\n}\n\nfunction removeSourceChildren(node: HTMLElement) {\n const sourceChildren = node.querySelectorAll('source');\n [].slice.call(sourceChildren).forEach((source) => {\n node.removeChild(source);\n });\n}\n\nfunction addSource(media: HTMLMediaElement, url: string) {\n const source = self.document.createElement('source');\n source.type = 'video/mp4';\n source.src = url;\n media.appendChild(source);\n}\n","/*\n * cap stream level to media size dimension controller\n */\n\nimport { Events } from '../events';\nimport type { Level } from '../types/level';\nimport type {\n ManifestParsedData,\n BufferCodecsData,\n MediaAttachingData,\n FPSDropLevelCappingData,\n LevelsUpdatedData,\n} from '../types/events';\nimport StreamController from './stream-controller';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\n\ntype RestrictedLevel = { width: number; height: number; bitrate: number };\nclass CapLevelController implements ComponentAPI {\n private hls: Hls;\n private autoLevelCapping: number;\n private firstLevel: number;\n private media: HTMLVideoElement | null;\n private restrictedLevels: RestrictedLevel[];\n private timer: number | undefined;\n private clientRect: { width: number; height: number } | null;\n private streamController?: StreamController;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = -1;\n this.media = null;\n this.restrictedLevels = [];\n this.timer = undefined;\n this.clientRect = null;\n\n this.registerListeners();\n }\n\n public setStreamController(streamController: StreamController) {\n this.streamController = streamController;\n }\n\n public destroy() {\n if (this.hls) {\n this.unregisterListener();\n }\n if (this.timer) {\n this.stopCapping();\n }\n this.media = null;\n this.clientRect = null;\n // @ts-ignore\n this.hls = this.streamController = null;\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected unregisterListener() {\n const { hls } = this;\n hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected onFpsDropLevelCapping(\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData,\n ) {\n // Don't add a restricted level more than once\n const level = this.hls.levels[data.droppedLevel];\n if (this.isLevelAllowed(level)) {\n this.restrictedLevels.push({\n bitrate: level.bitrate,\n height: level.height,\n width: level.width,\n });\n }\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) {\n this.media = data.media instanceof HTMLVideoElement ? data.media : null;\n this.clientRect = null;\n if (this.timer && this.hls.levels.length) {\n this.detectPlayerSize();\n }\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData,\n ) {\n if (this.timer && Number.isFinite(this.autoLevelCapping)) {\n this.detectPlayerSize();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData,\n ) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n\n protected onMediaDetaching() {\n this.stopCapping();\n }\n\n detectPlayerSize() {\n if (this.media) {\n if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {\n this.clientRect = null;\n return;\n }\n const levels = this.hls.levels;\n if (levels.length) {\n const hls = this.hls;\n const maxLevel = this.getMaxLevel(levels.length - 1);\n if (maxLevel !== this.autoLevelCapping) {\n logger.log(\n `Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`,\n );\n }\n hls.autoLevelCapping = maxLevel;\n if (\n hls.autoLevelCapping > this.autoLevelCapping &&\n this.streamController\n ) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n this.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel(capLevelIndex: number): number {\n const levels = this.hls.levels;\n if (!levels.length) {\n return -1;\n }\n\n const validLevels = levels.filter(\n (level, index) => this.isLevelAllowed(level) && index <= capLevelIndex,\n );\n\n this.clientRect = null;\n return CapLevelController.getMaxLevelByMediaSize(\n validLevels,\n this.mediaWidth,\n this.mediaHeight,\n );\n }\n\n startCapping() {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n self.clearInterval(this.timer);\n this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n stopCapping() {\n this.restrictedLevels = [];\n this.firstLevel = -1;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n self.clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n\n getDimensions(): { width: number; height: number } {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0,\n };\n\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width =\n clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height =\n clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n\n get mediaWidth(): number {\n return this.getDimensions().width * this.contentScaleFactor;\n }\n\n get mediaHeight(): number {\n return this.getDimensions().height * this.contentScaleFactor;\n }\n\n get contentScaleFactor(): number {\n let pixelRatio = 1;\n if (!this.hls.config.ignoreDevicePixelRatio) {\n try {\n pixelRatio = self.devicePixelRatio;\n } catch (e) {\n /* no-op */\n }\n }\n\n return pixelRatio;\n }\n\n private isLevelAllowed(level: Level): boolean {\n const restrictedLevels = this.restrictedLevels;\n return !restrictedLevels.some((restrictedLevel) => {\n return (\n level.bitrate === restrictedLevel.bitrate &&\n level.width === restrictedLevel.width &&\n level.height === restrictedLevel.height\n );\n });\n }\n\n static getMaxLevelByMediaSize(\n levels: Array<Level>,\n width: number,\n height: number,\n ): number {\n if (!levels?.length) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandwidth = (\n curLevel: Level,\n nextLevel: Level | undefined,\n ) => {\n if (!nextLevel) {\n return true;\n }\n\n return (\n curLevel.width !== nextLevel.width ||\n curLevel.height !== nextLevel.height\n );\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n // Prevent changes in aspect-ratio from causing capping to toggle back and forth\n const squareSize = Math.max(width, height);\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if (\n (level.width >= squareSize || level.height >= squareSize) &&\n atGreatestBandwidth(level, levels[i + 1])\n ) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","import { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { MediaAttachingData } from '../types/events';\nimport StreamController from './stream-controller';\n\nclass FPSController implements ComponentAPI {\n private hls: Hls;\n private isVideoPlaybackQualityAvailable: boolean = false;\n private timer?: number;\n private media: HTMLVideoElement | null = null;\n private lastTime: any;\n private lastDroppedFrames: number = 0;\n private lastDecodedFrames: number = 0;\n // stream controller must be provided as a dependency!\n private streamController!: StreamController;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n this.registerListeners();\n }\n\n public setStreamController(streamController: StreamController) {\n this.streamController = streamController;\n }\n\n protected registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n }\n\n protected unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n }\n\n destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.unregisterListeners();\n this.isVideoPlaybackQualityAvailable = false;\n this.media = null;\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const media =\n data.media instanceof self.HTMLVideoElement ? data.media : null;\n this.media = media;\n if (media && typeof media.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n self.clearInterval(this.timer);\n this.timer = self.setInterval(\n this.checkFPSInterval.bind(this),\n config.fpsDroppedMonitoringPeriod,\n );\n }\n }\n\n checkFPS(\n video: HTMLVideoElement,\n decodedFrames: number,\n droppedFrames: number,\n ) {\n const currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n const currentPeriod = currentTime - this.lastTime;\n const currentDropped = droppedFrames - this.lastDroppedFrames;\n const currentDecoded = decodedFrames - this.lastDecodedFrames;\n const droppedFPS = (1000 * currentDropped) / currentPeriod;\n const hls = this.hls;\n hls.trigger(Events.FPS_DROP, {\n currentDropped: currentDropped,\n currentDecoded: currentDecoded,\n totalDroppedFrames: droppedFrames,\n });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (\n currentDropped >\n hls.config.fpsDroppedMonitoringThreshold * currentDecoded\n ) {\n let currentLevel = hls.currentLevel;\n logger.warn(\n 'drop FPS ratio greater than max allowed value for currentLevel: ' +\n currentLevel,\n );\n if (\n currentLevel > 0 &&\n (hls.autoLevelCapping === -1 ||\n hls.autoLevelCapping >= currentLevel)\n ) {\n currentLevel = currentLevel - 1;\n hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {\n level: currentLevel,\n droppedLevel: hls.currentLevel,\n });\n hls.autoLevelCapping = currentLevel;\n this.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval() {\n const video = this.media;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n const videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(\n video,\n videoPlaybackQuality.totalVideoFrames,\n videoPlaybackQuality.droppedVideoFrames,\n );\n } else {\n // HTMLVideoElement doesn't include the webkit types\n this.checkFPS(\n video,\n (video as any).webkitDecodedFrameCount as number,\n (video as any).webkitDroppedFrameCount as number,\n );\n }\n }\n }\n}\n\nexport default FPSController;\n","import { Events } from '../events';\nimport { Level } from '../types/level';\nimport { reassignFragmentLevelIndexes } from '../utils/level-helper';\nimport { AttrList } from '../utils/attr-list';\nimport { ErrorActionFlags, NetworkErrorAction } from './error-controller';\nimport { logger } from '../utils/logger';\nimport {\n PlaylistContextType,\n type Loader,\n type LoaderCallbacks,\n type LoaderConfiguration,\n type LoaderContext,\n type LoaderResponse,\n type LoaderStats,\n} from '../types/loader';\nimport type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type {\n SteeringManifestLoadedData,\n ErrorData,\n ManifestLoadedData,\n ManifestParsedData,\n} from '../types/events';\nimport type { RetryConfig } from '../config';\n\nimport type { MediaAttributes, MediaPlaylist } from '../types/media-playlist';\n\nexport type SteeringManifest = {\n VERSION: 1;\n TTL: number;\n 'RELOAD-URI'?: string;\n 'PATHWAY-PRIORITY': string[];\n 'PATHWAY-CLONES'?: PathwayClone[];\n};\n\nexport type PathwayClone = {\n 'BASE-ID': string;\n ID: string;\n 'URI-REPLACEMENT': UriReplacement;\n};\n\nexport type UriReplacement = {\n HOST?: string;\n PARAMS?: { [queryParameter: string]: string };\n 'PER-VARIANT-URIS'?: { [stableVariantId: string]: string };\n 'PER-RENDITION-URIS'?: { [stableRenditionId: string]: string };\n};\n\nconst PATHWAY_PENALTY_DURATION_MS = 300000;\n\nexport default class ContentSteeringController implements NetworkComponentAPI {\n private readonly hls: Hls;\n private log: (msg: any) => void;\n private loader: Loader<LoaderContext> | null = null;\n private uri: string | null = null;\n private pathwayId: string = '.';\n private pathwayPriority: string[] | null = null;\n private timeToLoad: number = 300;\n private reloadTimer: number = -1;\n private updated: number = 0;\n private started: boolean = false;\n private enabled: boolean = true;\n private levels: Level[] | null = null;\n private audioTracks: MediaPlaylist[] | null = null;\n private subtitleTracks: MediaPlaylist[] | null = null;\n private penalizedPathways: { [pathwayId: string]: number } = {};\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.log = logger.log.bind(logger, `[content-steering]:`);\n this.registerListeners();\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n startLoad() {\n this.started = true;\n this.clearTimeout();\n if (this.enabled && this.uri) {\n if (this.updated) {\n const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);\n if (ttl > 0) {\n this.scheduleRefresh(this.uri, ttl);\n return;\n }\n }\n this.loadSteeringManifest(this.uri);\n }\n }\n\n stopLoad() {\n this.started = false;\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n this.clearTimeout();\n }\n\n clearTimeout() {\n if (this.reloadTimer !== -1) {\n self.clearTimeout(this.reloadTimer);\n this.reloadTimer = -1;\n }\n }\n\n destroy() {\n this.unregisterListeners();\n this.stopLoad();\n // @ts-ignore\n this.hls = null;\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n\n removeLevel(levelToRemove: Level) {\n const levels = this.levels;\n if (levels) {\n this.levels = levels.filter((level) => level !== levelToRemove);\n }\n }\n\n private onManifestLoading() {\n this.stopLoad();\n this.enabled = true;\n this.timeToLoad = 300;\n this.updated = 0;\n this.uri = null;\n this.pathwayId = '.';\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ) {\n const { contentSteering } = data;\n if (contentSteering === null) {\n return;\n }\n this.pathwayId = contentSteering.pathwayId;\n this.uri = contentSteering.uri;\n if (this.started) {\n this.startLoad();\n }\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n this.audioTracks = data.audioTracks;\n this.subtitleTracks = data.subtitleTracks;\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n const { errorAction } = data;\n if (\n errorAction?.action === NetworkErrorAction.SendAlternateToPenaltyBox &&\n errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost\n ) {\n const levels = this.levels;\n let pathwayPriority = this.pathwayPriority;\n let errorPathway = this.pathwayId;\n if (data.context) {\n const { groupId, pathwayId, type } = data.context;\n if (groupId && levels) {\n errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);\n } else if (pathwayId) {\n errorPathway = pathwayId;\n }\n }\n if (!(errorPathway in this.penalizedPathways)) {\n this.penalizedPathways[errorPathway] = performance.now();\n }\n if (!pathwayPriority && levels) {\n // If PATHWAY-PRIORITY was not provided, list pathways for error handling\n pathwayPriority = levels.reduce((pathways, level) => {\n if (pathways.indexOf(level.pathwayId) === -1) {\n pathways.push(level.pathwayId);\n }\n return pathways;\n }, [] as string[]);\n }\n if (pathwayPriority && pathwayPriority.length > 1) {\n this.updatePathwayPriority(pathwayPriority);\n errorAction.resolved = this.pathwayId !== errorPathway;\n }\n if (!errorAction.resolved) {\n logger.warn(\n `Could not resolve ${data.details} (\"${\n data.error.message\n }\") with content-steering for Pathway: ${errorPathway} levels: ${\n levels ? levels.length : levels\n } priorities: ${JSON.stringify(\n pathwayPriority,\n )} penalized: ${JSON.stringify(this.penalizedPathways)}`,\n );\n }\n }\n }\n\n public filterParsedLevels(levels: Level[]): Level[] {\n // Filter levels to only include those that are in the initial pathway\n this.levels = levels;\n let pathwayLevels = this.getLevelsForPathway(this.pathwayId);\n if (pathwayLevels.length === 0) {\n const pathwayId = levels[0].pathwayId;\n this.log(\n `No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to \"${pathwayId}\"`,\n );\n pathwayLevels = this.getLevelsForPathway(pathwayId);\n this.pathwayId = pathwayId;\n }\n if (pathwayLevels.length !== levels.length) {\n this.log(\n `Found ${pathwayLevels.length}/${levels.length} levels in Pathway \"${this.pathwayId}\"`,\n );\n return pathwayLevels;\n }\n return levels;\n }\n\n private getLevelsForPathway(pathwayId: string): Level[] {\n if (this.levels === null) {\n return [];\n }\n return this.levels.filter((level) => pathwayId === level.pathwayId);\n }\n\n private updatePathwayPriority(pathwayPriority: string[]) {\n this.pathwayPriority = pathwayPriority;\n let levels: Level[] | undefined;\n\n // Evaluate if we should remove the pathway from the penalized list\n const penalizedPathways = this.penalizedPathways;\n const now = performance.now();\n Object.keys(penalizedPathways).forEach((pathwayId) => {\n if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {\n delete penalizedPathways[pathwayId];\n }\n });\n for (let i = 0; i < pathwayPriority.length; i++) {\n const pathwayId = pathwayPriority[i];\n if (pathwayId in penalizedPathways) {\n continue;\n }\n if (pathwayId === this.pathwayId) {\n return;\n }\n const selectedIndex = this.hls.nextLoadLevel;\n const selectedLevel: Level = this.hls.levels[selectedIndex];\n levels = this.getLevelsForPathway(pathwayId);\n if (levels.length > 0) {\n this.log(`Setting Pathway to \"${pathwayId}\"`);\n this.pathwayId = pathwayId;\n reassignFragmentLevelIndexes(levels);\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed\n const levelAfterChange = this.hls.levels[selectedIndex];\n if (selectedLevel && levelAfterChange && this.levels) {\n if (\n levelAfterChange.attrs['STABLE-VARIANT-ID'] !==\n selectedLevel.attrs['STABLE-VARIANT-ID'] &&\n levelAfterChange.bitrate !== selectedLevel.bitrate\n ) {\n this.log(\n `Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`,\n );\n }\n this.hls.nextLoadLevel = selectedIndex;\n }\n break;\n }\n }\n }\n\n private getPathwayForGroupId(\n groupId: string,\n type: PlaylistContextType,\n defaultPathway: string,\n ): string {\n const levels = this.getLevelsForPathway(defaultPathway).concat(\n this.levels || [],\n );\n for (let i = 0; i < levels.length; i++) {\n if (\n (type === PlaylistContextType.AUDIO_TRACK &&\n levels[i].hasAudioGroup(groupId)) ||\n (type === PlaylistContextType.SUBTITLE_TRACK &&\n levels[i].hasSubtitleGroup(groupId))\n ) {\n return levels[i].pathwayId;\n }\n }\n return defaultPathway;\n }\n\n private clonePathways(pathwayClones: PathwayClone[]) {\n const levels = this.levels;\n if (!levels) {\n return;\n }\n const audioGroupCloneMap: Record<string, string> = {};\n const subtitleGroupCloneMap: Record<string, string> = {};\n pathwayClones.forEach((pathwayClone) => {\n const {\n ID: cloneId,\n 'BASE-ID': baseId,\n 'URI-REPLACEMENT': uriReplacement,\n } = pathwayClone;\n if (levels.some((level) => level.pathwayId === cloneId)) {\n return;\n }\n const clonedVariants = this.getLevelsForPathway(baseId).map(\n (baseLevel) => {\n const attributes = new AttrList(baseLevel.attrs);\n attributes['PATHWAY-ID'] = cloneId;\n const clonedAudioGroupId: string | undefined =\n attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;\n const clonedSubtitleGroupId: string | undefined =\n attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;\n if (clonedAudioGroupId) {\n audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;\n attributes.AUDIO = clonedAudioGroupId;\n }\n if (clonedSubtitleGroupId) {\n subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;\n attributes.SUBTITLES = clonedSubtitleGroupId;\n }\n const url = performUriReplacement(\n baseLevel.uri,\n attributes['STABLE-VARIANT-ID'],\n 'PER-VARIANT-URIS',\n uriReplacement,\n );\n const clonedLevel = new Level({\n attrs: attributes,\n audioCodec: baseLevel.audioCodec,\n bitrate: baseLevel.bitrate,\n height: baseLevel.height,\n name: baseLevel.name,\n url,\n videoCodec: baseLevel.videoCodec,\n width: baseLevel.width,\n });\n if (baseLevel.audioGroups) {\n for (let i = 1; i < baseLevel.audioGroups.length; i++) {\n clonedLevel.addGroupId(\n 'audio',\n `${baseLevel.audioGroups[i]}_clone_${cloneId}`,\n );\n }\n }\n if (baseLevel.subtitleGroups) {\n for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {\n clonedLevel.addGroupId(\n 'text',\n `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`,\n );\n }\n }\n return clonedLevel;\n },\n );\n levels.push(...clonedVariants);\n cloneRenditionGroups(\n this.audioTracks,\n audioGroupCloneMap,\n uriReplacement,\n cloneId,\n );\n cloneRenditionGroups(\n this.subtitleTracks,\n subtitleGroupCloneMap,\n uriReplacement,\n cloneId,\n );\n });\n }\n\n private loadSteeringManifest(uri: string) {\n const config = this.hls.config;\n const Loader = config.loader;\n if (this.loader) {\n this.loader.destroy();\n }\n this.loader = new Loader(config) as Loader<LoaderContext>;\n\n let url: URL;\n try {\n url = new self.URL(uri);\n } catch (error) {\n this.enabled = false;\n this.log(`Failed to parse Steering Manifest URI: ${uri}`);\n return;\n }\n if (url.protocol !== 'data:') {\n const throughput =\n (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;\n url.searchParams.set('_HLS_pathway', this.pathwayId);\n url.searchParams.set('_HLS_throughput', '' + throughput);\n }\n const context: LoaderContext = {\n responseType: 'json',\n url: url.href,\n };\n\n const loadPolicy = config.steeringManifestLoadPolicy.default;\n const legacyRetryCompatibility: RetryConfig | Record<string, void> =\n loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0,\n };\n\n const callbacks: LoaderCallbacks<LoaderContext> = {\n onSuccess: (\n response: LoaderResponse,\n stats: LoaderStats,\n context: LoaderContext,\n networkDetails: any,\n ) => {\n this.log(`Loaded steering manifest: \"${url}\"`);\n const steeringData = response.data as SteeringManifest;\n if (steeringData.VERSION !== 1) {\n this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);\n return;\n }\n this.updated = performance.now();\n this.timeToLoad = steeringData.TTL;\n const {\n 'RELOAD-URI': reloadUri,\n 'PATHWAY-CLONES': pathwayClones,\n 'PATHWAY-PRIORITY': pathwayPriority,\n } = steeringData;\n if (reloadUri) {\n try {\n this.uri = new self.URL(reloadUri, url).href;\n } catch (error) {\n this.enabled = false;\n this.log(\n `Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`,\n );\n return;\n }\n }\n this.scheduleRefresh(this.uri || context.url);\n if (pathwayClones) {\n this.clonePathways(pathwayClones);\n }\n\n const loadedSteeringData: SteeringManifestLoadedData = {\n steeringManifest: steeringData,\n url: url.toString(),\n };\n this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);\n\n if (pathwayPriority) {\n this.updatePathwayPriority(pathwayPriority);\n }\n },\n\n onError: (\n error: { code: number; text: string },\n context: LoaderContext,\n networkDetails: any,\n stats: LoaderStats,\n ) => {\n this.log(\n `Error loading steering manifest: ${error.code} ${error.text} (${context.url})`,\n );\n this.stopLoad();\n if (error.code === 410) {\n this.enabled = false;\n this.log(`Steering manifest ${context.url} no longer available`);\n return;\n }\n let ttl = this.timeToLoad * 1000;\n if (error.code === 429) {\n const loader = this.loader;\n if (typeof loader?.getResponseHeader === 'function') {\n const retryAfter = loader.getResponseHeader('Retry-After');\n if (retryAfter) {\n ttl = parseFloat(retryAfter) * 1000;\n }\n }\n this.log(`Steering manifest ${context.url} rate limited`);\n return;\n }\n this.scheduleRefresh(this.uri || context.url, ttl);\n },\n\n onTimeout: (\n stats: LoaderStats,\n context: LoaderContext,\n networkDetails: any,\n ) => {\n this.log(`Timeout loading steering manifest (${context.url})`);\n this.scheduleRefresh(this.uri || context.url);\n },\n };\n\n this.log(`Requesting steering manifest: ${url}`);\n this.loader.load(context, loaderConfig, callbacks);\n }\n\n private scheduleRefresh(uri: string, ttlMs: number = this.timeToLoad * 1000) {\n this.clearTimeout();\n this.reloadTimer = self.setTimeout(() => {\n const media = this.hls?.media;\n if (media && !media.ended) {\n this.loadSteeringManifest(uri);\n return;\n }\n this.scheduleRefresh(uri, this.timeToLoad * 1000);\n }, ttlMs);\n }\n}\n\nfunction cloneRenditionGroups(\n tracks: MediaPlaylist[] | null,\n groupCloneMap: Record<string, string>,\n uriReplacement: UriReplacement,\n cloneId: string,\n) {\n if (!tracks) {\n return;\n }\n Object.keys(groupCloneMap).forEach((audioGroupId) => {\n const clonedTracks = tracks\n .filter((track) => track.groupId === audioGroupId)\n .map((track) => {\n const clonedTrack = Object.assign({}, track);\n clonedTrack.details = undefined;\n clonedTrack.attrs = new AttrList(clonedTrack.attrs) as MediaAttributes;\n clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(\n track.url,\n track.attrs['STABLE-RENDITION-ID'],\n 'PER-RENDITION-URIS',\n uriReplacement,\n );\n clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] =\n groupCloneMap[audioGroupId];\n clonedTrack.attrs['PATHWAY-ID'] = cloneId;\n return clonedTrack;\n });\n tracks.push(...clonedTracks);\n });\n}\n\nfunction performUriReplacement(\n uri: string,\n stableId: string | undefined,\n perOptionKey: 'PER-VARIANT-URIS' | 'PER-RENDITION-URIS',\n uriReplacement: UriReplacement,\n): string {\n const {\n HOST: host,\n PARAMS: params,\n [perOptionKey]: perOptionUris,\n } = uriReplacement;\n let perVariantUri;\n if (stableId) {\n perVariantUri = perOptionUris?.[stableId];\n if (perVariantUri) {\n uri = perVariantUri;\n }\n }\n const url = new self.URL(uri);\n if (host && !perVariantUri) {\n url.host = host;\n }\n if (params) {\n Object.keys(params)\n .sort()\n .forEach((key) => {\n if (key) {\n url.searchParams.set(key, params[key]);\n }\n });\n }\n return url.href;\n}\n","import { logger } from '../utils/logger';\nimport type {\n LoaderCallbacks,\n LoaderContext,\n LoaderStats,\n Loader,\n LoaderConfiguration,\n LoaderResponse,\n} from '../types/loader';\nimport { LoadStats } from '../loader/load-stats';\nimport { type HlsConfig, RetryConfig } from '../config';\nimport { getRetryDelay, shouldRetry } from './error-helper';\n\nconst AGE_HEADER_LINE_REGEX = /^age:\\s*[\\d.]+\\s*$/im;\n\nclass XhrLoader implements Loader<LoaderContext> {\n private xhrSetup:\n | ((xhr: XMLHttpRequest, url: string) => Promise<void> | void)\n | null;\n private requestTimeout?: number;\n private retryTimeout?: number;\n private retryDelay: number;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public context: LoaderContext | null = null;\n\n private loader: XMLHttpRequest | null = null;\n public stats: LoaderStats;\n\n constructor(config: HlsConfig) {\n this.xhrSetup = config ? config.xhrSetup || null : null;\n this.stats = new LoadStats();\n this.retryDelay = 0;\n }\n\n destroy() {\n this.callbacks = null;\n this.abortInternal();\n this.loader = null;\n this.config = null;\n this.context = null;\n this.xhrSetup = null;\n }\n\n abortInternal() {\n const loader = this.loader;\n self.clearTimeout(this.requestTimeout);\n self.clearTimeout(this.retryTimeout);\n if (loader) {\n loader.onreadystatechange = null;\n loader.onprogress = null;\n if (loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n }\n }\n\n abort() {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(\n this.stats,\n this.context as LoaderContext,\n this.loader,\n );\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>,\n ) {\n if (this.stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n this.stats.loading.start = self.performance.now();\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.loadInternal();\n }\n\n loadInternal() {\n const { config, context } = this;\n if (!config || !context) {\n return;\n }\n const xhr = (this.loader = new self.XMLHttpRequest());\n\n const stats = this.stats;\n stats.loading.first = 0;\n stats.loaded = 0;\n stats.aborted = false;\n const xhrSetup = this.xhrSetup;\n\n if (xhrSetup) {\n Promise.resolve()\n .then(() => {\n if (this.loader !== xhr || this.stats.aborted) return;\n return xhrSetup(xhr, context.url);\n })\n .catch((error: Error) => {\n if (this.loader !== xhr || this.stats.aborted) return;\n xhr.open('GET', context.url, true);\n return xhrSetup(xhr, context.url);\n })\n .then(() => {\n if (this.loader !== xhr || this.stats.aborted) return;\n this.openAndSendXhr(xhr, context, config);\n })\n .catch((error: Error) => {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks!.onError(\n { code: xhr.status, text: error.message },\n context,\n xhr,\n stats,\n );\n return;\n });\n } else {\n this.openAndSendXhr(xhr, context, config);\n }\n }\n\n openAndSendXhr(\n xhr: XMLHttpRequest,\n context: LoaderContext,\n config: LoaderConfiguration,\n ) {\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n\n const headers = context.headers;\n const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy;\n if (headers) {\n for (const header in headers) {\n xhr.setRequestHeader(header, headers[header]);\n }\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader(\n 'Range',\n 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1),\n );\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType as XMLHttpRequestResponseType;\n // setup timeout before we perform request\n self.clearTimeout(this.requestTimeout);\n config.timeout =\n maxTimeToFirstByteMs && Number.isFinite(maxTimeToFirstByteMs)\n ? maxTimeToFirstByteMs\n : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.timeout,\n );\n xhr.send();\n }\n\n readystatechange() {\n const { context, loader: xhr, stats } = this;\n if (!context || !xhr) {\n return;\n }\n const readyState = xhr.readyState;\n const config = this.config as LoaderConfiguration;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n if (stats.loading.first === 0) {\n stats.loading.first = Math.max(\n self.performance.now(),\n stats.loading.start,\n );\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {\n self.clearTimeout(this.requestTimeout);\n config.timeout = config.loadPolicy.maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.loadPolicy.maxLoadTimeMs -\n (stats.loading.first - stats.loading.start),\n );\n }\n }\n\n if (readyState === 4) {\n self.clearTimeout(this.requestTimeout);\n xhr.onreadystatechange = null;\n xhr.onprogress = null;\n const status = xhr.status;\n // http status between 200 to 299 are all successful\n const useResponse = xhr.responseType !== 'text';\n if (\n status >= 200 &&\n status < 300 &&\n ((useResponse && xhr.response) || xhr.responseText !== null)\n ) {\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first,\n );\n const data = useResponse ? xhr.response : xhr.responseText;\n const len =\n xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;\n stats.loaded = stats.total = len;\n stats.bwEstimate =\n (stats.total * 8000) / (stats.loading.end - stats.loading.first);\n if (!this.callbacks) {\n return;\n }\n const onProgress = this.callbacks.onProgress;\n if (onProgress) {\n onProgress(stats, context, data, xhr);\n }\n if (!this.callbacks) {\n return;\n }\n const response: LoaderResponse = {\n url: xhr.responseURL,\n data: data,\n code: status,\n };\n\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n const retryConfig = config.loadPolicy.errorRetry;\n const retryCount = stats.retry;\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n const response: LoaderResponse = {\n url: context.url,\n data: undefined,\n code: status,\n };\n if (shouldRetry(retryConfig, retryCount, false, response)) {\n this.retry(retryConfig);\n } else {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks!.onError(\n { code: status, text: xhr.statusText },\n context,\n xhr,\n stats,\n );\n }\n }\n }\n }\n }\n\n loadtimeout() {\n if (!this.config) return;\n const retryConfig = this.config.loadPolicy.timeoutRetry;\n const retryCount = this.stats.retry;\n if (shouldRetry(retryConfig, retryCount, true)) {\n this.retry(retryConfig);\n } else {\n logger.warn(`timeout while loading ${this.context?.url}`);\n const callbacks = this.callbacks;\n if (callbacks) {\n this.abortInternal();\n callbacks.onTimeout(\n this.stats,\n this.context as LoaderContext,\n this.loader,\n );\n }\n }\n }\n\n retry(retryConfig: RetryConfig) {\n const { context, stats } = this;\n this.retryDelay = getRetryDelay(retryConfig, stats.retry);\n stats.retry++;\n logger.warn(\n `${\n status ? 'HTTP Status ' + status : 'Timeout'\n } while loading ${context?.url}, retrying ${stats.retry}/${\n retryConfig.maxNumRetry\n } in ${this.retryDelay}ms`,\n );\n // abort and reset internal state\n this.abortInternal();\n this.loader = null;\n // schedule retry\n self.clearTimeout(this.retryTimeout);\n this.retryTimeout = self.setTimeout(\n this.loadInternal.bind(this),\n this.retryDelay,\n );\n }\n\n loadprogress(event: ProgressEvent) {\n const stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n }\n\n getCacheAge(): number | null {\n let result: number | null = null;\n if (\n this.loader &&\n AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())\n ) {\n const ageHeader = this.loader.getResponseHeader('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n\n getResponseHeader(name: string): string | null {\n if (\n this.loader &&\n new RegExp(`^${name}:\\\\s*[\\\\d.]+\\\\s*$`, 'im').test(\n this.loader.getAllResponseHeaders(),\n )\n ) {\n return this.loader.getResponseHeader(name);\n }\n return null;\n }\n}\n\nexport default XhrLoader;\n","export default class ChunkCache {\n private chunks: Array<Uint8Array> = [];\n public dataLength: number = 0;\n\n push(chunk: Uint8Array) {\n this.chunks.push(chunk);\n this.dataLength += chunk.length;\n }\n\n flush(): Uint8Array {\n const { chunks, dataLength } = this;\n let result;\n if (!chunks.length) {\n return new Uint8Array(0);\n } else if (chunks.length === 1) {\n result = chunks[0];\n } else {\n result = concatUint8Arrays(chunks, dataLength);\n }\n this.reset();\n return result;\n }\n\n reset() {\n this.chunks.length = 0;\n this.dataLength = 0;\n }\n}\n\nfunction concatUint8Arrays(\n chunks: Array<Uint8Array>,\n dataLength: number,\n): Uint8Array {\n const result = new Uint8Array(dataLength);\n let offset = 0;\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n","import {\n LoaderCallbacks,\n LoaderContext,\n Loader,\n LoaderStats,\n LoaderConfiguration,\n LoaderOnProgress,\n LoaderResponse,\n} from '../types/loader';\nimport { LoadStats } from '../loader/load-stats';\nimport ChunkCache from '../demux/chunk-cache';\n\nexport function fetchSupported() {\n if (\n // @ts-ignore\n self.fetch &&\n self.AbortController &&\n self.ReadableStream &&\n self.Request\n ) {\n try {\n new self.ReadableStream({}); // eslint-disable-line no-new\n return true;\n } catch (e) {\n /* noop */\n }\n }\n return false;\n}\n\nconst BYTERANGE = /(\\d+)-(\\d+)\\/(\\d+)/;\n\nclass FetchLoader implements Loader<LoaderContext> {\n private fetchSetup: Function;\n private requestTimeout?: number;\n private request: Request | null = null;\n private response: Response | null = null;\n private controller: AbortController;\n public context: LoaderContext | null = null;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public stats: LoaderStats;\n private loader: Response | null = null;\n\n constructor(config /* HlsConfig */) {\n this.fetchSetup = config.fetchSetup || getRequest;\n this.controller = new self.AbortController();\n this.stats = new LoadStats();\n }\n\n destroy(): void {\n this.loader =\n this.callbacks =\n this.context =\n this.config =\n this.request =\n null;\n this.abortInternal();\n this.response = null;\n // @ts-ignore\n this.fetchSetup = this.controller = this.stats = null;\n }\n\n abortInternal(): void {\n if (this.controller && !this.stats.loading.end) {\n this.stats.aborted = true;\n this.controller.abort();\n }\n }\n\n abort(): void {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(\n this.stats,\n this.context as LoaderContext,\n this.response,\n );\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>,\n ): void {\n const stats = this.stats;\n if (stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n stats.loading.start = self.performance.now();\n\n const initParams = getRequestParameters(context, this.controller.signal);\n const onProgress: LoaderOnProgress<LoaderContext> | undefined =\n callbacks.onProgress;\n const isArrayBuffer = context.responseType === 'arraybuffer';\n const LENGTH = isArrayBuffer ? 'byteLength' : 'length';\n const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy;\n\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.request = this.fetchSetup(context, initParams);\n self.clearTimeout(this.requestTimeout);\n config.timeout =\n maxTimeToFirstByteMs && Number.isFinite(maxTimeToFirstByteMs)\n ? maxTimeToFirstByteMs\n : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(() => {\n this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n }, config.timeout);\n\n self\n .fetch(this.request as Request)\n .then((response: Response): Promise<string | ArrayBuffer> => {\n this.response = this.loader = response;\n\n const first = Math.max(self.performance.now(), stats.loading.start);\n\n self.clearTimeout(this.requestTimeout);\n config.timeout = maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n () => {\n this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n },\n maxLoadTimeMs - (first - stats.loading.start),\n );\n\n if (!response.ok) {\n const { status, statusText } = response;\n throw new FetchError(\n statusText || 'fetch, bad network response',\n status,\n response,\n );\n }\n stats.loading.first = first;\n\n stats.total = getContentLength(response.headers) || stats.total;\n\n if (onProgress && Number.isFinite(config.highWaterMark)) {\n return this.loadProgressively(\n response,\n stats,\n context,\n config.highWaterMark,\n onProgress,\n );\n }\n\n if (isArrayBuffer) {\n return response.arrayBuffer();\n }\n if (context.responseType === 'json') {\n return response.json();\n }\n return response.text();\n })\n .then((responseData: string | ArrayBuffer) => {\n const response = this.response;\n if (!response) {\n throw new Error('loader destroyed');\n }\n self.clearTimeout(this.requestTimeout);\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first,\n );\n const total = responseData[LENGTH];\n if (total) {\n stats.loaded = stats.total = total;\n }\n\n const loaderResponse: LoaderResponse = {\n url: response.url,\n data: responseData,\n code: response.status,\n };\n\n if (onProgress && !Number.isFinite(config.highWaterMark)) {\n onProgress(stats, context, responseData, response);\n }\n\n callbacks.onSuccess(loaderResponse, stats, context, response);\n })\n .catch((error) => {\n self.clearTimeout(this.requestTimeout);\n if (stats.aborted) {\n return;\n }\n // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior\n // when destroying, 'error' itself can be undefined\n const code: number = !error ? 0 : error.code || 0;\n const text: string = !error ? null : error.message;\n callbacks.onError(\n { code, text },\n context,\n error ? error.details : null,\n stats,\n );\n });\n }\n\n getCacheAge(): number | null {\n let result: number | null = null;\n if (this.response) {\n const ageHeader = this.response.headers.get('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n\n getResponseHeader(name: string): string | null {\n return this.response ? this.response.headers.get(name) : null;\n }\n\n private loadProgressively(\n response: Response,\n stats: LoaderStats,\n context: LoaderContext,\n highWaterMark: number = 0,\n onProgress: LoaderOnProgress<LoaderContext>,\n ): Promise<ArrayBuffer> {\n const chunkCache = new ChunkCache();\n const reader = (response.body as ReadableStream).getReader();\n\n const pump = (): Promise<ArrayBuffer> => {\n return reader\n .read()\n .then((data) => {\n if (data.done) {\n if (chunkCache.dataLength) {\n onProgress(stats, context, chunkCache.flush(), response);\n }\n\n return Promise.resolve(new ArrayBuffer(0));\n }\n const chunk: Uint8Array = data.value;\n const len = chunk.length;\n stats.loaded += len;\n if (len < highWaterMark || chunkCache.dataLength) {\n // The current chunk is too small to to be emitted or the cache already has data\n // Push it to the cache\n chunkCache.push(chunk);\n if (chunkCache.dataLength >= highWaterMark) {\n // flush in order to join the typed arrays\n onProgress(stats, context, chunkCache.flush(), response);\n }\n } else {\n // If there's nothing cached already, and the chache is large enough\n // just emit the progress event\n onProgress(stats, context, chunk, response);\n }\n return pump();\n })\n .catch(() => {\n /* aborted */\n return Promise.reject();\n });\n };\n\n return pump();\n }\n}\n\nfunction getRequestParameters(context: LoaderContext, signal): any {\n const initParams: any = {\n method: 'GET',\n mode: 'cors',\n credentials: 'same-origin',\n signal,\n headers: new self.Headers(Object.assign({}, context.headers)),\n };\n\n if (context.rangeEnd) {\n initParams.headers.set(\n 'Range',\n 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1),\n );\n }\n\n return initParams;\n}\n\nfunction getByteRangeLength(byteRangeHeader: string): number | undefined {\n const result = BYTERANGE.exec(byteRangeHeader);\n if (result) {\n return parseInt(result[2]) - parseInt(result[1]) + 1;\n }\n}\n\nfunction getContentLength(headers: Headers): number | undefined {\n const contentRange = headers.get('Content-Range');\n if (contentRange) {\n const byteRangeLength = getByteRangeLength(contentRange);\n if (Number.isFinite(byteRangeLength)) {\n return byteRangeLength;\n }\n }\n const contentLength = headers.get('Content-Length');\n if (contentLength) {\n return parseInt(contentLength);\n }\n}\n\nfunction getRequest(context: LoaderContext, initParams: any): Request {\n return new self.Request(context.url, initParams);\n}\n\nclass FetchError extends Error {\n public code: number;\n public details: any;\n constructor(message: string, code: number, details: any) {\n super(message);\n this.code = code;\n this.details = details;\n }\n}\n\nexport default FetchLoader;\n","import {\n ManifestLoadedData,\n ManifestParsedData,\n LevelLoadedData,\n ErrorData,\n LevelSwitchingData,\n LevelsUpdatedData,\n ManifestLoadingData,\n FragBufferedData,\n} from '../types/events';\nimport { Level, VideoRangeValues, isVideoRange } from '../types/level';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport {\n areCodecsMediaSourceSupported,\n codecsSetSelectionPreferenceValue,\n convertAVC1ToAVCOTI,\n getCodecCompatibleName,\n videoCodecPreferenceValue,\n} from '../utils/codecs';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport ContentSteeringController from './content-steering-controller';\nimport { reassignFragmentLevelIndexes } from '../utils/level-helper';\nimport { hlsDefaultConfig } from '../config';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters, LevelParsed } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nlet chromeOrFirefox: boolean;\n\nexport default class LevelController extends BasePlaylistController {\n private _levels: Level[] = [];\n private _firstLevel: number = -1;\n private _maxAutoLevel: number = -1;\n private _startLevel?: number;\n private currentLevel: Level | null = null;\n private currentLevelIndex: number = -1;\n private manualLevelIndex: number = -1;\n private steering: ContentSteeringController | null;\n\n public onParsedComplete!: Function;\n\n constructor(\n hls: Hls,\n contentSteeringController: ContentSteeringController | null,\n ) {\n super(hls, '[level-controller]');\n this.steering = contentSteeringController;\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this._unregisterListeners();\n this.steering = null;\n this.resetLevels();\n super.destroy();\n }\n\n public stopLoad(): void {\n const levels = this._levels;\n\n // clean up live level details to force reload them, and reset load errors\n levels.forEach((level) => {\n level.loadError = 0;\n level.fragmentError = 0;\n });\n\n super.stopLoad();\n }\n\n private resetLevels() {\n this._startLevel = undefined;\n this.manualLevelIndex = -1;\n this.currentLevelIndex = -1;\n this.currentLevel = null;\n this._levels = [];\n this._maxAutoLevel = -1;\n }\n\n private onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) {\n this.resetLevels();\n }\n\n protected onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ) {\n const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;\n const levels: Level[] = [];\n const redundantSet: { [key: string]: Level } = {};\n const generatePathwaySet: { [key: string]: number } = {};\n let resolutionFound = false;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n data.levels.forEach((levelParsed: LevelParsed) => {\n const attributes = levelParsed.attrs;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n let { audioCodec, videoCodec } = levelParsed;\n if (audioCodec?.indexOf('mp4a.40.34') !== -1) {\n chromeOrFirefox ||= /chrome|firefox/i.test(navigator.userAgent);\n if (chromeOrFirefox) {\n levelParsed.audioCodec = audioCodec = undefined;\n }\n }\n\n if (audioCodec) {\n levelParsed.audioCodec = audioCodec = getCodecCompatibleName(\n audioCodec,\n preferManagedMediaSource,\n );\n }\n\n if (videoCodec?.indexOf('avc1') === 0) {\n videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n const { width, height, unknownCodecs } = levelParsed;\n resolutionFound ||= !!(width && height);\n videoCodecFound ||= !!videoCodec;\n audioCodecFound ||= !!audioCodec;\n if (\n unknownCodecs?.length ||\n (audioCodec &&\n !areCodecsMediaSourceSupported(\n audioCodec,\n 'audio',\n preferManagedMediaSource,\n )) ||\n (videoCodec &&\n !areCodecsMediaSourceSupported(\n videoCodec,\n 'video',\n preferManagedMediaSource,\n ))\n ) {\n return;\n }\n\n const {\n CODECS,\n 'FRAME-RATE': FRAMERATE,\n 'HDCP-LEVEL': HDCP,\n 'PATHWAY-ID': PATHWAY,\n RESOLUTION,\n 'VIDEO-RANGE': VIDEO_RANGE,\n } = attributes;\n const contentSteeringPrefix = `${PATHWAY || '.'}-`;\n const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;\n\n if (!redundantSet[levelKey]) {\n const level = new Level(levelParsed);\n redundantSet[levelKey] = level;\n generatePathwaySet[levelKey] = 1;\n levels.push(level);\n } else if (\n redundantSet[levelKey].uri !== levelParsed.url &&\n !levelParsed.attrs['PATHWAY-ID']\n ) {\n // Assign Pathway IDs to Redundant Streams (default Pathways is \".\". Redundant Streams \"..\", \"...\", and so on.)\n // Content Steering controller to handles Pathway fallback on error\n const pathwayCount = (generatePathwaySet[levelKey] += 1);\n levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');\n const level = new Level(levelParsed);\n redundantSet[levelKey] = level;\n levels.push(level);\n } else {\n redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);\n redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);\n }\n });\n\n this.filterAndSortMediaOptions(\n levels,\n data,\n resolutionFound,\n videoCodecFound,\n audioCodecFound,\n );\n }\n\n private filterAndSortMediaOptions(\n filteredLevels: Level[],\n data: ManifestLoadedData,\n resolutionFound: boolean,\n videoCodecFound: boolean,\n audioCodecFound: boolean,\n ) {\n let audioTracks: MediaPlaylist[] = [];\n let subtitleTracks: MediaPlaylist[] = [];\n let levels = filteredLevels;\n\n // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled\n if ((resolutionFound || videoCodecFound) && audioCodecFound) {\n levels = levels.filter(\n ({ videoCodec, videoRange, width, height }) =>\n (!!videoCodec || !!(width && height)) && isVideoRange(videoRange),\n );\n }\n\n if (levels.length === 0) {\n // Dispatch error after MANIFEST_LOADED is done propagating\n Promise.resolve().then(() => {\n if (this.hls) {\n if (data.levels.length) {\n this.warn(\n `One or more CODECS in variant not supported: ${JSON.stringify(\n data.levels[0].attrs,\n )}`,\n );\n }\n const error = new Error(\n 'no level with compatible codecs found in manifest',\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: data.url,\n error,\n reason: error.message,\n });\n }\n });\n return;\n }\n\n if (data.audioTracks) {\n const { preferManagedMediaSource } = this.hls.config;\n audioTracks = data.audioTracks.filter(\n (track) =>\n !track.audioCodec ||\n areCodecsMediaSourceSupported(\n track.audioCodec,\n 'audio',\n preferManagedMediaSource,\n ),\n );\n // Assign ids after filtering as array indices by group-id\n assignTrackIdsByGroup(audioTracks);\n }\n\n if (data.subtitles) {\n subtitleTracks = data.subtitles;\n assignTrackIdsByGroup(subtitleTracks);\n }\n // start bitrate is the first bitrate of the manifest\n const unsortedLevels = levels.slice(0);\n // sort levels from lowest to highest\n levels.sort((a, b) => {\n if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {\n return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '')\n ? 1\n : -1;\n }\n // sort on height before bitrate for cap-level-controller\n if (resolutionFound && a.height !== b.height) {\n return a.height - b.height;\n }\n if (a.frameRate !== b.frameRate) {\n return a.frameRate - b.frameRate;\n }\n if (a.videoRange !== b.videoRange) {\n return (\n VideoRangeValues.indexOf(a.videoRange) -\n VideoRangeValues.indexOf(b.videoRange)\n );\n }\n if (a.videoCodec !== b.videoCodec) {\n const valueA = videoCodecPreferenceValue(a.videoCodec);\n const valueB = videoCodecPreferenceValue(b.videoCodec);\n if (valueA !== valueB) {\n return valueB - valueA;\n }\n }\n if (a.uri === b.uri && a.codecSet !== b.codecSet) {\n const valueA = codecsSetSelectionPreferenceValue(a.codecSet);\n const valueB = codecsSetSelectionPreferenceValue(b.codecSet);\n if (valueA !== valueB) {\n return valueB - valueA;\n }\n }\n if (a.averageBitrate !== b.averageBitrate) {\n return a.averageBitrate - b.averageBitrate;\n }\n return 0;\n });\n\n let firstLevelInPlaylist = unsortedLevels[0];\n if (this.steering) {\n levels = this.steering.filterParsedLevels(levels);\n if (levels.length !== unsortedLevels.length) {\n for (let i = 0; i < unsortedLevels.length; i++) {\n if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {\n firstLevelInPlaylist = unsortedLevels[i];\n break;\n }\n }\n }\n }\n\n this._levels = levels;\n\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i] === firstLevelInPlaylist) {\n this._firstLevel = i;\n const firstLevelBitrate = firstLevelInPlaylist.bitrate;\n const bandwidthEstimate = this.hls.bandwidthEstimate;\n this.log(\n `manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`,\n );\n // Update default bwe to first variant bitrate as long it has not been configured or set\n if (this.hls.userConfig?.abrEwmaDefaultEstimate === undefined) {\n const startingBwEstimate = Math.min(\n firstLevelBitrate,\n this.hls.config.abrEwmaDefaultEstimateMax,\n );\n if (\n startingBwEstimate > bandwidthEstimate &&\n bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate\n ) {\n this.hls.bandwidthEstimate = startingBwEstimate;\n }\n }\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag,\n // and this is not an audio-only stream where levels contain audio-only\n const audioOnly = audioCodecFound && !videoCodecFound;\n const edata: ManifestParsedData = {\n levels,\n audioTracks,\n subtitleTracks,\n sessionData: data.sessionData,\n sessionKeys: data.sessionKeys,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: !audioOnly && audioTracks.some((t) => !!t.url),\n };\n this.hls.trigger(Events.MANIFEST_PARSED, edata);\n\n // Initiate loading after all controllers have received MANIFEST_PARSED\n if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {\n this.hls.startLoad(this.hls.config.startPosition);\n }\n }\n\n get levels(): Level[] | null {\n if (this._levels.length === 0) {\n return null;\n }\n return this._levels;\n }\n\n get level(): number {\n return this.currentLevelIndex;\n }\n\n set level(newLevel: number) {\n const levels = this._levels;\n if (levels.length === 0) {\n return;\n }\n // check if level idx is valid\n if (newLevel < 0 || newLevel >= levels.length) {\n // invalid level id given, trigger error\n const error = new Error('invalid level idx');\n const fatal = newLevel < 0;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal,\n error,\n reason: error.message,\n });\n if (fatal) {\n return;\n }\n newLevel = Math.min(newLevel, levels.length - 1);\n }\n\n const lastLevelIndex = this.currentLevelIndex;\n const lastLevel = this.currentLevel;\n const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;\n const level = levels[newLevel];\n const pathwayId = level.attrs['PATHWAY-ID'];\n this.currentLevelIndex = newLevel;\n this.currentLevel = level;\n\n if (\n lastLevelIndex === newLevel &&\n level.details &&\n lastLevel &&\n lastPathwayId === pathwayId\n ) {\n return;\n }\n\n this.log(\n `Switching to level ${newLevel} (${\n level.height ? level.height + 'p ' : ''\n }${level.videoRange ? level.videoRange + ' ' : ''}${\n level.codecSet ? level.codecSet + ' ' : ''\n }@${level.bitrate})${\n pathwayId ? ' with Pathway ' + pathwayId : ''\n } from level ${lastLevelIndex}${\n lastPathwayId ? ' with Pathway ' + lastPathwayId : ''\n }`,\n );\n\n const levelSwitchingData: LevelSwitchingData = {\n level: newLevel,\n attrs: level.attrs,\n details: level.details,\n bitrate: level.bitrate,\n averageBitrate: level.averageBitrate,\n maxBitrate: level.maxBitrate,\n realBitrate: level.realBitrate,\n width: level.width,\n height: level.height,\n codecSet: level.codecSet,\n audioCodec: level.audioCodec,\n videoCodec: level.videoCodec,\n audioGroups: level.audioGroups,\n subtitleGroups: level.subtitleGroups,\n loaded: level.loaded,\n loadError: level.loadError,\n fragmentError: level.fragmentError,\n name: level.name,\n id: level.id,\n uri: level.uri,\n url: level.url,\n urlId: 0,\n audioGroupIds: level.audioGroupIds,\n textGroupIds: level.textGroupIds,\n };\n\n this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);\n // check if we need to load playlist for this level\n const levelDetails = level.details;\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n const hlsUrlParameters = this.switchParams(\n level.uri,\n lastLevel?.details,\n levelDetails,\n );\n this.loadPlaylist(hlsUrlParameters);\n }\n }\n\n get manualLevel(): number {\n return this.manualLevelIndex;\n }\n\n set manualLevel(newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel(): number {\n return this._firstLevel;\n }\n\n set firstLevel(newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel(): number {\n // Setting hls.startLevel (this._startLevel) overrides config.startLevel\n if (this._startLevel === undefined) {\n const configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n }\n return this.hls.firstAutoLevel;\n }\n return this._startLevel;\n }\n\n set startLevel(newLevel: number) {\n this._startLevel = newLevel;\n }\n\n protected onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.LEVEL &&\n data.context.level === this.level\n ) {\n this.checkRetry(data);\n }\n }\n\n // reset errors on the successful load of a fragment\n protected onFragBuffered(\n event: Events.FRAG_BUFFERED,\n { frag }: FragBufferedData,\n ) {\n if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {\n const el = frag.elementaryStreams;\n if (!Object.keys(el).some((type) => !!el[type])) {\n return;\n }\n const level = this._levels[frag.level];\n if (level?.loadError) {\n this.log(\n `Resetting level error count of ${level.loadError} on frag buffered`,\n );\n level.loadError = 0;\n }\n }\n }\n\n protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const { level, details } = data;\n const curLevel = this._levels[level];\n\n if (!curLevel) {\n this.warn(`Invalid level index ${level}`);\n if (data.deliveryDirectives?.skip) {\n details.deltaUpdateFailed = true;\n }\n return;\n }\n\n // only process level loaded events matching with expected level\n if (level === this.currentLevelIndex) {\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (curLevel.fragmentError === 0) {\n curLevel.loadError = 0;\n }\n this.playlistLoaded(level, data, curLevel.details);\n } else if (data.deliveryDirectives?.skip) {\n // received a delta playlist update that cannot be merged\n details.deltaUpdateFailed = true;\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters) {\n super.loadPlaylist();\n const currentLevelIndex = this.currentLevelIndex;\n const currentLevel = this.currentLevel;\n\n if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {\n let url = currentLevel.uri;\n if (hlsUrlParameters) {\n try {\n url = hlsUrlParameters.addDirectives(url);\n } catch (error) {\n this.warn(\n `Could not construct new URL with HLS Delivery Directives: ${error}`,\n );\n }\n }\n\n const pathwayId = currentLevel.attrs['PATHWAY-ID'];\n this.log(\n `Loading level index ${currentLevelIndex}${\n hlsUrlParameters?.msn !== undefined\n ? ' at sn ' +\n hlsUrlParameters.msn +\n ' part ' +\n hlsUrlParameters.part\n : ''\n } with${pathwayId ? ' Pathway ' + pathwayId : ''} ${url}`,\n );\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n this.clearTimer();\n this.hls.trigger(Events.LEVEL_LOADING, {\n url,\n level: currentLevelIndex,\n pathwayId: currentLevel.attrs['PATHWAY-ID'],\n id: 0, // Deprecated Level urlId\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n\n get nextLoadLevel() {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n\n removeLevel(levelIndex: number) {\n const levels = this._levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n if (this.steering) {\n this.steering.removeLevel(level);\n }\n if (level === this.currentLevel) {\n this.currentLevel = null;\n this.currentLevelIndex = -1;\n if (level.details) {\n level.details.fragments.forEach((f) => (f.level = -1));\n }\n }\n return false;\n });\n reassignFragmentLevelIndexes(levels);\n this._levels = levels;\n if (this.currentLevelIndex > -1 && this.currentLevel?.details) {\n this.currentLevelIndex = this.currentLevel.details.fragments[0].level;\n }\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n { levels }: LevelsUpdatedData,\n ) {\n this._levels = levels;\n }\n\n public checkMaxAutoUpdated() {\n const { autoLevelCapping, maxAutoLevel, maxHdcpLevel } = this.hls;\n if (this._maxAutoLevel !== maxAutoLevel) {\n this._maxAutoLevel = maxAutoLevel;\n this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {\n autoLevelCapping,\n levels: this.levels,\n maxAutoLevel,\n minAutoLevel: this.hls.minAutoLevel,\n maxHdcpLevel,\n });\n }\n }\n}\n\nfunction assignTrackIdsByGroup(tracks: MediaPlaylist[]): void {\n const groups = {};\n tracks.forEach((track) => {\n const groupId = track.groupId || '';\n track.id = groups[groupId] = groups[groupId] || 0;\n groups[groupId]++;\n });\n}\n","import AbrController from './controller/abr-controller';\nimport AudioStreamController from './controller/audio-stream-controller';\nimport AudioTrackController from './controller/audio-track-controller';\nimport { SubtitleStreamController } from './controller/subtitle-stream-controller';\nimport SubtitleTrackController from './controller/subtitle-track-controller';\nimport BufferController from './controller/buffer-controller';\nimport { TimelineController } from './controller/timeline-controller';\nimport CapLevelController from './controller/cap-level-controller';\nimport FPSController from './controller/fps-controller';\nimport EMEController, {\n MediaKeySessionContext,\n} from './controller/eme-controller';\nimport CMCDController from './controller/cmcd-controller';\nimport ContentSteeringController from './controller/content-steering-controller';\nimport ErrorController from './controller/error-controller';\nimport XhrLoader from './utils/xhr-loader';\nimport FetchLoader, { fetchSupported } from './utils/fetch-loader';\nimport Cues from './utils/cues';\nimport { requestMediaKeySystemAccess } from './utils/mediakeys-helper';\nimport { ILogger, logger } from './utils/logger';\n\nimport type Hls from './hls';\nimport type { CuesInterface } from './utils/cues';\nimport type { MediaKeyFunc, KeySystems } from './utils/mediakeys-helper';\nimport type {\n FragmentLoaderContext,\n Loader,\n LoaderContext,\n LoaderResponse,\n PlaylistLoaderContext,\n} from './types/loader';\nimport type {\n AudioSelectionOption,\n SubtitleSelectionOption,\n VideoSelectionOption,\n} from './types/media-playlist';\n\nexport type ABRControllerConfig = {\n abrEwmaFastLive: number;\n abrEwmaSlowLive: number;\n abrEwmaFastVoD: number;\n abrEwmaSlowVoD: number;\n /**\n * Default bandwidth estimate in bits/s prior to collecting fragment bandwidth samples\n */\n abrEwmaDefaultEstimate: number;\n abrEwmaDefaultEstimateMax: number;\n abrBandWidthFactor: number;\n abrBandWidthUpFactor: number;\n abrMaxWithRealBitrate: boolean;\n maxStarvationDelay: number;\n maxLoadingDelay: number;\n};\n\nexport type BufferControllerConfig = {\n appendErrorMaxRetry: number;\n backBufferLength: number;\n frontBufferFlushThreshold: number;\n liveDurationInfinity: boolean;\n /**\n * @deprecated use backBufferLength\n */\n liveBackBufferLength: number | null;\n};\n\nexport type CapLevelControllerConfig = {\n capLevelToPlayerSize: boolean;\n};\n\nexport type CMCDControllerConfig = {\n sessionId?: string;\n contentId?: string;\n useHeaders?: boolean;\n includeKeys?: string[];\n};\n\nexport type DRMSystemOptions = {\n audioRobustness?: string;\n videoRobustness?: string;\n audioEncryptionScheme?: string | null;\n videoEncryptionScheme?: string | null;\n persistentState?: MediaKeysRequirement;\n distinctiveIdentifier?: MediaKeysRequirement;\n sessionTypes?: string[];\n sessionType?: string;\n};\n\nexport type DRMSystemConfiguration = {\n licenseUrl: string;\n serverCertificateUrl?: string;\n generateRequest?: (\n this: Hls,\n initDataType: string,\n initData: ArrayBuffer | null,\n keyContext: MediaKeySessionContext,\n ) =>\n | { initDataType: string; initData: ArrayBuffer | null }\n | undefined\n | never;\n};\n\nexport type DRMSystemsConfiguration = Partial<\n Record<KeySystems, DRMSystemConfiguration>\n>;\n\nexport type EMEControllerConfig = {\n licenseXhrSetup?: (\n this: Hls,\n xhr: XMLHttpRequest,\n url: string,\n keyContext: MediaKeySessionContext,\n licenseChallenge: Uint8Array,\n ) => void | Uint8Array | Promise<Uint8Array | void>;\n licenseResponseCallback?: (\n this: Hls,\n xhr: XMLHttpRequest,\n url: string,\n keyContext: MediaKeySessionContext,\n ) => ArrayBuffer;\n emeEnabled: boolean;\n widevineLicenseUrl?: string;\n drmSystems: DRMSystemsConfiguration;\n drmSystemOptions: DRMSystemOptions;\n requestMediaKeySystemAccessFunc: MediaKeyFunc | null;\n};\n\nexport interface FragmentLoaderConstructor {\n new (confg: HlsConfig): Loader<FragmentLoaderContext>;\n}\n\n/**\n * @deprecated use fragLoadPolicy.default\n */\nexport type FragmentLoaderConfig = {\n fragLoadingTimeOut: number;\n fragLoadingMaxRetry: number;\n fragLoadingRetryDelay: number;\n fragLoadingMaxRetryTimeout: number;\n};\n\nexport type FPSControllerConfig = {\n capLevelOnFPSDrop: boolean;\n fpsDroppedMonitoringPeriod: number;\n fpsDroppedMonitoringThreshold: number;\n};\n\nexport type LevelControllerConfig = {\n startLevel?: number;\n};\n\nexport type MP4RemuxerConfig = {\n stretchShortVideoTrack: boolean;\n maxAudioFramesDrift: number;\n};\n\nexport interface PlaylistLoaderConstructor {\n new (confg: HlsConfig): Loader<PlaylistLoaderContext>;\n}\n\n/**\n * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default\n */\nexport type PlaylistLoaderConfig = {\n manifestLoadingTimeOut: number;\n manifestLoadingMaxRetry: number;\n manifestLoadingRetryDelay: number;\n manifestLoadingMaxRetryTimeout: number;\n\n levelLoadingTimeOut: number;\n levelLoadingMaxRetry: number;\n levelLoadingRetryDelay: number;\n levelLoadingMaxRetryTimeout: number;\n};\n\nexport type HlsLoadPolicies = {\n fragLoadPolicy: LoadPolicy;\n keyLoadPolicy: LoadPolicy;\n certLoadPolicy: LoadPolicy;\n playlistLoadPolicy: LoadPolicy;\n manifestLoadPolicy: LoadPolicy;\n steeringManifestLoadPolicy: LoadPolicy;\n};\n\nexport type LoadPolicy = {\n default: LoaderConfig;\n};\n\nexport type LoaderConfig = {\n maxTimeToFirstByteMs: number; // Max time to first byte\n maxLoadTimeMs: number; // Max time for load completion\n timeoutRetry: RetryConfig | null;\n errorRetry: RetryConfig | null;\n};\n\nexport type RetryConfig = {\n maxNumRetry: number; // Maximum number of retries\n retryDelayMs: number; // Retry delay = 2^retryCount * retryDelayMs (exponential) or retryCount * retryDelayMs (linear)\n maxRetryDelayMs: number; // Maximum delay between retries\n backoff?: 'exponential' | 'linear'; // used to determine retry backoff duration (see retryDelayMs)\n shouldRetry?: (\n retryConfig: RetryConfig | null | undefined,\n retryCount: number,\n isTimeout: boolean,\n loaderResponse: LoaderResponse | undefined,\n retry: boolean,\n ) => boolean;\n};\n\nexport type StreamControllerConfig = {\n autoStartLoad: boolean;\n startPosition: number;\n defaultAudioCodec?: string;\n initialLiveManifestSize: number;\n maxBufferLength: number;\n maxBufferSize: number;\n maxBufferHole: number;\n highBufferWatchdogPeriod: number;\n nudgeOffset: number;\n nudgeMaxRetry: number;\n maxFragLookUpTolerance: number;\n maxMaxBufferLength: number;\n startFragPrefetch: boolean;\n testBandwidth: boolean;\n};\n\nexport type SelectionPreferences = {\n videoPreference?: VideoSelectionOption;\n audioPreference?: AudioSelectionOption;\n subtitlePreference?: SubtitleSelectionOption;\n};\n\nexport type LatencyControllerConfig = {\n liveSyncDurationCount: number;\n liveMaxLatencyDurationCount: number;\n liveSyncDuration?: number;\n liveMaxLatencyDuration?: number;\n maxLiveSyncPlaybackRate: number;\n};\n\nexport type MetadataControllerConfig = {\n enableDateRangeMetadataCues: boolean;\n enableEmsgMetadataCues: boolean;\n enableID3MetadataCues: boolean;\n};\n\nexport type TimelineControllerConfig = {\n cueHandler: CuesInterface;\n enableWebVTT: boolean;\n enableIMSC1: boolean;\n enableCEA708Captions: boolean;\n captionsTextTrack1Label: string;\n captionsTextTrack1LanguageCode: string;\n captionsTextTrack2Label: string;\n captionsTextTrack2LanguageCode: string;\n captionsTextTrack3Label: string;\n captionsTextTrack3LanguageCode: string;\n captionsTextTrack4Label: string;\n captionsTextTrack4LanguageCode: string;\n renderTextTracksNatively: boolean;\n};\n\nexport type TSDemuxerConfig = {\n forceKeyFrameOnDiscontinuity: boolean;\n};\n\nexport type HlsConfig = {\n debug: boolean | ILogger;\n enableWorker: boolean;\n workerPath: null | string;\n enableSoftwareAES: boolean;\n minAutoBitrate: number;\n ignoreDevicePixelRatio: boolean;\n preferManagedMediaSource: boolean;\n loader: { new (confg: HlsConfig): Loader<LoaderContext> };\n fLoader?: FragmentLoaderConstructor;\n pLoader?: PlaylistLoaderConstructor;\n fetchSetup?: (context: LoaderContext, initParams: any) => Request;\n xhrSetup?: (xhr: XMLHttpRequest, url: string) => Promise<void> | void;\n\n // Alt Audio\n audioStreamController?: typeof AudioStreamController;\n audioTrackController?: typeof AudioTrackController;\n // Subtitle\n subtitleStreamController?: typeof SubtitleStreamController;\n subtitleTrackController?: typeof SubtitleTrackController;\n timelineController?: typeof TimelineController;\n // EME\n emeController?: typeof EMEController;\n // CMCD\n cmcd?: CMCDControllerConfig;\n cmcdController?: typeof CMCDController;\n // Content Steering\n contentSteeringController?: typeof ContentSteeringController;\n\n // MediaCapabilies API for level, track, and switch filtering\n useMediaCapabilities: boolean;\n\n abrController: typeof AbrController;\n bufferController: typeof BufferController;\n capLevelController: typeof CapLevelController;\n errorController: typeof ErrorController;\n fpsController: typeof FPSController;\n progressive: boolean;\n lowLatencyMode: boolean;\n} & ABRControllerConfig &\n BufferControllerConfig &\n CapLevelControllerConfig &\n EMEControllerConfig &\n FPSControllerConfig &\n LevelControllerConfig &\n MP4RemuxerConfig &\n StreamControllerConfig &\n SelectionPreferences &\n LatencyControllerConfig &\n MetadataControllerConfig &\n TimelineControllerConfig &\n TSDemuxerConfig &\n HlsLoadPolicies &\n FragmentLoaderConfig &\n PlaylistLoaderConfig;\n\nconst defaultLoadPolicy: LoaderConfig = {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: null,\n errorRetry: null,\n};\n\n/**\n * @ignore\n * If possible, keep hlsDefaultConfig shallow\n * It is cloned whenever a new Hls instance is created, by keeping the config\n * shallow the properties are cloned, and we don't end up manipulating the default\n */\nexport const hlsDefaultConfig: HlsConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: undefined, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n ignoreDevicePixelRatio: false, // used by cap-level-controller\n preferManagedMediaSource: true,\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n backBufferLength: Infinity, // used by buffer-controller\n frontBufferFlushThreshold: Infinity,\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.1, // used by stream-controller\n highBufferWatchdogPeriod: 2, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry: 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount: 3, // used by latency-controller\n liveMaxLatencyDurationCount: Infinity, // used by latency-controller\n liveSyncDuration: undefined, // used by latency-controller\n liveMaxLatencyDuration: undefined, // used by latency-controller\n maxLiveSyncPlaybackRate: 1, // used by latency-controller\n liveDurationInfinity: false, // used by buffer-controller\n /**\n * @deprecated use backBufferLength\n */\n liveBackBufferLength: null, // used by buffer-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by transmuxer\n workerPath: null, // used by transmuxer\n enableSoftwareAES: true, // used by decrypter\n startLevel: undefined, // used by level-controller\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\n loader: XhrLoader,\n // loader: FetchLoader,\n fLoader: undefined, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\n licenseResponseCallback: undefined, // used by eme-controller\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n errorController: ErrorController,\n fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift: 1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrEwmaDefaultEstimateMax: 5e6, // 5 mbps\n abrBandWidthFactor: 0.95, // used by abr-controller\n abrBandWidthUpFactor: 0.7, // used by abr-controller\n abrMaxWithRealBitrate: false, // used by abr-controller\n maxStarvationDelay: 4, // used by abr-controller\n maxLoadingDelay: 4, // used by abr-controller\n minAutoBitrate: 0, // used by hls\n emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n drmSystems: {}, // used by eme-controller\n drmSystemOptions: {}, // used by eme-controller\n requestMediaKeySystemAccessFunc: __USE_EME_DRM__\n ? requestMediaKeySystemAccess\n : null, // used by eme-controller\n testBandwidth: true,\n progressive: false,\n lowLatencyMode: true,\n cmcd: undefined,\n enableDateRangeMetadataCues: true,\n enableEmsgMetadataCues: true,\n enableID3MetadataCues: true,\n useMediaCapabilities: __USE_MEDIA_CAPABILITIES__,\n\n certLoadPolicy: {\n default: defaultLoadPolicy,\n },\n keyLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear',\n },\n errorRetry: {\n maxNumRetry: 8,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear',\n },\n },\n },\n manifestLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: Infinity,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n playlistLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 2,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n fragLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 120000,\n timeoutRetry: {\n maxNumRetry: 4,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 6,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n steeringManifestLoadPolicy: {\n default: __USE_CONTENT_STEERING__\n ? {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n }\n : defaultLoadPolicy,\n },\n\n // These default settings are deprecated in favor of the above policies\n // and are maintained for backwards compatibility\n manifestLoadingTimeOut: 10000,\n manifestLoadingMaxRetry: 1,\n manifestLoadingRetryDelay: 1000,\n manifestLoadingMaxRetryTimeout: 64000,\n levelLoadingTimeOut: 10000,\n levelLoadingMaxRetry: 4,\n levelLoadingRetryDelay: 1000,\n levelLoadingMaxRetryTimeout: 64000,\n fragLoadingTimeOut: 20000,\n fragLoadingMaxRetry: 6,\n fragLoadingRetryDelay: 1000,\n fragLoadingMaxRetryTimeout: 64000,\n\n // Dynamic Modules\n ...timelineConfig(),\n subtitleStreamController: __USE_SUBTITLES__\n ? SubtitleStreamController\n : undefined,\n subtitleTrackController: __USE_SUBTITLES__\n ? SubtitleTrackController\n : undefined,\n timelineController: __USE_SUBTITLES__ ? TimelineController : undefined,\n audioStreamController: __USE_ALT_AUDIO__ ? AudioStreamController : undefined,\n audioTrackController: __USE_ALT_AUDIO__ ? AudioTrackController : undefined,\n emeController: __USE_EME_DRM__ ? EMEController : undefined,\n cmcdController: __USE_CMCD__ ? CMCDController : undefined,\n contentSteeringController: __USE_CONTENT_STEERING__\n ? ContentSteeringController\n : undefined,\n};\n\nfunction timelineConfig(): TimelineControllerConfig {\n return {\n cueHandler: Cues, // used by timeline-controller\n enableWebVTT: __USE_SUBTITLES__, // used by timeline-controller\n enableIMSC1: __USE_SUBTITLES__, // used by timeline-controller\n enableCEA708Captions: __USE_SUBTITLES__, // used by timeline-controller\n captionsTextTrack1Label: 'English', // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en', // used by timeline-controller\n captionsTextTrack2Label: 'Spanish', // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es', // used by timeline-controller\n captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack3LanguageCode: '', // used by timeline-controller\n captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack4LanguageCode: '', // used by timeline-controller\n renderTextTracksNatively: true,\n };\n}\n\n/**\n * @ignore\n */\nexport function mergeConfig(\n defaultConfig: HlsConfig,\n userConfig: Partial<HlsConfig>,\n): HlsConfig {\n if (\n (userConfig.liveSyncDurationCount ||\n userConfig.liveMaxLatencyDurationCount) &&\n (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)\n ) {\n throw new Error(\n \"Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration\",\n );\n }\n\n if (\n userConfig.liveMaxLatencyDurationCount !== undefined &&\n (userConfig.liveSyncDurationCount === undefined ||\n userConfig.liveMaxLatencyDurationCount <=\n userConfig.liveSyncDurationCount)\n ) {\n throw new Error(\n 'Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be greater than \"liveSyncDurationCount\"',\n );\n }\n\n if (\n userConfig.liveMaxLatencyDuration !== undefined &&\n (userConfig.liveSyncDuration === undefined ||\n userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)\n ) {\n throw new Error(\n 'Illegal hls.js config: \"liveMaxLatencyDuration\" must be greater than \"liveSyncDuration\"',\n );\n }\n\n const defaultsCopy = deepCpy(defaultConfig);\n\n // Backwards compatibility with deprecated config values\n const deprecatedSettingTypes = ['manifest', 'level', 'frag'];\n const deprecatedSettings = [\n 'TimeOut',\n 'MaxRetry',\n 'RetryDelay',\n 'MaxRetryTimeout',\n ];\n deprecatedSettingTypes.forEach((type) => {\n const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;\n const policyNotSet = userConfig[policyName] === undefined;\n const report: string[] = [];\n deprecatedSettings.forEach((setting) => {\n const deprecatedSetting = `${type}Loading${setting}`;\n const value = userConfig[deprecatedSetting];\n if (value !== undefined && policyNotSet) {\n report.push(deprecatedSetting);\n const settings: LoaderConfig = defaultsCopy[policyName].default;\n userConfig[policyName] = { default: settings };\n switch (setting) {\n case 'TimeOut':\n settings.maxLoadTimeMs = value;\n settings.maxTimeToFirstByteMs = value;\n break;\n case 'MaxRetry':\n settings.errorRetry!.maxNumRetry = value;\n settings.timeoutRetry!.maxNumRetry = value;\n break;\n case 'RetryDelay':\n settings.errorRetry!.retryDelayMs = value;\n settings.timeoutRetry!.retryDelayMs = value;\n break;\n case 'MaxRetryTimeout':\n settings.errorRetry!.maxRetryDelayMs = value;\n settings.timeoutRetry!.maxRetryDelayMs = value;\n break;\n }\n }\n });\n if (report.length) {\n logger.warn(\n `hls.js config: \"${report.join(\n '\", \"',\n )}\" setting(s) are deprecated, use \"${policyName}\": ${JSON.stringify(\n userConfig[policyName],\n )}`,\n );\n }\n });\n\n return {\n ...defaultsCopy,\n ...userConfig,\n };\n}\n\nfunction deepCpy(obj: any): any {\n if (obj && typeof obj === 'object') {\n if (Array.isArray(obj)) {\n return obj.map(deepCpy);\n }\n return Object.keys(obj).reduce((result, key) => {\n result[key] = deepCpy(obj[key]);\n return result;\n }, {});\n }\n return obj;\n}\n\n/**\n * @ignore\n */\nexport function enableStreamingMode(config) {\n const currentLoader = config.loader;\n if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {\n // If a developer has configured their own loader, respect that choice\n logger.log(\n '[config]: Custom loader detected, cannot enable progressive streaming',\n );\n config.progressive = false;\n } else {\n const canStreamProgressively = fetchSupported();\n if (canStreamProgressively) {\n config.loader = FetchLoader;\n config.progressive = true;\n config.enableSoftwareAES = true;\n logger.log('[config]: Progressive streaming enabled, using FetchLoader');\n }\n }\n}\n","import { Events } from '../events';\nimport { Fragment, Part } from '../loader/fragment';\nimport { PlaylistLevelType } from '../types/loader';\nimport type { SourceBufferName } from '../types/buffer';\nimport type {\n FragmentBufferedRange,\n FragmentEntity,\n FragmentTimeRange,\n} from '../types/fragment-tracker';\nimport type { ComponentAPI } from '../types/component-api';\nimport type {\n BufferAppendedData,\n FragBufferedData,\n FragLoadedData,\n} from '../types/events';\nimport type Hls from '../hls';\n\nexport const enum FragmentState {\n NOT_LOADED = 'NOT_LOADED',\n APPENDING = 'APPENDING',\n PARTIAL = 'PARTIAL',\n OK = 'OK',\n}\n\nexport class FragmentTracker implements ComponentAPI {\n private activePartLists: { [key in PlaylistLevelType]?: Part[] } =\n Object.create(null);\n private endListFragments: { [key in PlaylistLevelType]?: FragmentEntity } =\n Object.create(null);\n private fragments: Partial<Record<string, FragmentEntity>> =\n Object.create(null);\n private timeRanges:\n | {\n [key in SourceBufferName]?: TimeRanges;\n }\n | null = Object.create(null);\n\n private bufferPadding: number = 0.2;\n private hls: Hls;\n private hasGaps: boolean = false;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n\n public destroy() {\n this._unregisterListeners();\n // @ts-ignore\n this.fragments =\n // @ts-ignore\n this.activePartLists =\n // @ts-ignore\n this.endListFragments =\n this.timeRanges =\n null;\n }\n\n /**\n * Return a Fragment or Part with an appended range that matches the position and levelType\n * Otherwise, return null\n */\n public getAppendedFrag(\n position: number,\n levelType: PlaylistLevelType,\n ): Fragment | Part | null {\n const activeParts = this.activePartLists[levelType];\n if (activeParts) {\n for (let i = activeParts.length; i--; ) {\n const activePart = activeParts[i];\n if (!activePart) {\n break;\n }\n const appendedPTS = activePart.end;\n if (\n activePart.start <= position &&\n appendedPTS !== null &&\n position <= appendedPTS\n ) {\n return activePart;\n }\n }\n }\n return this.getBufferedFrag(position, levelType);\n }\n\n /**\n * Return a buffered Fragment that matches the position and levelType.\n * A buffered Fragment is one whose loading, parsing and appending is done (completed or \"partial\" meaning aborted).\n * If not found any Fragment, return null\n */\n public getBufferedFrag(\n position: number,\n levelType: PlaylistLevelType,\n ): Fragment | null {\n const { fragments } = this;\n const keys = Object.keys(fragments);\n for (let i = keys.length; i--; ) {\n const fragmentEntity = fragments[keys[i]];\n if (fragmentEntity?.body.type === levelType && fragmentEntity.buffered) {\n const frag = fragmentEntity.body;\n if (frag.start <= position && position <= frag.end) {\n return frag;\n }\n }\n }\n return null;\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n */\n public detectEvictedFragments(\n elementaryStream: SourceBufferName,\n timeRange: TimeRanges,\n playlistType: PlaylistLevelType,\n appendedPart?: Part | null,\n ) {\n if (this.timeRanges) {\n this.timeRanges[elementaryStream] = timeRange;\n }\n // Check if any flagged fragments have been unloaded\n // excluding anything newer than appendedPartSn\n const appendedPartSn = (appendedPart?.fragment.sn || -1) as number;\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (appendedPartSn >= (fragmentEntity.body.sn as number)) {\n return;\n }\n if (!fragmentEntity.buffered && !fragmentEntity.loaded) {\n if (fragmentEntity.body.type === playlistType) {\n this.removeFragment(fragmentEntity.body);\n }\n return;\n }\n const esData = fragmentEntity.range[elementaryStream];\n if (!esData) {\n return;\n }\n esData.time.some((time: FragmentTimeRange) => {\n const isNotBuffered = !this.isTimeBuffered(\n time.startPTS,\n time.endPTS,\n timeRange,\n );\n if (isNotBuffered) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n }\n return isNotBuffered;\n });\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n */\n public detectPartialFragments(data: FragBufferedData) {\n const timeRanges = this.timeRanges;\n const { frag, part } = data;\n if (!timeRanges || frag.sn === 'initSegment') {\n return;\n }\n\n const fragKey = getFragmentKey(frag);\n const fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity || (fragmentEntity.buffered && frag.gap)) {\n return;\n }\n const isFragHint = !frag.relurl;\n Object.keys(timeRanges).forEach((elementaryStream: SourceBufferName) => {\n const streamInfo = frag.elementaryStreams[elementaryStream];\n if (!streamInfo) {\n return;\n }\n const timeRange = timeRanges[elementaryStream] as TimeRanges;\n const partial = isFragHint || streamInfo.partial === true;\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(\n frag,\n part,\n partial,\n timeRange,\n );\n });\n fragmentEntity.loaded = null;\n if (Object.keys(fragmentEntity.range).length) {\n fragmentEntity.buffered = true;\n const endList = (fragmentEntity.body.endList =\n frag.endList || fragmentEntity.body.endList);\n if (endList) {\n this.endListFragments[fragmentEntity.body.type] = fragmentEntity;\n }\n if (!isPartial(fragmentEntity)) {\n // Remove older fragment parts from lookup after frag is tracked as buffered\n this.removeParts((frag.sn as number) - 1, frag.type);\n }\n } else {\n // remove fragment if nothing was appended\n this.removeFragment(fragmentEntity.body);\n }\n }\n\n private removeParts(snToKeep: number, levelType: PlaylistLevelType) {\n const activeParts = this.activePartLists[levelType];\n if (!activeParts) {\n return;\n }\n this.activePartLists[levelType] = activeParts.filter(\n (part) => (part.fragment.sn as number) >= snToKeep,\n );\n }\n\n public fragBuffered(frag: Fragment, force?: true) {\n const fragKey = getFragmentKey(frag);\n let fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity && force) {\n fragmentEntity = this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded: null,\n buffered: false,\n range: Object.create(null),\n };\n if (frag.gap) {\n this.hasGaps = true;\n }\n }\n if (fragmentEntity) {\n fragmentEntity.loaded = null;\n fragmentEntity.buffered = true;\n }\n }\n\n private getBufferedTimes(\n fragment: Fragment,\n part: Part | null,\n partial: boolean,\n timeRange: TimeRanges,\n ): FragmentBufferedRange {\n const buffered: FragmentBufferedRange = {\n time: [],\n partial,\n };\n const startPTS = fragment.start;\n const endPTS = fragment.end;\n const minEndPTS = fragment.minEndPTS || endPTS;\n const maxStartPTS = fragment.maxStartPTS || startPTS;\n for (let i = 0; i < timeRange.length; i++) {\n const startTime = timeRange.start(i) - this.bufferPadding;\n const endTime = timeRange.end(i) + this.bufferPadding;\n if (maxStartPTS >= startTime && minEndPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i)),\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n const start = Math.max(startPTS, timeRange.start(i));\n const end = Math.min(endPTS, timeRange.end(i));\n if (end > start) {\n buffered.partial = true;\n // Check for intersection with buffer\n // Get playable sections of the fragment\n buffered.time.push({\n startPTS: start,\n endPTS: end,\n });\n }\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n return buffered;\n }\n\n /**\n * Gets the partial fragment for a certain time\n */\n public getPartialFragment(time: number): Fragment | null {\n let bestFragment: Fragment | null = null;\n let timePadding: number;\n let startTime: number;\n let endTime: number;\n let bestOverlap: number = 0;\n const { bufferPadding, fragments } = this;\n Object.keys(fragments).forEach((key) => {\n const fragmentEntity = fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.start - bufferPadding;\n endTime = fragmentEntity.body.end + bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n public isEndListAppended(type: PlaylistLevelType): boolean {\n const lastFragmentEntity = this.endListFragments[type];\n return (\n lastFragmentEntity !== undefined &&\n (lastFragmentEntity.buffered || isPartial(lastFragmentEntity))\n );\n }\n\n public getState(fragment: Fragment): FragmentState {\n const fragKey = getFragmentKey(fragment);\n const fragmentEntity = this.fragments[fragKey];\n\n if (fragmentEntity) {\n if (!fragmentEntity.buffered) {\n return FragmentState.APPENDING;\n } else if (isPartial(fragmentEntity)) {\n return FragmentState.PARTIAL;\n } else {\n return FragmentState.OK;\n }\n }\n\n return FragmentState.NOT_LOADED;\n }\n\n private isTimeBuffered(\n startPTS: number,\n endPTS: number,\n timeRange: TimeRanges,\n ): boolean {\n let startTime;\n let endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n private onFragLoaded(event: Events.FRAG_LOADED, data: FragLoadedData) {\n const { frag, part } = data;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (frag.sn === 'initSegment' || frag.bitrateTest) {\n return;\n }\n\n // Fragment entity `loaded` FragLoadedData is null when loading parts\n const loaded = part ? null : data;\n\n const fragKey = getFragmentKey(frag);\n this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded,\n buffered: false,\n range: Object.create(null),\n };\n }\n\n private onBufferAppended(\n event: Events.BUFFER_APPENDED,\n data: BufferAppendedData,\n ) {\n const { frag, part, timeRanges } = data;\n if (frag.sn === 'initSegment') {\n return;\n }\n const playlistType = frag.type;\n if (part) {\n let activeParts = this.activePartLists[playlistType];\n if (!activeParts) {\n this.activePartLists[playlistType] = activeParts = [];\n }\n activeParts.push(part);\n }\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = timeRanges;\n Object.keys(timeRanges).forEach((elementaryStream: SourceBufferName) => {\n const timeRange = timeRanges[elementaryStream] as TimeRanges;\n this.detectEvictedFragments(\n elementaryStream,\n timeRange,\n playlistType,\n part,\n );\n });\n }\n\n private onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n this.detectPartialFragments(data);\n }\n\n private hasFragment(fragment: Fragment): boolean {\n const fragKey = getFragmentKey(fragment);\n return !!this.fragments[fragKey];\n }\n\n public hasParts(type: PlaylistLevelType): boolean {\n return !!this.activePartLists[type]?.length;\n }\n\n public removeFragmentsInRange(\n start: number,\n end: number,\n playlistType: PlaylistLevelType,\n withGapOnly?: boolean,\n unbufferedOnly?: boolean,\n ) {\n if (withGapOnly && !this.hasGaps) {\n return;\n }\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n const frag = fragmentEntity.body;\n if (frag.type !== playlistType || (withGapOnly && !frag.gap)) {\n return;\n }\n if (\n frag.start < end &&\n frag.end > start &&\n (fragmentEntity.buffered || unbufferedOnly)\n ) {\n this.removeFragment(frag);\n }\n });\n }\n\n public removeFragment(fragment: Fragment) {\n const fragKey = getFragmentKey(fragment);\n fragment.stats.loaded = 0;\n fragment.clearElementaryStreamInfo();\n const activeParts = this.activePartLists[fragment.type];\n if (activeParts) {\n const snToRemove = fragment.sn;\n this.activePartLists[fragment.type] = activeParts.filter(\n (part) => part.fragment.sn !== snToRemove,\n );\n }\n delete this.fragments[fragKey];\n if (fragment.endList) {\n delete this.endListFragments[fragment.type];\n }\n }\n\n public removeAllFragments() {\n this.fragments = Object.create(null);\n this.endListFragments = Object.create(null);\n this.activePartLists = Object.create(null);\n this.hasGaps = false;\n }\n}\n\nfunction isPartial(fragmentEntity: FragmentEntity): boolean {\n return (\n fragmentEntity.buffered &&\n (fragmentEntity.body.gap ||\n fragmentEntity.range.video?.partial ||\n fragmentEntity.range.audio?.partial ||\n fragmentEntity.range.audiovideo?.partial)\n );\n}\n\nfunction getFragmentKey(fragment: Fragment): string {\n return `${fragment.type}_${fragment.level}_${fragment.sn}`;\n}\n","import { ErrorTypes, ErrorDetails } from '../errors';\nimport { Fragment } from './fragment';\nimport {\n Loader,\n LoaderConfiguration,\n FragmentLoaderContext,\n} from '../types/loader';\nimport { getLoaderConfigWithoutReties } from '../utils/error-helper';\nimport type { HlsConfig } from '../config';\nimport type { BaseSegment, Part } from './fragment';\nimport type {\n ErrorData,\n FragLoadedData,\n PartsLoadedData,\n} from '../types/events';\n\nconst MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb\n\nexport default class FragmentLoader {\n private readonly config: HlsConfig;\n private loader: Loader<FragmentLoaderContext> | null = null;\n private partLoadTimeout: number = -1;\n\n constructor(config: HlsConfig) {\n this.config = config;\n }\n\n destroy() {\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n }\n\n abort() {\n if (this.loader) {\n // Abort the loader for current fragment. Only one may load at any given time\n this.loader.abort();\n }\n }\n\n load(\n frag: Fragment,\n onProgress?: FragmentLoadProgressCallback,\n ): Promise<FragLoadedData> {\n const url = frag.url;\n if (!url) {\n return Promise.reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n error: new Error(\n `Fragment does not have a ${url ? 'part list' : 'url'}`,\n ),\n networkDetails: null,\n }),\n );\n }\n this.abort();\n\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap) {\n if (frag.tagList.some((tags) => tags[0] === 'GAP')) {\n reject(createGapLoadError(frag));\n return;\n } else {\n // Reset temporary treatment as GAP tag\n frag.gap = false;\n }\n }\n const loader =\n (this.loader =\n frag.loader =\n FragmentILoader\n ? new FragmentILoader(config)\n : (new DefaultILoader(config) as Loader<FragmentLoaderContext>));\n const loaderContext = createLoaderContext(frag);\n const loadPolicy = getLoaderConfigWithoutReties(\n config.fragLoadPolicy.default,\n );\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE,\n };\n // Assign frag stats to the loader's stats reference\n frag.stats = loader.stats;\n loader.load(loaderContext, loaderConfig, {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n let payload = response.data as ArrayBuffer;\n if (context.resetIV && frag.decryptdata) {\n frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));\n payload = payload.slice(16);\n }\n resolve({\n frag,\n part: null,\n payload,\n networkDetails,\n });\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n response: { url, data: undefined, ...response },\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats,\n }),\n );\n },\n onAbort: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n error: new Error('Aborted'),\n networkDetails,\n stats,\n }),\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats,\n }),\n );\n },\n onProgress: (stats, context, data, networkDetails) => {\n if (onProgress) {\n onProgress({\n frag,\n part: null,\n payload: data as ArrayBuffer,\n networkDetails,\n });\n }\n },\n });\n });\n }\n\n public loadPart(\n frag: Fragment,\n part: Part,\n onProgress: FragmentLoadProgressCallback,\n ): Promise<FragLoadedData> {\n this.abort();\n\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap || part.gap) {\n reject(createGapLoadError(frag, part));\n return;\n }\n const loader =\n (this.loader =\n frag.loader =\n FragmentILoader\n ? new FragmentILoader(config)\n : (new DefaultILoader(config) as Loader<FragmentLoaderContext>));\n const loaderContext = createLoaderContext(frag, part);\n // Should we define another load policy for parts?\n const loadPolicy = getLoaderConfigWithoutReties(\n config.fragLoadPolicy.default,\n );\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: MIN_CHUNK_SIZE,\n };\n // Assign part stats to the loader's stats reference\n part.stats = loader.stats;\n loader.load(loaderContext, loaderConfig, {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n this.updateStatsFromPart(frag, part);\n const partLoadedData: FragLoadedData = {\n frag,\n part,\n payload: response.data as ArrayBuffer,\n networkDetails,\n };\n onProgress(partLoadedData);\n resolve(partLoadedData);\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n part,\n response: {\n url: loaderContext.url,\n data: undefined,\n ...response,\n },\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats,\n }),\n );\n },\n onAbort: (stats, context, networkDetails) => {\n frag.stats.aborted = part.stats.aborted;\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n part,\n error: new Error('Aborted'),\n networkDetails,\n stats,\n }),\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n part,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats,\n }),\n );\n },\n });\n });\n }\n\n private updateStatsFromPart(frag: Fragment, part: Part) {\n const fragStats = frag.stats;\n const partStats = part.stats;\n const partTotal = partStats.total;\n fragStats.loaded += partStats.loaded;\n if (partTotal) {\n const estTotalParts = Math.round(frag.duration / part.duration);\n const estLoadedParts = Math.min(\n Math.round(fragStats.loaded / partTotal),\n estTotalParts,\n );\n const estRemainingParts = estTotalParts - estLoadedParts;\n const estRemainingBytes =\n estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);\n fragStats.total = fragStats.loaded + estRemainingBytes;\n } else {\n fragStats.total = Math.max(fragStats.loaded, fragStats.total);\n }\n const fragLoading = fragStats.loading;\n const partLoading = partStats.loading;\n if (fragLoading.start) {\n // add to fragment loader latency\n fragLoading.first += partLoading.first - partLoading.start;\n } else {\n fragLoading.start = partLoading.start;\n fragLoading.first = partLoading.first;\n }\n fragLoading.end = partLoading.end;\n }\n\n private resetLoader(frag: Fragment, loader: Loader<FragmentLoaderContext>) {\n frag.loader = null;\n if (this.loader === loader) {\n self.clearTimeout(this.partLoadTimeout);\n this.loader = null;\n }\n loader.destroy();\n }\n}\n\nfunction createLoaderContext(\n frag: Fragment,\n part: Part | null = null,\n): FragmentLoaderContext {\n const segment: BaseSegment = part || frag;\n const loaderContext: FragmentLoaderContext = {\n frag,\n part,\n responseType: 'arraybuffer',\n url: segment.url,\n headers: {},\n rangeStart: 0,\n rangeEnd: 0,\n };\n const start = segment.byteRangeStartOffset as number;\n const end = segment.byteRangeEndOffset as number;\n if (Number.isFinite(start) && Number.isFinite(end)) {\n let byteRangeStart = start;\n let byteRangeEnd = end;\n if (frag.sn === 'initSegment' && frag.decryptdata?.method === 'AES-128') {\n // MAP segment encrypted with method 'AES-128', when served with HTTP Range,\n // has the unencrypted size specified in the range.\n // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6\n const fragmentLen = end - start;\n if (fragmentLen % 16) {\n byteRangeEnd = end + (16 - (fragmentLen % 16));\n }\n if (start !== 0) {\n loaderContext.resetIV = true;\n byteRangeStart = start - 16;\n }\n }\n loaderContext.rangeStart = byteRangeStart;\n loaderContext.rangeEnd = byteRangeEnd;\n }\n return loaderContext;\n}\n\nfunction createGapLoadError(frag: Fragment, part?: Part): LoadError {\n const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);\n const errorData: FragLoadFailResult = {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_GAP,\n fatal: false,\n frag,\n error,\n networkDetails: null,\n };\n if (part) {\n errorData.part = part;\n }\n (part ? part : frag).stats.aborted = true;\n return new LoadError(errorData);\n}\n\nexport class LoadError extends Error {\n public readonly data: FragLoadFailResult;\n constructor(data: FragLoadFailResult) {\n super(data.error.message);\n this.data = data;\n }\n}\n\nexport interface FragLoadFailResult extends ErrorData {\n frag: Fragment;\n part?: Part;\n response?: {\n data: any;\n // error status code\n code: number;\n // error description\n text: string;\n url: string;\n };\n networkDetails: any;\n}\n\nexport type FragmentLoadProgressCallback = (\n result: FragLoadedData | PartsLoadedData,\n) => void;\n","import { ErrorTypes, ErrorDetails } from '../errors';\nimport {\n LoaderStats,\n LoaderResponse,\n LoaderConfiguration,\n LoaderCallbacks,\n Loader,\n KeyLoaderContext,\n PlaylistLevelType,\n} from '../types/loader';\nimport { LoadError } from './fragment-loader';\nimport type { HlsConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { KeyLoadedData } from '../types/events';\nimport type { LevelKey } from './level-key';\nimport type EMEController from '../controller/eme-controller';\nimport type { MediaKeySessionContext } from '../controller/eme-controller';\nimport type { KeySystemFormats } from '../utils/mediakeys-helper';\n\nexport interface KeyLoaderInfo {\n decryptdata: LevelKey;\n keyLoadPromise: Promise<KeyLoadedData> | null;\n loader: Loader<KeyLoaderContext> | null;\n mediaKeySessionContext: MediaKeySessionContext | null;\n}\nexport default class KeyLoader implements ComponentAPI {\n private readonly config: HlsConfig;\n public keyUriToKeyInfo: { [keyuri: string]: KeyLoaderInfo } = {};\n public emeController: EMEController | null = null;\n\n constructor(config: HlsConfig) {\n this.config = config;\n }\n\n abort(type?: PlaylistLevelType) {\n for (const uri in this.keyUriToKeyInfo) {\n const loader = this.keyUriToKeyInfo[uri].loader;\n if (loader) {\n if (type && type !== loader.context?.frag.type) {\n return;\n }\n loader.abort();\n }\n }\n }\n\n detach() {\n for (const uri in this.keyUriToKeyInfo) {\n const keyInfo = this.keyUriToKeyInfo[uri];\n // Remove cached EME keys on detach\n if (\n keyInfo.mediaKeySessionContext ||\n keyInfo.decryptdata.isCommonEncryption\n ) {\n delete this.keyUriToKeyInfo[uri];\n }\n }\n }\n\n destroy() {\n this.detach();\n for (const uri in this.keyUriToKeyInfo) {\n const loader = this.keyUriToKeyInfo[uri].loader;\n if (loader) {\n loader.destroy();\n }\n }\n this.keyUriToKeyInfo = {};\n }\n\n createKeyLoadError(\n frag: Fragment,\n details: ErrorDetails = ErrorDetails.KEY_LOAD_ERROR,\n error: Error,\n networkDetails?: any,\n response?: { url: string; data: undefined; code: number; text: string },\n ): LoadError {\n return new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal: false,\n frag,\n response,\n error,\n networkDetails,\n });\n }\n\n loadClear(\n loadingFrag: Fragment,\n encryptedFragments: Fragment[],\n ): void | Promise<void> {\n if (this.emeController && this.config.emeEnabled) {\n // access key-system with nearest key on start (loaidng frag is unencrypted)\n const { sn, cc } = loadingFrag;\n for (let i = 0; i < encryptedFragments.length; i++) {\n const frag = encryptedFragments[i];\n if (\n cc <= frag.cc &&\n (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)\n ) {\n this.emeController\n .selectKeySystemFormat(frag)\n .then((keySystemFormat) => {\n frag.setKeyFormat(keySystemFormat);\n });\n break;\n }\n }\n }\n }\n\n load(frag: Fragment): Promise<KeyLoadedData> {\n if (!frag.decryptdata && frag.encrypted && this.emeController) {\n // Multiple keys, but none selected, resolve in eme-controller\n return this.emeController\n .selectKeySystemFormat(frag)\n .then((keySystemFormat) => {\n return this.loadInternal(frag, keySystemFormat);\n });\n }\n\n return this.loadInternal(frag);\n }\n\n loadInternal(\n frag: Fragment,\n keySystemFormat?: KeySystemFormats,\n ): Promise<KeyLoadedData> {\n if (keySystemFormat) {\n frag.setKeyFormat(keySystemFormat);\n }\n const decryptdata = frag.decryptdata;\n if (!decryptdata) {\n const error = new Error(\n keySystemFormat\n ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}`\n : 'Missing decryption data on fragment in onKeyLoading',\n );\n return Promise.reject(\n this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error),\n );\n }\n const uri = decryptdata.uri;\n if (!uri) {\n return Promise.reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error(`Invalid key URI: \"${uri}\"`),\n ),\n );\n }\n let keyInfo = this.keyUriToKeyInfo[uri];\n\n if (keyInfo?.decryptdata.key) {\n decryptdata.key = keyInfo.decryptdata.key;\n return Promise.resolve({ frag, keyInfo });\n }\n // Return key load promise as long as it does not have a mediakey session with an unusable key status\n if (keyInfo?.keyLoadPromise) {\n switch (keyInfo.mediaKeySessionContext?.keyStatus) {\n case undefined:\n case 'status-pending':\n case 'usable':\n case 'usable-in-future':\n return keyInfo.keyLoadPromise.then((keyLoadedData) => {\n // Return the correct fragment with updated decryptdata key and loaded keyInfo\n decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;\n return { frag, keyInfo };\n });\n }\n // If we have a key session and status and it is not pending or usable, continue\n // This will go back to the eme-controller for expired keys to get a new keyLoadPromise\n }\n\n // Load the key or return the loading promise\n keyInfo = this.keyUriToKeyInfo[uri] = {\n decryptdata,\n keyLoadPromise: null,\n loader: null,\n mediaKeySessionContext: null,\n };\n\n switch (decryptdata.method) {\n case 'ISO-23001-7':\n case 'SAMPLE-AES':\n case 'SAMPLE-AES-CENC':\n case 'SAMPLE-AES-CTR':\n if (decryptdata.keyFormat === 'identity') {\n // loadKeyHTTP handles http(s) and data URLs\n return this.loadKeyHTTP(keyInfo, frag);\n }\n return this.loadKeyEME(keyInfo, frag);\n case 'AES-128':\n return this.loadKeyHTTP(keyInfo, frag);\n default:\n return Promise.reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error(\n `Key supplied with unsupported METHOD: \"${decryptdata.method}\"`,\n ),\n ),\n );\n }\n }\n\n loadKeyEME(keyInfo: KeyLoaderInfo, frag: Fragment): Promise<KeyLoadedData> {\n const keyLoadedData: KeyLoadedData = { frag, keyInfo };\n if (this.emeController && this.config.emeEnabled) {\n const keySessionContextPromise =\n this.emeController.loadKey(keyLoadedData);\n if (keySessionContextPromise) {\n return (keyInfo.keyLoadPromise = keySessionContextPromise.then(\n (keySessionContext) => {\n keyInfo.mediaKeySessionContext = keySessionContext;\n return keyLoadedData;\n },\n )).catch((error) => {\n // Remove promise for license renewal or retry\n keyInfo.keyLoadPromise = null;\n throw error;\n });\n }\n }\n return Promise.resolve(keyLoadedData);\n }\n\n loadKeyHTTP(keyInfo: KeyLoaderInfo, frag: Fragment): Promise<KeyLoadedData> {\n const config = this.config;\n const Loader = config.loader;\n const keyLoader = new Loader(config) as Loader<KeyLoaderContext>;\n frag.keyLoader = keyInfo.loader = keyLoader;\n\n return (keyInfo.keyLoadPromise = new Promise((resolve, reject) => {\n const loaderContext: KeyLoaderContext = {\n keyInfo,\n frag,\n responseType: 'arraybuffer',\n url: keyInfo.decryptdata.uri,\n };\n\n // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,\n // key-loader will trigger an error and rely on stream-controller to handle retry logic.\n // this will also align retry logic with fragment-loader\n const loadPolicy = config.keyLoadPolicy.default;\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n };\n\n const loaderCallbacks: LoaderCallbacks<KeyLoaderContext> = {\n onSuccess: (\n response: LoaderResponse,\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any,\n ) => {\n const { frag, keyInfo, url: uri } = context;\n if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {\n return reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error('after key load, decryptdata unset or changed'),\n networkDetails,\n ),\n );\n }\n\n keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(\n response.data as ArrayBuffer,\n );\n\n // detach fragment key loader on load success\n frag.keyLoader = null;\n keyInfo.loader = null;\n resolve({ frag, keyInfo });\n },\n\n onError: (\n response: { code: number; text: string },\n context: KeyLoaderContext,\n networkDetails: any,\n stats: LoaderStats,\n ) => {\n this.resetLoader(context);\n reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error(\n `HTTP Error ${response.code} loading key ${response.text}`,\n ),\n networkDetails,\n { url: loaderContext.url, data: undefined, ...response },\n ),\n );\n },\n\n onTimeout: (\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any,\n ) => {\n this.resetLoader(context);\n reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_TIMEOUT,\n new Error('key loading timed out'),\n networkDetails,\n ),\n );\n },\n\n onAbort: (\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any,\n ) => {\n this.resetLoader(context);\n reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.INTERNAL_ABORTED,\n new Error('key loading aborted'),\n networkDetails,\n ),\n );\n },\n };\n\n keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n }));\n }\n\n private resetLoader(context: KeyLoaderContext) {\n const { frag, keyInfo, url: uri } = context;\n const loader = keyInfo.loader;\n if (frag.keyLoader === loader) {\n frag.keyLoader = null;\n keyInfo.loader = null;\n }\n delete this.keyUriToKeyInfo[uri];\n if (loader) {\n loader.destroy();\n }\n }\n}\n","/**\n * @ignore\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\nexport default class TaskLoop {\n private readonly _boundTick: () => void;\n private _tickTimer: number | null = null;\n private _tickInterval: number | null = null;\n private _tickCallCount = 0;\n\n constructor() {\n this._boundTick = this.tick.bind(this);\n }\n\n public destroy() {\n this.onHandlerDestroying();\n this.onHandlerDestroyed();\n }\n\n protected onHandlerDestroying() {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n protected onHandlerDestroyed() {}\n\n public hasInterval(): boolean {\n return !!this._tickInterval;\n }\n\n public hasNextTick(): boolean {\n return !!this._tickTimer;\n }\n\n /**\n * @param millis - Interval time (ms)\n * @eturns True when interval has been scheduled, false when already scheduled (no effect)\n */\n public setInterval(millis: number): boolean {\n if (!this._tickInterval) {\n this._tickCallCount = 0;\n this._tickInterval = self.setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when interval was cleared, false when none was set (no effect)\n */\n public clearInterval(): boolean {\n if (this._tickInterval) {\n self.clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when timeout was cleared, false when none was set (no effect)\n */\n public clearNextTick(): boolean {\n if (this._tickTimer) {\n self.clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n public tick(): void {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.tickImmediate();\n }\n this._tickCallCount = 0;\n }\n }\n\n public tickImmediate(): void {\n this.clearNextTick();\n this._tickTimer = self.setTimeout(this._boundTick, 0);\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n protected doTick(): void {}\n}\n","import type { RemuxerResult } from './remuxer';\nimport type { HlsChunkPerformanceTiming } from './loader';\nimport type { SourceBufferName } from './buffer';\n\nexport interface TransmuxerResult {\n remuxResult: RemuxerResult;\n chunkMeta: ChunkMetadata;\n}\n\nexport class ChunkMetadata {\n public readonly level: number;\n public readonly sn: number;\n public readonly part: number;\n public readonly id: number;\n public readonly size: number;\n public readonly partial: boolean;\n public readonly transmuxing: HlsChunkPerformanceTiming =\n getNewPerformanceTiming();\n public readonly buffering: {\n [key in SourceBufferName]: HlsChunkPerformanceTiming;\n } = {\n audio: getNewPerformanceTiming(),\n video: getNewPerformanceTiming(),\n audiovideo: getNewPerformanceTiming(),\n };\n\n constructor(\n level: number,\n sn: number,\n id: number,\n size = 0,\n part = -1,\n partial = false,\n ) {\n this.level = level;\n this.sn = sn;\n this.id = id;\n this.size = size;\n this.part = part;\n this.partial = partial;\n }\n}\n\nfunction getNewPerformanceTiming(): HlsChunkPerformanceTiming {\n return { start: 0, executeStart: 0, executeEnd: 0, end: 0 };\n}\n","import { logger } from './logger';\nimport { adjustSliding } from './level-helper';\n\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../loader/level-details';\n\nexport function findFirstFragWithCC(\n fragments: Fragment[],\n cc: number,\n): Fragment | null {\n for (let i = 0, len = fragments.length; i < len; i++) {\n if (fragments[i]?.cc === cc) {\n return fragments[i];\n }\n }\n return null;\n}\n\nexport function shouldAlignOnDiscontinuities(\n lastFrag: Fragment | null,\n switchDetails: LevelDetails | undefined,\n details: LevelDetails,\n): switchDetails is LevelDetails & boolean {\n if (switchDetails) {\n if (\n details.endCC > details.startCC ||\n (lastFrag && lastFrag.cc < details.startCC)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag(\n prevDetails: LevelDetails,\n curDetails: LevelDetails,\n) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nfunction adjustFragmentStart(frag: Fragment, sliding: number) {\n if (frag) {\n const start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n}\n\nexport function adjustSlidingStart(sliding: number, details: LevelDetails) {\n // Update segments\n const fragments = details.fragments;\n for (let i = 0, len = fragments.length; i < len; i++) {\n adjustFragmentStart(fragments[i], sliding);\n }\n // Update LL-HLS parts at the end of the playlist\n if (details.fragmentHint) {\n adjustFragmentStart(details.fragmentHint, sliding);\n }\n details.alignedSliding = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastFrag\n * @param lastLevel\n * @param details\n */\nexport function alignStream(\n lastFrag: Fragment | null,\n switchDetails: LevelDetails | undefined,\n details: LevelDetails,\n) {\n if (!switchDetails) {\n return;\n }\n alignDiscontinuities(lastFrag, details, switchDetails);\n if (!details.alignedSliding && switchDetails) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignMediaPlaylistByPDT(details, switchDetails);\n }\n if (!details.alignedSliding && switchDetails && !details.skippedSegments) {\n // Try to align on sn so that we pick a better start fragment.\n // Do not perform this on playlists with delta updates as this is only to align levels on switch\n // and adjustSliding only adjusts fragments after skippedSegments.\n adjustSliding(switchDetails, details);\n }\n}\n\n/**\n * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n * discontinuity sequence.\n * @param lastFrag - The last Fragment which shares the same discontinuity sequence\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nfunction alignDiscontinuities(\n lastFrag: Fragment | null,\n details: LevelDetails,\n switchDetails: LevelDetails | undefined,\n) {\n if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(\n switchDetails,\n details,\n );\n if (referenceFrag && Number.isFinite(referenceFrag.start)) {\n logger.log(\n `Adjusting PTS using last level due to CC increase within current level ${details.url}`,\n );\n adjustSlidingStart(referenceFrag.start, details);\n }\n }\n}\n\n/**\n * Ensures appropriate time-alignment between renditions based on PDT.\n * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs\n * for the last discontinuity sequence number shared by both playlists when present,\n * and uses the \"wallclock\"/PDT timeline as a cross-reference to `details`, adjusting the presentation\n * times/timelines of `details` accordingly.\n * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,\n * the primary purpose of this function is to ensure the \"local timelines\" of audio/subtitle tracks\n * are aligned to the main/video timeline, using PDT as the cross-reference/\"anchor\" that should\n * be consistent across playlists, per the HLS spec.\n * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).\n * @param refDetails - The details of the reference rendition with start and PDT times for alignment.\n */\nexport function alignMediaPlaylistByPDT(\n details: LevelDetails,\n refDetails: LevelDetails,\n) {\n if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {\n return;\n }\n\n const fragments = details.fragments;\n const refFragments = refDetails.fragments;\n if (!fragments.length || !refFragments.length) {\n return;\n }\n\n // Calculate a delta to apply to all fragments according to the delta in PDT times and start times\n // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.\n // If a fragment of the same discontinuity was not found use the middle fragment of both.\n let refFrag: Fragment | null | undefined;\n let frag: Fragment | null | undefined;\n const targetCC = Math.min(refDetails.endCC, details.endCC);\n if (refDetails.startCC < targetCC && details.startCC < targetCC) {\n refFrag = findFirstFragWithCC(refFragments, targetCC);\n frag = findFirstFragWithCC(fragments, targetCC);\n }\n if (!refFrag || !frag) {\n refFrag = refFragments[Math.floor(refFragments.length / 2)];\n frag =\n findFirstFragWithCC(fragments, refFrag.cc) ||\n fragments[Math.floor(fragments.length / 2)];\n }\n const refPDT = refFrag.programDateTime;\n const targetPDT = frag.programDateTime;\n if (!refPDT || !targetPDT) {\n return;\n }\n\n const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);\n adjustSlidingStart(delta, details);\n}\n","export default class AESCrypto {\n private subtle: SubtleCrypto;\n private aesIV: Uint8Array;\n\n constructor(subtle: SubtleCrypto, iv: Uint8Array) {\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n decrypt(data: ArrayBuffer, key: CryptoKey) {\n return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);\n }\n}\n","export default class FastAESKey {\n private subtle: SubtleCrypto;\n private key: ArrayBuffer;\n\n constructor(subtle: SubtleCrypto, key: ArrayBuffer) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey() {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, [\n 'encrypt',\n 'decrypt',\n ]);\n }\n}\n","import { sliceUint8 } from '../utils/typed-array';\n\n// PKCS7\nexport function removePadding(array: Uint8Array): Uint8Array {\n const outputBytes = array.byteLength;\n const paddingBytes =\n outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return sliceUint8(array, 0, outputBytes - paddingBytes);\n }\n return array;\n}\n\nexport default class AESDecryptor {\n private rcon: Array<number> = [\n 0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,\n ];\n private subMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private invSubMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private sBox: Uint32Array = new Uint32Array(256);\n private invSBox: Uint32Array = new Uint32Array(256);\n private key: Uint32Array = new Uint32Array(0);\n\n private ksRows: number = 0;\n private keySize: number = 0;\n private keySchedule!: Uint32Array;\n private invKeySchedule!: Uint32Array;\n\n constructor() {\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_(arrayBuffer) {\n const view = new DataView(arrayBuffer);\n const newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n }\n\n initTable() {\n const sBox = this.sBox;\n const invSBox = this.invSBox;\n const subMix = this.subMix;\n const subMix0 = subMix[0];\n const subMix1 = subMix[1];\n const subMix2 = subMix[2];\n const subMix3 = subMix[3];\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n const x2 = d[x];\n const x4 = d[x2];\n const x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey(keyBuffer: ArrayBuffer) {\n // convert keyBuffer to Uint32Array\n const key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = key[offset] === this.key[offset];\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n const keySize = (this.keySize = key.length);\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n const ksRows = (this.ksRows = (keySize + 6 + 1) * 4);\n let ksRow;\n let invKsRow;\n\n const keySchedule = (this.keySchedule = new Uint32Array(ksRows));\n const invKeySchedule = (this.invKeySchedule = new Uint32Array(ksRows));\n const sbox = this.sBox;\n const rcon = this.rcon;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] =\n invSubMix0[sbox[t >>> 24]] ^\n invSubMix1[sbox[(t >>> 16) & 0xff]] ^\n invSubMix2[sbox[(t >>> 8) & 0xff]] ^\n invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap(word) {\n return (\n (word << 24) |\n ((word & 0xff00) << 8) |\n ((word & 0xff0000) >> 8) |\n (word >>> 24)\n );\n }\n\n decrypt(inputArrayBuffer: ArrayBuffer, offset: number, aesIV: ArrayBuffer) {\n const nRounds = this.keySize + 6;\n const invKeySchedule = this.invKeySchedule;\n const invSBOX = this.invSBox;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n const inputInt32 = new Int32Array(inputArrayBuffer);\n const outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n let ksRow, i;\n const swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 =\n invSubMix0[s0 >>> 24] ^\n invSubMix1[(s1 >> 16) & 0xff] ^\n invSubMix2[(s2 >> 8) & 0xff] ^\n invSubMix3[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n invSubMix0[s1 >>> 24] ^\n invSubMix1[(s2 >> 16) & 0xff] ^\n invSubMix2[(s3 >> 8) & 0xff] ^\n invSubMix3[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n invSubMix0[s2 >>> 24] ^\n invSubMix1[(s3 >> 16) & 0xff] ^\n invSubMix2[(s0 >> 8) & 0xff] ^\n invSubMix3[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n invSubMix0[s3 >>> 24] ^\n invSubMix1[(s0 >> 16) & 0xff] ^\n invSubMix2[(s1 >> 8) & 0xff] ^\n invSubMix3[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 =\n (invSBOX[s0 >>> 24] << 24) ^\n (invSBOX[(s1 >> 16) & 0xff] << 16) ^\n (invSBOX[(s2 >> 8) & 0xff] << 8) ^\n invSBOX[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n (invSBOX[s1 >>> 24] << 24) ^\n (invSBOX[(s2 >> 16) & 0xff] << 16) ^\n (invSBOX[(s3 >> 8) & 0xff] << 8) ^\n invSBOX[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n (invSBOX[s2 >>> 24] << 24) ^\n (invSBOX[(s3 >> 16) & 0xff] << 16) ^\n (invSBOX[(s0 >> 8) & 0xff] << 8) ^\n invSBOX[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n (invSBOX[s3 >>> 24] << 24) ^\n (invSBOX[(s0 >> 16) & 0xff] << 16) ^\n (invSBOX[(s1 >> 8) & 0xff] << 8) ^\n invSBOX[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return outputInt32.buffer;\n }\n}\n","import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor, { removePadding } from './aes-decryptor';\nimport { logger } from '../utils/logger';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { sliceUint8 } from '../utils/typed-array';\nimport type { HlsConfig } from '../config';\n\nconst CHUNK_SIZE = 16; // 16 bytes, 128 bits\n\nexport default class Decrypter {\n private logEnabled: boolean = true;\n private removePKCS7Padding: boolean;\n private subtle: SubtleCrypto | null = null;\n private softwareDecrypter: AESDecryptor | null = null;\n private key: ArrayBuffer | null = null;\n private fastAesKey: FastAESKey | null = null;\n private remainderData: Uint8Array | null = null;\n private currentIV: ArrayBuffer | null = null;\n private currentResult: ArrayBuffer | null = null;\n private useSoftware: boolean;\n\n constructor(config: HlsConfig, { removePKCS7Padding = true } = {}) {\n this.useSoftware = config.enableSoftwareAES;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = self.crypto;\n if (browserCrypto) {\n this.subtle =\n browserCrypto.subtle ||\n ((browserCrypto as any).webkitSubtle as SubtleCrypto);\n }\n } catch (e) {\n /* no-op */\n }\n }\n\n this.useSoftware = !this.subtle;\n }\n\n destroy() {\n this.subtle = null;\n this.softwareDecrypter = null;\n this.key = null;\n this.fastAesKey = null;\n this.remainderData = null;\n this.currentIV = null;\n this.currentResult = null;\n }\n\n public isSync() {\n return this.useSoftware;\n }\n\n public flush(): Uint8Array | null {\n const { currentResult, remainderData } = this;\n if (!currentResult || remainderData) {\n this.reset();\n return null;\n }\n const data = new Uint8Array(currentResult);\n this.reset();\n if (this.removePKCS7Padding) {\n return removePadding(data);\n }\n return data;\n }\n\n public reset() {\n this.currentResult = null;\n this.currentIV = null;\n this.remainderData = null;\n if (this.softwareDecrypter) {\n this.softwareDecrypter = null;\n }\n }\n\n public decrypt(\n data: Uint8Array | ArrayBuffer,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): Promise<ArrayBuffer> {\n if (this.useSoftware) {\n return new Promise((resolve, reject) => {\n this.softwareDecrypt(new Uint8Array(data), key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n resolve(decryptResult.buffer);\n } else {\n reject(new Error('[softwareDecrypt] Failed to decrypt data'));\n }\n });\n }\n return this.webCryptoDecrypt(new Uint8Array(data), key, iv);\n }\n\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n public softwareDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): ArrayBuffer | null {\n const { currentIV, currentResult, remainderData } = this;\n this.logOnce('JS AES decrypt');\n // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call\n // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached\n // the end on flush(), but by that time we have already received all bytes for the segment.\n // Progressive decryption does not work with WebCrypto\n\n if (remainderData) {\n data = appendUint8Array(remainderData, data);\n this.remainderData = null;\n }\n\n // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)\n const currentChunk = this.getValidChunk(data);\n if (!currentChunk.length) {\n return null;\n }\n\n if (currentIV) {\n iv = currentIV;\n }\n\n let softwareDecrypter = this.softwareDecrypter;\n if (!softwareDecrypter) {\n softwareDecrypter = this.softwareDecrypter = new AESDecryptor();\n }\n softwareDecrypter.expandKey(key);\n\n const result = currentResult;\n\n this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);\n this.currentIV = sliceUint8(currentChunk, -16).buffer;\n\n if (!result) {\n return null;\n }\n return result;\n }\n\n public webCryptoDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): Promise<ArrayBuffer> {\n if (this.key !== key || !this.fastAesKey) {\n if (!this.subtle) {\n return Promise.resolve(this.onWebCryptoError(data, key, iv));\n }\n this.key = key;\n this.fastAesKey = new FastAESKey(this.subtle, key);\n }\n return this.fastAesKey\n .expandKey()\n .then((aesKey) => {\n // decrypt using web crypto\n if (!this.subtle) {\n return Promise.reject(new Error('web crypto not initialized'));\n }\n this.logOnce('WebCrypto AES decrypt');\n const crypto = new AESCrypto(this.subtle, new Uint8Array(iv));\n return crypto.decrypt(data.buffer, aesKey);\n })\n .catch((err) => {\n logger.warn(\n `[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`,\n );\n\n return this.onWebCryptoError(data, key, iv);\n });\n }\n\n private onWebCryptoError(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): ArrayBuffer | never {\n this.useSoftware = true;\n this.logEnabled = true;\n this.softwareDecrypt(data, key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n return decryptResult.buffer;\n }\n throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');\n }\n\n private getValidChunk(data: Uint8Array): Uint8Array {\n let currentChunk = data;\n const splitPoint = data.length - (data.length % CHUNK_SIZE);\n if (splitPoint !== data.length) {\n currentChunk = sliceUint8(data, 0, splitPoint);\n this.remainderData = sliceUint8(data, splitPoint);\n }\n return currentChunk;\n }\n\n private logOnce(msg: string) {\n if (!this.logEnabled) {\n return;\n }\n logger.log(`[decrypter]: ${msg}`);\n this.logEnabled = false;\n }\n}\n","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r: TimeRanges) {\n let log = '';\n const len = r.length;\n for (let i = 0; i < len; i++) {\n log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;\n }\n\n return log;\n },\n};\n\nexport default TimeRanges;\n","import TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport { Bufferable, BufferHelper, BufferInfo } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\nimport { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { alignStream } from '../utils/discontinuities';\nimport {\n findFragmentByPDT,\n findFragmentByPTS,\n findFragWithCC,\n} from './fragment-finders';\nimport {\n findPart,\n getFragmentWithSN,\n getPartWith,\n updateFragPTSDTS,\n} from '../utils/level-helper';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { Fragment, Part } from '../loader/fragment';\nimport FragmentLoader, {\n FragmentLoadProgressCallback,\n LoadError,\n} from '../loader/fragment-loader';\nimport KeyLoader from '../loader/key-loader';\nimport { LevelDetails } from '../loader/level-details';\nimport Decrypter from '../crypt/decrypter';\nimport TimeRanges from '../utils/time-ranges';\nimport { PlaylistLevelType } from '../types/loader';\nimport { getRetryDelay } from '../utils/error-helper';\nimport { NetworkErrorAction } from './error-controller';\nimport type {\n BufferAppendingData,\n ErrorData,\n FragLoadedData,\n PartsLoadedData,\n KeyLoadedData,\n MediaAttachedData,\n BufferFlushingData,\n ManifestLoadedData,\n} from '../types/events';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type { Level } from '../types/level';\nimport type { RemuxedTrack } from '../types/remuxer';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { SourceBufferName } from '../types/buffer';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\ntype ResolveFragLoaded = (FragLoadedEndData) => void;\ntype RejectFragLoaded = (LoadError) => void;\n\nexport const State = {\n STOPPED: 'STOPPED',\n IDLE: 'IDLE',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK: 'WAITING_TRACK',\n PARSING: 'PARSING',\n PARSED: 'PARSED',\n ENDED: 'ENDED',\n ERROR: 'ERROR',\n WAITING_INIT_PTS: 'WAITING_INIT_PTS',\n WAITING_LEVEL: 'WAITING_LEVEL',\n};\n\nexport default class BaseStreamController\n extends TaskLoop\n implements NetworkComponentAPI\n{\n protected hls: Hls;\n\n protected fragPrevious: Fragment | null = null;\n protected fragCurrent: Fragment | null = null;\n protected fragmentTracker: FragmentTracker;\n protected transmuxer: TransmuxerInterface | null = null;\n protected _state: string = State.STOPPED;\n protected playlistType: PlaylistLevelType;\n protected media: HTMLMediaElement | null = null;\n protected mediaBuffer: Bufferable | null = null;\n protected config: HlsConfig;\n protected bitrateTest: boolean = false;\n protected lastCurrentTime: number = 0;\n protected nextLoadPosition: number = 0;\n protected startPosition: number = 0;\n protected startTimeOffset: number | null = null;\n protected loadedmetadata: boolean = false;\n protected retryDate: number = 0;\n protected levels: Array<Level> | null = null;\n protected fragmentLoader: FragmentLoader;\n protected keyLoader: KeyLoader;\n protected levelLastLoaded: Level | null = null;\n protected startFragRequested: boolean = false;\n protected decrypter: Decrypter;\n protected initPTS: RationalTimestamp[] = [];\n protected onvseeking: EventListener | null = null;\n protected onvended: EventListener | null = null;\n\n private readonly logPrefix: string = '';\n protected log: (msg: any) => void;\n protected warn: (msg: any) => void;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader,\n logPrefix: string,\n playlistType: PlaylistLevelType,\n ) {\n super();\n this.playlistType = playlistType;\n this.logPrefix = logPrefix;\n this.log = logger.log.bind(logger, `${logPrefix}:`);\n this.warn = logger.warn.bind(logger, `${logPrefix}:`);\n this.hls = hls;\n this.fragmentLoader = new FragmentLoader(hls.config);\n this.keyLoader = keyLoader;\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.decrypter = new Decrypter(hls.config);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n\n protected doTick() {\n this.onTickEnd();\n }\n\n protected onTickEnd() {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public startLoad(startPosition: number): void {}\n\n public stopLoad() {\n this.fragmentLoader.abort();\n this.keyLoader.abort(this.playlistType);\n const frag = this.fragCurrent;\n if (frag?.loader) {\n frag.abortRequests();\n this.fragmentTracker.removeFragment(frag);\n }\n this.resetTransmuxer();\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.clearInterval();\n this.clearNextTick();\n this.state = State.STOPPED;\n }\n\n protected _streamEnded(\n bufferInfo: BufferInfo,\n levelDetails: LevelDetails,\n ): boolean {\n // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,\n // of nothing loading/loaded return false\n if (\n levelDetails.live ||\n bufferInfo.nextStart ||\n !bufferInfo.end ||\n !this.media\n ) {\n return false;\n }\n const partList = levelDetails.partList;\n // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,\n // check instead if the last part is buffered.\n if (partList?.length) {\n const lastPart = partList[partList.length - 1];\n\n // Checking the midpoint of the part for potential margin of error and related issues.\n // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)\n // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream\n // part mismatches for independent audio and video playlists/segments.\n const lastPartBuffered = BufferHelper.isBuffered(\n this.media,\n lastPart.start + lastPart.duration / 2,\n );\n return lastPartBuffered;\n }\n\n const playlistType =\n levelDetails.fragments[levelDetails.fragments.length - 1].type;\n return this.fragmentTracker.isEndListAppended(playlistType);\n }\n\n protected getLevelDetails(): LevelDetails | undefined {\n if (this.levels && this.levelLastLoaded !== null) {\n return this.levelLastLoaded?.details;\n }\n }\n\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ) {\n const media = (this.media = this.mediaBuffer = data.media);\n this.onvseeking = this.onMediaSeeking.bind(this) as EventListener;\n this.onvended = this.onMediaEnded.bind(this) as EventListener;\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n const config = this.config;\n if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {\n this.startLoad(config.startPosition);\n }\n }\n\n protected onMediaDetaching() {\n const media = this.media;\n if (media?.ended) {\n this.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // remove video listeners\n if (media && this.onvseeking && this.onvended) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvended = null;\n }\n if (this.keyLoader) {\n this.keyLoader.detach();\n }\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.fragmentTracker.removeAllFragments();\n this.stopLoad();\n }\n\n protected onMediaSeeking() {\n const { config, fragCurrent, media, mediaBuffer, state } = this;\n const currentTime: number = media ? media.currentTime : 0;\n const bufferInfo = BufferHelper.bufferInfo(\n mediaBuffer ? mediaBuffer : media,\n currentTime,\n config.maxBufferHole,\n );\n\n this.log(\n `media seeking to ${\n Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime\n }, state: ${state}`,\n );\n\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n } else if (fragCurrent) {\n // Seeking while frag load is in progress\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset =\n fragCurrent.start + fragCurrent.duration + tolerance;\n // if seeking out of buffered range or into new one\n if (\n !bufferInfo.len ||\n fragEndOffset < bufferInfo.start ||\n fragStartOffset > bufferInfo.end\n ) {\n const pastFragment = currentTime > fragEndOffset;\n // if the seek position is outside the current fragment range\n if (currentTime < fragStartOffset || pastFragment) {\n if (pastFragment && fragCurrent.loader) {\n this.log(\n 'seeking outside of buffer while fragment load in progress, cancel fragment load',\n );\n fragCurrent.abortRequests();\n this.resetLoadingState();\n }\n this.fragPrevious = null;\n }\n }\n }\n\n if (media) {\n // Remove gap fragments\n this.fragmentTracker.removeFragmentsInRange(\n currentTime,\n Infinity,\n this.playlistType,\n true,\n );\n\n this.lastCurrentTime = currentTime;\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.loadedmetadata && !bufferInfo.len) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // Async tick to speed up processing\n this.tickImmediate();\n }\n\n protected onMediaEnded() {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n protected onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ): void {\n this.startTimeOffset = data.startTimeOffset;\n this.initPTS = [];\n }\n\n protected onHandlerDestroying() {\n this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n this.stopLoad();\n super.onHandlerDestroying();\n // @ts-ignore\n this.hls = null;\n }\n\n protected onHandlerDestroyed() {\n this.state = State.STOPPED;\n if (this.fragmentLoader) {\n this.fragmentLoader.destroy();\n }\n if (this.keyLoader) {\n this.keyLoader.destroy();\n }\n if (this.decrypter) {\n this.decrypter.destroy();\n }\n\n this.hls =\n this.log =\n this.warn =\n this.decrypter =\n this.keyLoader =\n this.fragmentLoader =\n this.fragmentTracker =\n null as any;\n super.onHandlerDestroyed();\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number,\n ) {\n this._loadFragForPlayback(frag, level, targetBufferTime);\n }\n\n private _loadFragForPlayback(\n frag: Fragment,\n level: Level,\n targetBufferTime: number,\n ) {\n const progressCallback: FragmentLoadProgressCallback = (\n data: FragLoadedData,\n ) => {\n if (this.fragContextChanged(frag)) {\n this.warn(\n `Fragment ${frag.sn}${\n data.part ? ' p: ' + data.part.index : ''\n } of level ${frag.level} was dropped during download.`,\n );\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n frag.stats.chunkCount++;\n this._handleFragmentLoadProgress(data);\n };\n\n this._doFragLoad(frag, level, targetBufferTime, progressCallback)\n .then((data) => {\n if (!data) {\n // if we're here we probably needed to backtrack or are waiting for more parts\n return;\n }\n const state = this.state;\n if (this.fragContextChanged(frag)) {\n if (\n state === State.FRAG_LOADING ||\n (!this.fragCurrent && state === State.PARSING)\n ) {\n this.fragmentTracker.removeFragment(frag);\n this.state = State.IDLE;\n }\n return;\n }\n\n if ('payload' in data) {\n this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);\n this.hls.trigger(Events.FRAG_LOADED, data);\n }\n\n // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback\n this._handleFragmentLoadComplete(data);\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(`Frag error: ${reason?.message || reason}`);\n this.resetFragmentLoading(frag);\n });\n }\n\n protected clearTrackerIfNeeded(frag: Fragment) {\n const { fragmentTracker } = this;\n const fragState = fragmentTracker.getState(frag);\n if (fragState === FragmentState.APPENDING) {\n // Lower the max buffer length and try again\n const playlistType = frag.type as PlaylistLevelType;\n const bufferedInfo = this.getFwdBufferInfo(\n this.mediaBuffer,\n playlistType,\n );\n const minForwardBufferLength = Math.max(\n frag.duration,\n bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength,\n );\n // If backtracking, always remove from the tracker without reducing max buffer length\n const backtrackFragment = (this as any).backtrackFragment as\n | Fragment\n | undefined;\n const backtracked = backtrackFragment\n ? (frag.sn as number) - (backtrackFragment.sn as number)\n : 0;\n if (\n backtracked === 1 ||\n this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)\n ) {\n fragmentTracker.removeFragment(frag);\n }\n } else if (this.mediaBuffer?.buffered.length === 0) {\n // Stop gap for bad tracker / buffer flush behavior\n fragmentTracker.removeAllFragments();\n } else if (fragmentTracker.hasParts(frag.type)) {\n // In low latency mode, remove fragments for which only some parts were buffered\n fragmentTracker.detectPartialFragments({\n frag,\n part: null,\n stats: frag.stats,\n id: frag.type,\n });\n if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {\n fragmentTracker.removeFragment(frag);\n }\n }\n }\n\n protected checkLiveUpdate(details: LevelDetails) {\n if (details.updated && !details.live) {\n // Live stream ended, update fragment tracker\n const lastFragment = details.fragments[details.fragments.length - 1];\n this.fragmentTracker.detectPartialFragments({\n frag: lastFragment,\n part: null,\n stats: lastFragment.stats,\n id: lastFragment.type,\n });\n }\n if (!details.fragments[0]) {\n details.deltaUpdateFailed = true;\n }\n }\n\n protected flushMainBuffer(\n startOffset: number,\n endOffset: number,\n type: SourceBufferName | null = null,\n ) {\n if (!(startOffset - endOffset)) {\n return;\n }\n // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,\n // passing a null type flushes both buffers\n const flushScope: BufferFlushingData = { startOffset, endOffset, type };\n this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);\n }\n\n protected _loadInitSegment(frag: Fragment, level: Level) {\n this._doFragLoad(frag, level)\n .then((data) => {\n if (!data || this.fragContextChanged(frag) || !this.levels) {\n throw new Error('init load aborted');\n }\n\n return data;\n })\n .then((data: FragLoadedData) => {\n const { hls } = this;\n const { payload } = data;\n const decryptData = frag.decryptdata;\n\n // check to see if the payload needs to be decrypted\n if (\n payload &&\n payload.byteLength > 0 &&\n decryptData?.key &&\n decryptData.iv &&\n decryptData.method === 'AES-128'\n ) {\n const startTime = self.performance.now();\n // decrypt init segment data\n return this.decrypter\n .decrypt(\n new Uint8Array(payload),\n decryptData.key.buffer,\n decryptData.iv.buffer,\n )\n .catch((err) => {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_DECRYPT_ERROR,\n fatal: false,\n error: err,\n reason: err.message,\n frag,\n });\n throw err;\n })\n .then((decryptedData) => {\n const endTime = self.performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime,\n },\n });\n data.payload = decryptedData;\n return this.completeInitSegmentLoad(data);\n });\n }\n return this.completeInitSegmentLoad(data);\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(reason);\n this.resetFragmentLoading(frag);\n });\n }\n\n private completeInitSegmentLoad(data: FragLoadedData) {\n const { levels } = this;\n if (!levels) {\n throw new Error('init load aborted, missing levels');\n }\n const stats = data.frag.stats;\n this.state = State.IDLE;\n data.frag.data = new Uint8Array(data.payload);\n stats.parsing.start = stats.buffering.start = self.performance.now();\n stats.parsing.end = stats.buffering.end = self.performance.now();\n this.tick();\n }\n\n protected fragContextChanged(frag: Fragment | null) {\n const { fragCurrent } = this;\n return (\n !frag ||\n !fragCurrent ||\n frag.sn !== fragCurrent.sn ||\n frag.level !== fragCurrent.level\n );\n }\n\n protected fragBufferedComplete(frag: Fragment, part: Part | null) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n this.log(\n `Buffered ${frag.type} sn: ${frag.sn}${\n part ? ' part: ' + part.index : ''\n } of ${\n this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track'\n } ${frag.level} (frag:[${(frag.startPTS ?? NaN).toFixed(3)}-${(\n frag.endPTS ?? NaN\n ).toFixed(3)}] > buffer:${\n media\n ? TimeRanges.toString(BufferHelper.getBuffered(media))\n : '(detached)'\n })`,\n );\n if (frag.sn !== 'initSegment') {\n if (frag.type !== PlaylistLevelType.SUBTITLE) {\n const el = frag.elementaryStreams;\n if (!Object.keys(el).some((type) => !!el[type])) {\n // empty segment\n this.state = State.IDLE;\n return;\n }\n }\n const level = this.levels?.[frag.level];\n if (level?.fragmentError) {\n this.log(\n `Resetting level fragment error count of ${level.fragmentError} on frag buffered`,\n );\n level.fragmentError = 0;\n }\n }\n this.state = State.IDLE;\n if (!media) {\n return;\n }\n if (\n !this.loadedmetadata &&\n frag.type == PlaylistLevelType.MAIN &&\n media.buffered.length &&\n this.fragCurrent?.sn === this.fragPrevious?.sn\n ) {\n this.loadedmetadata = true;\n this.seekToStartPos();\n }\n this.tick();\n }\n\n protected seekToStartPos() {}\n\n protected _handleFragmentLoadComplete(fragLoadedEndData: PartsLoadedData) {\n const { transmuxer } = this;\n if (!transmuxer) {\n return;\n }\n const { frag, part, partsLoaded } = fragLoadedEndData;\n // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data\n const complete =\n !partsLoaded ||\n partsLoaded.length === 0 ||\n partsLoaded.some((fragLoaded) => !fragLoaded);\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount + 1,\n 0,\n part ? part.index : -1,\n !complete,\n );\n transmuxer.flush(chunkMeta);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected _handleFragmentLoadProgress(\n frag: PartsLoadedData | FragLoadedData,\n ) {}\n\n protected _doFragLoad(\n frag: Fragment,\n level: Level,\n targetBufferTime: number | null = null,\n progressCallback?: FragmentLoadProgressCallback,\n ): Promise<PartsLoadedData | FragLoadedData | null> {\n const details = level?.details;\n if (!this.levels || !details) {\n throw new Error(\n `frag load aborted, missing level${details ? '' : ' detail'}s`,\n );\n }\n\n let keyLoadingPromise: Promise<KeyLoadedData | void> | null = null;\n if (frag.encrypted && !frag.decryptdata?.key) {\n this.log(\n `Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${\n this.logPrefix === '[stream-controller]' ? 'level' : 'track'\n } ${frag.level}`,\n );\n this.state = State.KEY_LOADING;\n this.fragCurrent = frag;\n keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {\n if (!this.fragContextChanged(keyLoadedData.frag)) {\n this.hls.trigger(Events.KEY_LOADED, keyLoadedData);\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n }\n return keyLoadedData;\n }\n });\n this.hls.trigger(Events.KEY_LOADING, { frag });\n if (this.fragCurrent === null) {\n keyLoadingPromise = Promise.reject(\n new Error(`frag load aborted, context changed in KEY_LOADING`),\n );\n }\n } else if (!frag.encrypted && details.encryptedFragments.length) {\n this.keyLoader.loadClear(frag, details.encryptedFragments);\n }\n\n targetBufferTime = Math.max(frag.start, targetBufferTime || 0);\n if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {\n const partList = details.partList;\n if (partList && progressCallback) {\n if (targetBufferTime > frag.end && details.fragmentHint) {\n frag = details.fragmentHint;\n }\n const partIndex = this.getNextPart(partList, frag, targetBufferTime);\n if (partIndex > -1) {\n const part = partList[partIndex];\n this.log(\n `Loading part sn: ${frag.sn} p: ${part.index} cc: ${\n frag.cc\n } of playlist [${details.startSN}-${\n details.endSN\n }] parts [0-${partIndex}-${partList.length - 1}] ${\n this.logPrefix === '[stream-controller]' ? 'level' : 'track'\n }: ${frag.level}, target: ${parseFloat(\n targetBufferTime.toFixed(3),\n )}`,\n );\n this.nextLoadPosition = part.start + part.duration;\n this.state = State.FRAG_LOADING;\n let result: Promise<PartsLoadedData | FragLoadedData | null>;\n if (keyLoadingPromise) {\n result = keyLoadingPromise\n .then((keyLoadedData) => {\n if (\n !keyLoadedData ||\n this.fragContextChanged(keyLoadedData.frag)\n ) {\n return null;\n }\n return this.doFragPartsLoad(\n frag,\n part,\n level,\n progressCallback,\n );\n })\n .catch((error) => this.handleFragLoadError(error));\n } else {\n result = this.doFragPartsLoad(\n frag,\n part,\n level,\n progressCallback,\n ).catch((error: LoadError) => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, {\n frag,\n part,\n targetBufferTime,\n });\n if (this.fragCurrent === null) {\n return Promise.reject(\n new Error(\n `frag load aborted, context changed in FRAG_LOADING parts`,\n ),\n );\n }\n return result;\n } else if (\n !frag.url ||\n this.loadedEndOfParts(partList, targetBufferTime)\n ) {\n // Fragment hint has no parts\n return Promise.resolve(null);\n }\n }\n }\n\n this.log(\n `Loading fragment ${frag.sn} cc: ${frag.cc} ${\n details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : ''\n }${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${\n frag.level\n }, target: ${parseFloat(targetBufferTime.toFixed(3))}`,\n );\n // Don't update nextLoadPosition for fragments which are not buffered\n if (Number.isFinite(frag.sn as number) && !this.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n this.state = State.FRAG_LOADING;\n\n // Load key before streaming fragment data\n const dataOnProgress = this.config.progressive;\n let result: Promise<PartsLoadedData | FragLoadedData | null>;\n if (dataOnProgress && keyLoadingPromise) {\n result = keyLoadingPromise\n .then((keyLoadedData) => {\n if (!keyLoadedData || this.fragContextChanged(keyLoadedData?.frag)) {\n return null;\n }\n return this.fragmentLoader.load(frag, progressCallback);\n })\n .catch((error) => this.handleFragLoadError(error));\n } else {\n // load unencrypted fragment data with progress event,\n // or handle fragment result after key and fragment are finished loading\n result = Promise.all([\n this.fragmentLoader.load(\n frag,\n dataOnProgress ? progressCallback : undefined,\n ),\n keyLoadingPromise,\n ])\n .then(([fragLoadedData]) => {\n if (!dataOnProgress && fragLoadedData && progressCallback) {\n progressCallback(fragLoadedData);\n }\n return fragLoadedData;\n })\n .catch((error) => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, { frag, targetBufferTime });\n if (this.fragCurrent === null) {\n return Promise.reject(\n new Error(`frag load aborted, context changed in FRAG_LOADING`),\n );\n }\n return result;\n }\n\n private doFragPartsLoad(\n frag: Fragment,\n fromPart: Part,\n level: Level,\n progressCallback: FragmentLoadProgressCallback,\n ): Promise<PartsLoadedData | null> {\n return new Promise(\n (resolve: ResolveFragLoaded, reject: RejectFragLoaded) => {\n const partsLoaded: FragLoadedData[] = [];\n const initialPartList = level.details?.partList;\n const loadPart = (part: Part) => {\n this.fragmentLoader\n .loadPart(frag, part, progressCallback)\n .then((partLoadedData: FragLoadedData) => {\n partsLoaded[part.index] = partLoadedData;\n const loadedPart = partLoadedData.part as Part;\n this.hls.trigger(Events.FRAG_LOADED, partLoadedData);\n const nextPart =\n getPartWith(level, frag.sn as number, part.index + 1) ||\n findPart(initialPartList, frag.sn as number, part.index + 1);\n if (nextPart) {\n loadPart(nextPart);\n } else {\n return resolve({\n frag,\n part: loadedPart,\n partsLoaded,\n });\n }\n })\n .catch(reject);\n };\n loadPart(fromPart);\n },\n );\n }\n\n private handleFragLoadError(error: LoadError | Error) {\n if ('data' in error) {\n const data = error.data;\n if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {\n this.handleFragLoadAborted(data.frag, data.part);\n } else {\n this.hls.trigger(Events.ERROR, data as ErrorData);\n }\n } else {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n err: error,\n error,\n fatal: true,\n });\n }\n return null;\n }\n\n protected _handleTransmuxerFlush(chunkMeta: ChunkMetadata) {\n const context = this.getCurrentContext(chunkMeta);\n if (!context || this.state !== State.PARSING) {\n if (\n !this.fragCurrent &&\n this.state !== State.STOPPED &&\n this.state !== State.ERROR\n ) {\n this.state = State.IDLE;\n }\n return;\n }\n const { frag, part, level } = context;\n const now = self.performance.now();\n frag.stats.parsing.end = now;\n if (part) {\n part.stats.parsing.end = now;\n }\n this.updateLevelTiming(frag, part, level, chunkMeta.partial);\n }\n\n protected getCurrentContext(\n chunkMeta: ChunkMetadata,\n ): { frag: Fragment; part: Part | null; level: Level } | null {\n const { levels, fragCurrent } = this;\n const { level: levelIndex, sn, part: partIndex } = chunkMeta;\n if (!levels?.[levelIndex]) {\n this.warn(\n `Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`,\n );\n return null;\n }\n const level = levels[levelIndex];\n const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;\n const frag = part\n ? part.fragment\n : getFragmentWithSN(level, sn, fragCurrent);\n if (!frag) {\n return null;\n }\n if (fragCurrent && fragCurrent !== frag) {\n frag.stats = fragCurrent.stats;\n }\n return { frag, part, level };\n }\n\n protected bufferFragmentData(\n data: RemuxedTrack,\n frag: Fragment,\n part: Part | null,\n chunkMeta: ChunkMetadata,\n noBacktracking?: boolean,\n ) {\n if (!data || this.state !== State.PARSING) {\n return;\n }\n\n const { data1, data2 } = data;\n let buffer = data1;\n if (data1 && data2) {\n // Combine the moof + mdat so that we buffer with a single append\n buffer = appendUint8Array(data1, data2);\n }\n\n if (!buffer?.length) {\n return;\n }\n\n const segment: BufferAppendingData = {\n type: data.type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n data: buffer,\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n\n if (data.dropped && data.independent && !part) {\n if (noBacktracking) {\n return;\n }\n // Clear buffer so that we reload previous segments sequentially if required\n this.flushBufferGap(frag);\n }\n }\n\n protected flushBufferGap(frag: Fragment) {\n const media = this.media;\n if (!media) {\n return;\n }\n // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed\n if (!BufferHelper.isBuffered(media, media.currentTime)) {\n this.flushMainBuffer(0, frag.start);\n return;\n }\n // Remove back-buffer without interrupting playback to allow back tracking\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const fragDuration = frag.duration;\n const segmentFraction = Math.min(\n this.config.maxFragLookUpTolerance * 2,\n fragDuration * 0.25,\n );\n const start = Math.max(\n Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction),\n currentTime + segmentFraction,\n );\n if (frag.start - start > segmentFraction) {\n this.flushMainBuffer(start, frag.start);\n }\n }\n\n protected getFwdBufferInfo(\n bufferable: Bufferable | null,\n type: PlaylistLevelType,\n ): BufferInfo | null {\n const pos = this.getLoadPosition();\n if (!Number.isFinite(pos)) {\n return null;\n }\n return this.getFwdBufferInfoAtPos(bufferable, pos, type);\n }\n\n protected getFwdBufferInfoAtPos(\n bufferable: Bufferable | null,\n pos: number,\n type: PlaylistLevelType,\n ): BufferInfo | null {\n const {\n config: { maxBufferHole },\n } = this;\n const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);\n // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos\n if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {\n const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);\n if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {\n return BufferHelper.bufferInfo(\n bufferable,\n pos,\n Math.max(bufferInfo.nextStart, maxBufferHole),\n );\n }\n }\n return bufferInfo;\n }\n\n protected getMaxBufferLength(levelBitrate?: number): number {\n const { config } = this;\n let maxBufLen;\n if (levelBitrate) {\n maxBufLen = Math.max(\n (8 * config.maxBufferSize) / levelBitrate,\n config.maxBufferLength,\n );\n } else {\n maxBufLen = config.maxBufferLength;\n }\n return Math.min(maxBufLen, config.maxMaxBufferLength);\n }\n\n protected reduceMaxBufferLength(threshold: number, fragDuration: number) {\n const config = this.config;\n const minLength = Math.max(\n Math.min(threshold - fragDuration, config.maxBufferLength),\n fragDuration,\n );\n const reducedLength = Math.max(\n threshold - fragDuration * 3,\n config.maxMaxBufferLength / 2,\n minLength,\n );\n if (reducedLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength = reducedLength;\n this.warn(`Reduce max buffer length to ${reducedLength}s`);\n return true;\n }\n return false;\n }\n\n protected getAppendedFrag(\n position: number,\n playlistType: PlaylistLevelType = PlaylistLevelType.MAIN,\n ): Fragment | null {\n const fragOrPart = this.fragmentTracker.getAppendedFrag(\n position,\n PlaylistLevelType.MAIN,\n );\n if (fragOrPart && 'fragment' in fragOrPart) {\n return fragOrPart.fragment;\n }\n return fragOrPart;\n }\n\n protected getNextFragment(\n pos: number,\n levelDetails: LevelDetails,\n ): Fragment | null {\n const fragments = levelDetails.fragments;\n const fragLen = fragments.length;\n\n if (!fragLen) {\n return null;\n }\n\n // find fragment index, contiguous with end of buffer position\n const { config } = this;\n const start = fragments[0].start;\n let frag;\n\n if (levelDetails.live) {\n const initialLiveManifestSize = config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n this.warn(\n `Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`,\n );\n return null;\n }\n // The real fragment start times for a live stream are only known after the PTS range for that level is known.\n // In order to discover the range, we load the best matching fragment for that level and demux it.\n // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that\n // we get the fragment matching that start time\n if (\n (!levelDetails.PTSKnown &&\n !this.startFragRequested &&\n this.startPosition === -1) ||\n pos < start\n ) {\n frag = this.getInitialLiveFragment(levelDetails, fragments);\n this.startPosition = this.nextLoadPosition = frag\n ? this.hls.liveSyncPosition || frag.start\n : pos;\n }\n } else if (pos <= start) {\n // VoD playlist: if loadPosition before start of playlist, load first fragment\n frag = fragments[0];\n }\n\n // If we haven't run into any special cases already, just load the fragment most closely matching the requested position\n if (!frag) {\n const end = config.lowLatencyMode\n ? levelDetails.partEnd\n : levelDetails.fragmentEnd;\n frag = this.getFragmentAtPosition(pos, end, levelDetails);\n }\n\n return this.mapToInitFragWhenRequired(frag);\n }\n\n protected isLoopLoading(frag: Fragment, targetBufferTime: number): boolean {\n const trackerState = this.fragmentTracker.getState(frag);\n return (\n (trackerState === FragmentState.OK ||\n (trackerState === FragmentState.PARTIAL && !!frag.gap)) &&\n this.nextLoadPosition > targetBufferTime\n );\n }\n\n protected getNextFragmentLoopLoading(\n frag: Fragment,\n levelDetails: LevelDetails,\n bufferInfo: BufferInfo,\n playlistType: PlaylistLevelType,\n maxBufLen: number,\n ): Fragment | null {\n const gapStart = frag.gap;\n const nextFragment = this.getNextFragment(\n this.nextLoadPosition,\n levelDetails,\n );\n if (nextFragment === null) {\n return nextFragment;\n }\n frag = nextFragment;\n if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {\n // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length\n const nextbufferInfo = this.getFwdBufferInfoAtPos(\n this.mediaBuffer ? this.mediaBuffer : this.media,\n bufferInfo.nextStart,\n playlistType,\n );\n if (\n nextbufferInfo !== null &&\n bufferInfo.len + nextbufferInfo.len >= maxBufLen\n ) {\n // Returning here might result in not finding an audio and video candiate to skip to\n this.log(\n `buffer full after gaps in \"${playlistType}\" playlist starting at sn: ${frag.sn}`,\n );\n return null;\n }\n }\n return frag;\n }\n\n mapToInitFragWhenRequired(frag: Fragment | null): typeof frag {\n // If an initSegment is present, it must be buffered first\n if (frag?.initSegment && !frag?.initSegment.data && !this.bitrateTest) {\n return frag.initSegment;\n }\n\n return frag;\n }\n\n getNextPart(\n partList: Part[],\n frag: Fragment,\n targetBufferTime: number,\n ): number {\n let nextPart = -1;\n let contiguous = false;\n let independentAttrOmitted = true;\n for (let i = 0, len = partList.length; i < len; i++) {\n const part = partList[i];\n independentAttrOmitted = independentAttrOmitted && !part.independent;\n if (nextPart > -1 && targetBufferTime < part.start) {\n break;\n }\n const loaded = part.loaded;\n if (loaded) {\n nextPart = -1;\n } else if (\n (contiguous || part.independent || independentAttrOmitted) &&\n part.fragment === frag\n ) {\n nextPart = i;\n }\n contiguous = loaded;\n }\n return nextPart;\n }\n\n private loadedEndOfParts(\n partList: Part[],\n targetBufferTime: number,\n ): boolean {\n const lastPart = partList[partList.length - 1];\n return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;\n }\n\n /*\n This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the\n \"sliding\" of the playlist, which is its offset from the start of playback. After sliding we can compute the real\n start and end times for each fragment in the playlist (after which this method will not need to be called).\n */\n protected getInitialLiveFragment(\n levelDetails: LevelDetails,\n fragments: Array<Fragment>,\n ): Fragment | null {\n const fragPrevious = this.fragPrevious;\n let frag: Fragment | null = null;\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding\n this.log(\n `Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`,\n );\n frag = findFragmentByPDT(\n fragments,\n fragPrevious.endProgramDateTime,\n this.config.maxFragLookUpTolerance,\n );\n }\n if (!frag) {\n // SN does not need to be accurate between renditions, but depending on the packaging it may be so.\n const targetSN = (fragPrevious.sn as number) + 1;\n if (\n targetSN >= levelDetails.startSN &&\n targetSN <= levelDetails.endSN\n ) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n // Ensure that we're staying within the continuity range, since PTS resets upon a new range\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n this.log(\n `Live playlist, switching playlist, load frag with next SN: ${\n frag!.sn\n }`,\n );\n }\n }\n // It's important to stay within the continuity range if available; otherwise the fragments in the playlist\n // will have the wrong start times\n if (!frag) {\n frag = findFragWithCC(fragments, fragPrevious.cc);\n if (frag) {\n this.log(\n `Live playlist, switching playlist, load frag with same CC: ${frag.sn}`,\n );\n }\n }\n }\n } else {\n // Find a new start fragment when fragPrevious is null\n const liveStart = this.hls.liveSyncPosition;\n if (liveStart !== null) {\n frag = this.getFragmentAtPosition(\n liveStart,\n this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge,\n levelDetails,\n );\n }\n }\n\n return frag;\n }\n\n /*\n This method finds the best matching fragment given the provided position.\n */\n protected getFragmentAtPosition(\n bufferEnd: number,\n end: number,\n levelDetails: LevelDetails,\n ): Fragment | null {\n const { config } = this;\n let { fragPrevious } = this;\n let { fragments, endSN } = levelDetails;\n const { fragmentHint } = levelDetails;\n const { maxFragLookUpTolerance } = config;\n const partList = levelDetails.partList;\n\n const loadingParts = !!(\n config.lowLatencyMode &&\n partList?.length &&\n fragmentHint\n );\n if (loadingParts && fragmentHint && !this.bitrateTest) {\n // Include incomplete fragment with parts at end\n fragments = fragments.concat(fragmentHint);\n endSN = fragmentHint.sn as number;\n }\n\n let frag;\n if (bufferEnd < end) {\n const lookupTolerance =\n bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPTS(\n fragPrevious,\n fragments,\n bufferEnd,\n lookupTolerance,\n );\n } else {\n // reach end of playlist\n frag = fragments[fragments.length - 1];\n }\n\n if (frag) {\n const curSNIdx = frag.sn - levelDetails.startSN;\n // Move fragPrevious forward to support forcing the next fragment to load\n // when the buffer catches up to a previously buffered range.\n const fragState = this.fragmentTracker.getState(frag);\n if (\n fragState === FragmentState.OK ||\n (fragState === FragmentState.PARTIAL && frag.gap)\n ) {\n fragPrevious = frag;\n }\n if (\n fragPrevious &&\n frag.sn === fragPrevious.sn &&\n (!loadingParts || partList[0].fragment.sn > frag.sn)\n ) {\n // Force the next fragment to load if the previous one was already selected. This can occasionally happen with\n // non-uniform fragment durations\n const sameLevel = fragPrevious && frag.level === fragPrevious.level;\n if (sameLevel) {\n const nextFrag = fragments[curSNIdx + 1];\n if (\n frag.sn < endSN &&\n this.fragmentTracker.getState(nextFrag) !== FragmentState.OK\n ) {\n frag = nextFrag;\n } else {\n frag = null;\n }\n }\n }\n }\n return frag;\n }\n\n protected synchronizeToLiveEdge(levelDetails: LevelDetails) {\n const { config, media } = this;\n if (!media) {\n return;\n }\n const liveSyncPosition = this.hls.liveSyncPosition;\n const currentTime = media.currentTime;\n const start = levelDetails.fragments[0].start;\n const end = levelDetails.edge;\n const withinSlidingWindow =\n currentTime >= start - config.maxFragLookUpTolerance &&\n currentTime <= end;\n // Continue if we can seek forward to sync position or if current time is outside of sliding window\n if (\n liveSyncPosition !== null &&\n media.duration > liveSyncPosition &&\n (currentTime < liveSyncPosition || !withinSlidingWindow)\n ) {\n // Continue if buffer is starving or if current time is behind max latency\n const maxLatency =\n config.liveMaxLatencyDuration !== undefined\n ? config.liveMaxLatencyDuration\n : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n if (\n (!withinSlidingWindow && media.readyState < 4) ||\n currentTime < end - maxLatency\n ) {\n if (!this.loadedmetadata) {\n this.nextLoadPosition = liveSyncPosition;\n }\n // Only seek if ready and there is not a significant forward buffer available for playback\n if (media.readyState) {\n this.warn(\n `Playback: ${currentTime.toFixed(\n 3,\n )} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(\n 3,\n )}`,\n );\n media.currentTime = liveSyncPosition;\n }\n }\n }\n }\n\n protected alignPlaylists(\n details: LevelDetails,\n previousDetails: LevelDetails | undefined,\n switchDetails: LevelDetails | undefined,\n ): number {\n // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,\n // this could all go in level-helper mergeDetails()\n const length = details.fragments.length;\n if (!length) {\n this.warn(`No fragments in live playlist`);\n return 0;\n }\n const slidingStart = details.fragments[0].start;\n const firstLevelLoad = !previousDetails;\n const aligned = details.alignedSliding && Number.isFinite(slidingStart);\n if (firstLevelLoad || (!aligned && !slidingStart)) {\n const { fragPrevious } = this;\n alignStream(fragPrevious, switchDetails, details);\n const alignedSlidingStart = details.fragments[0].start;\n this.log(\n `Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${\n previousDetails ? previousDetails.startSN : 'na'\n }->${details.startSN} prev-sn: ${\n fragPrevious ? fragPrevious.sn : 'na'\n } fragments: ${length}`,\n );\n return alignedSlidingStart;\n }\n return slidingStart;\n }\n\n protected waitForCdnTuneIn(details: LevelDetails) {\n // Wait for Low-Latency CDN Tune-in to get an updated playlist\n const advancePartLimit = 3;\n return (\n details.live &&\n details.canBlockReload &&\n details.partTarget &&\n details.tuneInGoal >\n Math.max(details.partHoldBack, details.partTarget * advancePartLimit)\n );\n }\n\n protected setStartPosition(details: LevelDetails, sliding: number) {\n // compute start position if set to -1. use it straight away if value is defined\n let startPosition = this.startPosition;\n if (startPosition < sliding) {\n startPosition = -1;\n }\n if (startPosition === -1 || this.lastCurrentTime === -1) {\n // Use Playlist EXT-X-START:TIME-OFFSET when set\n // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match\n const offsetInMultivariantPlaylist = this.startTimeOffset !== null;\n const startTimeOffset = offsetInMultivariantPlaylist\n ? this.startTimeOffset\n : details.startTimeOffset;\n if (startTimeOffset !== null && Number.isFinite(startTimeOffset)) {\n startPosition = sliding + startTimeOffset;\n if (startTimeOffset < 0) {\n startPosition += details.totalduration;\n }\n startPosition = Math.min(\n Math.max(sliding, startPosition),\n sliding + details.totalduration,\n );\n this.log(\n `Start time offset ${startTimeOffset} found in ${\n offsetInMultivariantPlaylist ? 'multivariant' : 'media'\n } playlist, adjust startPosition to ${startPosition}`,\n );\n this.startPosition = startPosition;\n } else if (details.live) {\n // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has\n // not been specified via the config or an as an argument to startLoad (#3736).\n startPosition = this.hls.liveSyncPosition || sliding;\n } else {\n this.startPosition = startPosition = 0;\n }\n this.lastCurrentTime = startPosition;\n }\n this.nextLoadPosition = startPosition;\n }\n\n protected getLoadPosition(): number {\n const { media } = this;\n // if we have not yet loaded any fragment, start loading from start position\n let pos = 0;\n if (this.loadedmetadata && media) {\n pos = media.currentTime;\n } else if (this.nextLoadPosition) {\n pos = this.nextLoadPosition;\n }\n\n return pos;\n }\n\n private handleFragLoadAborted(frag: Fragment, part: Part | undefined) {\n if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {\n this.warn(\n `Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${\n frag.level\n } was aborted`,\n );\n this.resetFragmentLoading(frag);\n }\n }\n\n protected resetFragmentLoading(frag: Fragment) {\n if (\n !this.fragCurrent ||\n (!this.fragContextChanged(frag) &&\n this.state !== State.FRAG_LOADING_WAITING_RETRY)\n ) {\n this.state = State.IDLE;\n }\n }\n\n protected onFragmentOrKeyLoadError(\n filterType: PlaylistLevelType,\n data: ErrorData,\n ) {\n if (data.chunkMeta && !data.frag) {\n const context = this.getCurrentContext(data.chunkMeta);\n if (context) {\n data.frag = context.frag;\n }\n }\n const frag = data.frag;\n // Handle frag error related to caller's filterType\n if (!frag || frag.type !== filterType || !this.levels) {\n return;\n }\n if (this.fragContextChanged(frag)) {\n this.warn(\n `Frag load error must match current frag to retry ${frag.url} > ${this.fragCurrent?.url}`,\n );\n return;\n }\n const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;\n if (gapTagEncountered) {\n this.fragmentTracker.fragBuffered(frag, true);\n }\n // keep retrying until the limit will be reached\n const errorAction = data.errorAction;\n const { action, retryCount = 0, retryConfig } = errorAction || {};\n if (\n errorAction &&\n action === NetworkErrorAction.RetryRequest &&\n retryConfig\n ) {\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n const delay = getRetryDelay(retryConfig, retryCount);\n this.warn(\n `Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${\n data.details\n }, retrying loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } in ${delay}ms`,\n );\n errorAction.resolved = true;\n this.retryDate = self.performance.now() + delay;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else if (retryConfig && errorAction) {\n this.resetFragmentErrors(filterType);\n if (retryCount < retryConfig.maxNumRetry) {\n // Network retry is skipped when level switch is preferred\n if (\n !gapTagEncountered &&\n action !== NetworkErrorAction.RemoveAlternatePermanently\n ) {\n errorAction.resolved = true;\n }\n } else {\n logger.warn(\n `${data.details} reached or exceeded max retry (${retryCount})`,\n );\n return;\n }\n } else if (\n errorAction?.action === NetworkErrorAction.SendAlternateToPenaltyBox\n ) {\n this.state = State.WAITING_LEVEL;\n } else {\n this.state = State.ERROR;\n }\n // Perform next async tick sooner to speed up error action resolution\n this.tickImmediate();\n }\n\n protected reduceLengthAndFlushBuffer(data: ErrorData): boolean {\n // if in appending state\n if (this.state === State.PARSING || this.state === State.PARSED) {\n const frag = data.frag;\n const playlistType = data.parent as PlaylistLevelType;\n const bufferedInfo = this.getFwdBufferInfo(\n this.mediaBuffer,\n playlistType,\n );\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n // reduce max buf len if current position is buffered\n const buffered = bufferedInfo && bufferedInfo.len > 0.5;\n if (buffered) {\n this.reduceMaxBufferLength(bufferedInfo.len, frag?.duration || 10);\n }\n const flushBuffer = !buffered;\n if (flushBuffer) {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n this.warn(\n `Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`,\n );\n }\n if (frag) {\n this.fragmentTracker.removeFragment(frag);\n this.nextLoadPosition = frag.start;\n }\n this.resetLoadingState();\n return flushBuffer;\n }\n return false;\n }\n\n protected resetFragmentErrors(filterType: PlaylistLevelType) {\n if (filterType === PlaylistLevelType.AUDIO) {\n // Reset current fragment since audio track audio is essential and may not have a fail-over track\n this.fragCurrent = null;\n }\n // Fragment errors that result in a level switch or redundant fail-over\n // should reset the stream controller state to idle\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n }\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n\n protected afterBufferFlushed(\n media: Bufferable,\n bufferType: SourceBufferName,\n playlistType: PlaylistLevelType,\n ) {\n if (!media) {\n return;\n }\n // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media\n // (so that we will check against video.buffered ranges in case of alt audio track)\n const bufferedTimeRanges = BufferHelper.getBuffered(media);\n this.fragmentTracker.detectEvictedFragments(\n bufferType,\n bufferedTimeRanges,\n playlistType,\n );\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n }\n }\n\n protected resetLoadingState() {\n this.log('Reset loading state');\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.state = State.IDLE;\n }\n\n protected resetStartWhenNotLoaded(level: Level | null): void {\n // if loadedmetadata is not set, it means that first frag request failed\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n const details = level ? level.details : null;\n if (details?.live) {\n // Update the start position and return to IDLE to recover live start\n this.startPosition = -1;\n this.setStartPosition(details, 0);\n this.resetLoadingState();\n } else {\n this.nextLoadPosition = this.startPosition;\n }\n }\n }\n\n protected resetWhenMissingContext(chunkMeta: ChunkMetadata) {\n this.warn(\n `The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`,\n );\n this.removeUnbufferedFrags();\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n this.resetLoadingState();\n }\n\n protected removeUnbufferedFrags(start: number = 0) {\n this.fragmentTracker.removeFragmentsInRange(\n start,\n Infinity,\n this.playlistType,\n false,\n true,\n );\n }\n\n private updateLevelTiming(\n frag: Fragment,\n part: Part | null,\n level: Level,\n partial: boolean,\n ) {\n const details = level.details as LevelDetails;\n if (!details) {\n this.warn('level.details undefined');\n return;\n }\n const parsed = Object.keys(frag.elementaryStreams).reduce(\n (result, type) => {\n const info = frag.elementaryStreams[type];\n if (info) {\n const parsedDuration = info.endPTS - info.startPTS;\n if (parsedDuration <= 0) {\n // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.\n // The new transmuxer will be configured with a time offset matching the next fragment start,\n // preventing the timeline from shifting.\n this.warn(\n `Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`,\n );\n return result || false;\n }\n const drift = partial\n ? 0\n : updateFragPTSDTS(\n details,\n frag,\n info.startPTS,\n info.endPTS,\n info.startDTS,\n info.endDTS,\n );\n this.hls.trigger(Events.LEVEL_PTS_UPDATED, {\n details,\n level,\n drift,\n type,\n frag,\n start: info.startPTS,\n end: info.endPTS,\n });\n return true;\n }\n return result;\n },\n false,\n );\n if (!parsed && this.transmuxer?.error === null) {\n const error = new Error(\n `Found no media in fragment ${frag.sn} of level ${frag.level} resetting transmuxer to fallback to playlist timing`,\n );\n if (level.fragmentError === 0) {\n // Mark and track the odd empty segment as a gap to avoid reloading\n level.fragmentError++;\n frag.gap = true;\n this.fragmentTracker.removeFragment(frag);\n this.fragmentTracker.fragBuffered(frag, true);\n }\n this.warn(error.message);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n frag,\n reason: `Found no media in msn ${frag.sn} of level \"${level.url}\"`,\n });\n if (!this.hls) {\n return;\n }\n this.resetTransmuxer();\n // For this error fallthrough. Marking parsed will allow advancing to next fragment.\n }\n this.state = State.PARSED;\n this.hls.trigger(Events.FRAG_PARSED, { frag, part });\n }\n\n protected resetTransmuxer() {\n if (this.transmuxer) {\n this.transmuxer.destroy();\n this.transmuxer = null;\n }\n }\n\n protected recoverWorkerError(data: ErrorData) {\n if (data.event === 'demuxerWorker') {\n this.fragmentTracker.removeAllFragments();\n this.resetTransmuxer();\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n this.resetLoadingState();\n }\n }\n\n set state(nextState) {\n const previousState = this._state;\n if (previousState !== nextState) {\n this._state = nextState;\n this.log(`${previousState}->${nextState}`);\n }\n }\n\n get state() {\n return this._state;\n }\n}\n","import { getMediaSource } from './utils/mediasource-helper';\nimport { mimeTypeForCodec } from './utils/codecs';\nimport type { ExtendedSourceBuffer } from './types/buffer';\n\nfunction getSourceBuffer(): typeof self.SourceBuffer {\n return self.SourceBuffer || (self as any).WebKitSourceBuffer;\n}\n\nexport function isMSESupported(): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n\n // if SourceBuffer is exposed ensure its API is valid\n // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBuffer = getSourceBuffer();\n return (\n !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function')\n );\n}\n\nexport function isSupported(): boolean {\n if (!isMSESupported()) {\n return false;\n }\n\n const mediaSource = getMediaSource();\n return (\n typeof mediaSource?.isTypeSupported === 'function' &&\n (['avc1.42E01E,mp4a.40.2', 'av01.0.01M.08', 'vp09.00.50.08'].some(\n (codecsForVideoContainer) =>\n mediaSource.isTypeSupported(\n mimeTypeForCodec(codecsForVideoContainer, 'video'),\n ),\n ) ||\n ['mp4a.40.2', 'fLaC'].some((codecForAudioContainer) =>\n mediaSource.isTypeSupported(\n mimeTypeForCodec(codecForAudioContainer, 'audio'),\n ),\n ))\n );\n}\n\nexport function changeTypeSupported(): boolean {\n const sourceBuffer = getSourceBuffer();\n return (\n typeof (sourceBuffer?.prototype as ExtendedSourceBuffer)?.changeType ===\n 'function'\n );\n}\n","import type { DemuxedTrack } from '../types/demuxer';\n\nexport function dummyTrack(type = '', inputTimeScale = 90000): DemuxedTrack {\n return {\n type,\n id: -1,\n pid: -1,\n inputTimeScale,\n sequenceNumber: -1,\n samples: [],\n dropped: 0,\n };\n}\n","import * as ID3 from '../id3';\nimport {\n DemuxerResult,\n Demuxer,\n DemuxedAudioTrack,\n AudioFrame,\n DemuxedMetadataTrack,\n DemuxedVideoTrackBase,\n DemuxedUserdataTrack,\n KeyData,\n MetadataSchema,\n} from '../../types/demuxer';\nimport { dummyTrack } from '../dummy-demuxed-track';\nimport { appendUint8Array } from '../../utils/mp4-tools';\nimport { sliceUint8 } from '../../utils/typed-array';\nimport { RationalTimestamp } from '../../utils/timescale-conversion';\n\nclass BaseAudioDemuxer implements Demuxer {\n protected _audioTrack!: DemuxedAudioTrack;\n protected _id3Track!: DemuxedMetadataTrack;\n protected frameIndex: number = 0;\n protected cachedData: Uint8Array | null = null;\n protected basePTS: number | null = null;\n protected initPTS: RationalTimestamp | null = null;\n protected lastPTS: number | null = null;\n\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n this._id3Track = {\n type: 'id3',\n id: 3,\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n };\n }\n\n resetTimeStamp(deaultTimestamp: RationalTimestamp | null) {\n this.initPTS = deaultTimestamp;\n this.resetContiguity();\n }\n\n resetContiguity(): void {\n this.basePTS = null;\n this.lastPTS = null;\n this.frameIndex = 0;\n }\n\n canParse(data: Uint8Array, offset: number): boolean {\n return false;\n }\n\n appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n ): AudioFrame | void {}\n\n // feed incoming data to the front of the parsing pipeline\n demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n if (this.cachedData) {\n data = appendUint8Array(this.cachedData, data);\n this.cachedData = null;\n }\n\n let id3Data: Uint8Array | undefined = ID3.getID3Data(data, 0);\n let offset = id3Data ? id3Data.length : 0;\n let lastDataIndex;\n const track = this._audioTrack;\n const id3Track = this._id3Track;\n const timestamp = id3Data ? ID3.getTimeStamp(id3Data) : undefined;\n const length = data.length;\n\n if (\n this.basePTS === null ||\n (this.frameIndex === 0 && Number.isFinite(timestamp))\n ) {\n this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);\n this.lastPTS = this.basePTS;\n }\n\n if (this.lastPTS === null) {\n this.lastPTS = this.basePTS;\n }\n\n // more expressive than alternative: id3Data?.length\n if (id3Data && id3Data.length > 0) {\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n }\n\n while (offset < length) {\n if (this.canParse(data, offset)) {\n const frame = this.appendFrame(track, data, offset);\n if (frame) {\n this.frameIndex++;\n this.lastPTS = frame.sample.pts;\n offset += frame.length;\n lastDataIndex = offset;\n } else {\n offset = length;\n }\n } else if (ID3.canParse(data, offset)) {\n // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data\n id3Data = ID3.getID3Data(data, offset)!;\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n offset += id3Data.length;\n lastDataIndex = offset;\n } else {\n offset++;\n }\n if (offset === length && lastDataIndex !== length) {\n const partialData = sliceUint8(data, lastDataIndex);\n if (this.cachedData) {\n this.cachedData = appendUint8Array(this.cachedData, partialData);\n } else {\n this.cachedData = partialData;\n }\n }\n }\n\n return {\n audioTrack: track,\n videoTrack: dummyTrack() as DemuxedVideoTrackBase,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error(\n `[${this}] This demuxer does not support Sample-AES decryption`,\n ),\n );\n }\n\n flush(timeOffset: number): DemuxerResult {\n // Parse cache in case of remaining frames.\n const cachedData = this.cachedData;\n if (cachedData) {\n this.cachedData = null;\n this.demux(cachedData, 0);\n }\n\n return {\n audioTrack: this._audioTrack,\n videoTrack: dummyTrack() as DemuxedVideoTrackBase,\n id3Track: this._id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n destroy() {}\n}\n\n/**\n * Initialize PTS\n * <p>\n * use timestamp unless it is undefined, NaN or Infinity\n * </p>\n */\nexport const initPTSFn = (\n timestamp: number | undefined,\n timeOffset: number,\n initPTS: RationalTimestamp | null,\n): number => {\n if (Number.isFinite(timestamp as number)) {\n return timestamp! * 90;\n }\n const init90kHz = initPTS\n ? (initPTS.baseTime * 90000) / initPTS.timescale\n : 0;\n return timeOffset * 90000 + init90kHz;\n};\nexport default BaseAudioDemuxer;\n","/**\n * ADTS parser helper\n * @link https://wiki.multimedia.cx/index.php?title=ADTS\n */\nimport { logger } from '../../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../../errors';\nimport type { HlsEventEmitter } from '../../events';\nimport { Events } from '../../events';\nimport type {\n DemuxedAudioTrack,\n AudioFrame,\n AudioSample,\n} from '../../types/demuxer';\n\ntype AudioConfig = {\n config: number[];\n samplerate: number;\n channelCount: number;\n codec: string;\n manifestCodec: string;\n};\n\ntype FrameHeader = {\n headerLength: number;\n frameLength: number;\n};\n\nexport function getAudioConfig(\n observer: HlsEventEmitter,\n data: Uint8Array,\n offset: number,\n audioCodec: string,\n): AudioConfig | void {\n let adtsObjectType: number;\n let adtsExtensionSamplingIndex: number;\n let adtsChannelConfig: number;\n let config: number[];\n const userAgent = navigator.userAgent.toLowerCase();\n const manifestCodec = audioCodec;\n const adtsSamplingRates = [\n 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025,\n 8000, 7350,\n ];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;\n const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;\n if (adtsSamplingIndex > adtsSamplingRates.length - 1) {\n const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);\n observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: true,\n error,\n reason: error.message,\n });\n return;\n }\n adtsChannelConfig = (data[offset + 2] & 0x01) << 2;\n // byte 3\n adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;\n logger.log(\n `manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`,\n );\n // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/i.test(userAgent)) {\n if (adtsSamplingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi/Opera ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if (\n (audioCodec &&\n (audioCodec.indexOf('mp4a.40.29') !== -1 ||\n audioCodec.indexOf('mp4a.40.5') !== -1)) ||\n (!audioCodec && adtsSamplingIndex >= 6)\n ) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (\n (audioCodec &&\n audioCodec.indexOf('mp4a.40.2') !== -1 &&\n ((adtsSamplingIndex >= 6 && adtsChannelConfig === 1) ||\n /vivaldi/i.test(userAgent))) ||\n (!audioCodec && adtsChannelConfig === 1)\n ) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSamplingIndex & 0x0e) >> 1;\n config[1] |= (adtsSamplingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChannelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSamplingIndex\n config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;\n config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n return {\n config,\n samplerate: adtsSamplingRates[adtsSamplingIndex],\n channelCount: adtsChannelConfig,\n codec: 'mp4a.40.' + adtsObjectType,\n manifestCodec,\n };\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nexport function getHeaderLength(data: Uint8Array, offset: number): number {\n return data[offset + 1] & 0x01 ? 7 : 9;\n}\n\nexport function getFullFrameLength(data: Uint8Array, offset: number): number {\n return (\n ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xe0) >>> 5)\n );\n}\n\nexport function canGetFrameLength(data: Uint8Array, offset: number): boolean {\n return offset + 5 < data.length;\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n return (\n canGetFrameLength(data, offset) &&\n isHeaderPattern(data, offset) &&\n getFullFrameLength(data, offset) <= data.length - offset\n );\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (isHeader(data, offset)) {\n // ADTS header Length\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n const frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n\nexport function initTrackConfig(\n track: DemuxedAudioTrack,\n observer: HlsEventEmitter,\n data: Uint8Array,\n offset: number,\n audioCodec: string,\n) {\n if (!track.samplerate) {\n const config = getAudioConfig(observer, data, offset, audioCodec);\n if (!config) {\n return;\n }\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(\n `parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`,\n );\n }\n}\n\nexport function getFrameDuration(samplerate: number): number {\n return (1024 * 90000) / samplerate;\n}\n\nexport function parseFrameHeader(\n data: Uint8Array,\n offset: number,\n): FrameHeader | void {\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength <= data.length) {\n // retrieve frame size\n const frameLength = getFullFrameLength(data, offset) - headerLength;\n if (frameLength > 0) {\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);\n return { headerLength, frameLength };\n }\n }\n}\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number,\n): AudioFrame {\n const frameDuration = getFrameDuration(track.samplerate as number);\n const stamp = pts + frameIndex * frameDuration;\n const header = parseFrameHeader(data, offset);\n let unit: Uint8Array;\n if (header) {\n const { frameLength, headerLength } = header;\n const length = headerLength + frameLength;\n const missing = Math.max(0, offset + length - data.length);\n // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);\n if (missing) {\n unit = new Uint8Array(length - headerLength);\n unit.set(data.subarray(offset + headerLength, data.length), 0);\n } else {\n unit = data.subarray(offset + headerLength, offset + length);\n }\n\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n if (!missing) {\n track.samples.push(sample as AudioSample);\n }\n\n return { sample, length, missing };\n }\n // overflow incomplete header\n const length = data.length - offset;\n unit = new Uint8Array(length);\n unit.set(data.subarray(offset, data.length), 0);\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n return { sample, length, missing: -1 };\n}\n","/**\n * MPEG parser helper\n */\nimport { DemuxedAudioTrack } from '../../types/demuxer';\n\nlet chromeVersion: number | null = null;\n\nconst BitratesMap = [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56,\n 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80,\n 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144,\n 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144,\n 160,\n];\n\nconst SamplingRateMap = [\n 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000,\n];\n\nconst SamplesCoefficients = [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0, // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n];\n\nconst BytesInSlot = [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4, // Layer1\n];\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number,\n) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return;\n }\n\n const header = parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n const frameDuration = (header.samplesPerFrame * 90000) / header.sampleRate;\n const stamp = pts + frameIndex * frameDuration;\n const sample = {\n unit: data.subarray(offset, offset + header.frameLength),\n pts: stamp,\n dts: stamp,\n };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n\n return { sample, length: header.frameLength, missing: 0 };\n }\n}\n\nexport function parseHeader(data: Uint8Array, offset: number) {\n const mpegVersion = (data[offset + 1] >> 3) & 3;\n const mpegLayer = (data[offset + 1] >> 1) & 3;\n const bitRateIndex = (data[offset + 2] >> 4) & 15;\n const sampleRateIndex = (data[offset + 2] >> 2) & 3;\n if (\n mpegVersion !== 1 &&\n bitRateIndex !== 0 &&\n bitRateIndex !== 15 &&\n sampleRateIndex !== 3\n ) {\n const paddingBit = (data[offset + 2] >> 1) & 1;\n const channelMode = data[offset + 3] >> 6;\n const columnInBitrates =\n mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;\n const bitRate =\n BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;\n const columnInSampleRates =\n mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;\n const sampleRate =\n SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];\n const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];\n const bytesInSlot = BytesInSlot[mpegLayer];\n const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n const frameLength =\n Math.floor((sampleCoefficient * bitRate) / sampleRate + paddingBit) *\n bytesInSlot;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n const needChromeFix = !!chromeVersion && chromeVersion <= 87;\n\n if (\n needChromeFix &&\n mpegLayer === 2 &&\n bitRate >= 224000 &&\n channelMode === 0\n ) {\n // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)\n data[offset + 3] = data[offset + 3] | 0x80;\n }\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\n }\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return (\n data[offset] === 0xff &&\n (data[offset + 1] & 0xe0) === 0xe0 &&\n (data[offset + 1] & 0x06) !== 0x00\n );\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n const headerSize = 4;\n\n return isHeaderPattern(data, offset) && headerSize <= data.length - offset;\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n // MPEG header Length\n const headerLength = 4;\n // MPEG frame Length\n const header = parseHeader(data, offset);\n let frameLength = headerLength;\n if (header?.frameLength) {\n frameLength = header.frameLength;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n","/**\n * AAC demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ADTS from './adts';\nimport * as MpegAudio from './mpegaudio';\nimport { logger } from '../../utils/logger';\nimport * as ID3 from '../id3';\nimport type { HlsEventEmitter } from '../../events';\nimport type { HlsConfig } from '../../config';\n\nclass AACDemuxer extends BaseAudioDemuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n\n constructor(observer, config) {\n super();\n this.observer = observer;\n this.config = config;\n }\n\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/adts',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'aac',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS\n static probe(data: Uint8Array | undefined): boolean {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0);\n let offset = id3Data?.length || 0;\n\n if (MpegAudio.probe(data, offset)) {\n return false;\n }\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return ADTS.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n track.manifestCodec,\n );\n const frame = ADTS.appendFrame(\n track,\n data,\n offset,\n this.basePTS as number,\n this.frameIndex,\n );\n if (frame && frame.missing === 0) {\n return frame;\n }\n }\n}\n\nexport default AACDemuxer;\n","/**\n * MP4 demuxer\n */\nimport {\n Demuxer,\n DemuxerResult,\n PassthroughTrack,\n DemuxedAudioTrack,\n DemuxedUserdataTrack,\n DemuxedMetadataTrack,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport {\n findBox,\n segmentValidRange,\n appendUint8Array,\n parseEmsg,\n parseSamples,\n parseInitSegment,\n RemuxerTrackIdConfig,\n hasMoofData,\n} from '../utils/mp4-tools';\nimport { dummyTrack } from './dummy-demuxed-track';\nimport type { HlsEventEmitter } from '../events';\nimport type { HlsConfig } from '../config';\n\nconst emsgSchemePattern = /\\/emsg[-/]ID3/i;\n\nclass MP4Demuxer implements Demuxer {\n private remainderData: Uint8Array | null = null;\n private timeOffset: number = 0;\n private config: HlsConfig;\n private videoTrack?: PassthroughTrack;\n private audioTrack?: DemuxedAudioTrack;\n private id3Track?: DemuxedMetadataTrack;\n private txtTrack?: DemuxedUserdataTrack;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig) {\n this.config = config;\n }\n\n public resetTimeStamp() {}\n\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n const videoTrack = (this.videoTrack = dummyTrack(\n 'video',\n 1,\n ) as PassthroughTrack);\n const audioTrack = (this.audioTrack = dummyTrack(\n 'audio',\n 1,\n ) as DemuxedAudioTrack);\n const captionTrack = (this.txtTrack = dummyTrack(\n 'text',\n 1,\n ) as DemuxedUserdataTrack);\n\n this.id3Track = dummyTrack('id3', 1) as DemuxedMetadataTrack;\n this.timeOffset = 0;\n\n if (!initSegment?.byteLength) {\n return;\n }\n const initData = parseInitSegment(initSegment);\n\n if (initData.video) {\n const { id, timescale, codec } = initData.video;\n videoTrack.id = id;\n videoTrack.timescale = captionTrack.timescale = timescale;\n videoTrack.codec = codec;\n }\n\n if (initData.audio) {\n const { id, timescale, codec } = initData.audio;\n audioTrack.id = id;\n audioTrack.timescale = timescale;\n audioTrack.codec = codec;\n }\n\n captionTrack.id = RemuxerTrackIdConfig.text;\n videoTrack.sampleDuration = 0;\n videoTrack.duration = audioTrack.duration = trackDuration;\n }\n\n public resetContiguity(): void {\n this.remainderData = null;\n }\n\n static probe(data: Uint8Array) {\n return hasMoofData(data);\n }\n\n public demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n this.timeOffset = timeOffset;\n // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter\n let videoSamples = data;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n if (this.config.progressive) {\n // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.\n // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee\n // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.\n if (this.remainderData) {\n videoSamples = appendUint8Array(this.remainderData, data);\n }\n const segmentedData = segmentValidRange(videoSamples);\n this.remainderData = segmentedData.remainder;\n videoTrack.samples = segmentedData.valid || new Uint8Array();\n } else {\n videoTrack.samples = videoSamples;\n }\n\n const id3Track = this.extractID3Track(videoTrack, timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: this.audioTrack as DemuxedAudioTrack,\n id3Track,\n textTrack: this.txtTrack as DemuxedUserdataTrack,\n };\n }\n\n public flush() {\n const timeOffset = this.timeOffset;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n videoTrack.samples = this.remainderData || new Uint8Array();\n this.remainderData = null;\n\n const id3Track = this.extractID3Track(videoTrack, this.timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: dummyTrack() as DemuxedAudioTrack,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n private extractID3Track(\n videoTrack: PassthroughTrack,\n timeOffset: number,\n ): DemuxedMetadataTrack {\n const id3Track = this.id3Track as DemuxedMetadataTrack;\n if (videoTrack.samples.length) {\n const emsgs = findBox(videoTrack.samples, ['emsg']);\n if (emsgs) {\n emsgs.forEach((data: Uint8Array) => {\n const emsgInfo = parseEmsg(data);\n if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {\n const pts = Number.isFinite(emsgInfo.presentationTime)\n ? emsgInfo.presentationTime! / emsgInfo.timeScale\n : timeOffset +\n emsgInfo.presentationTimeDelta! / emsgInfo.timeScale;\n let duration =\n emsgInfo.eventDuration === 0xffffffff\n ? Number.POSITIVE_INFINITY\n : emsgInfo.eventDuration / emsgInfo.timeScale;\n // Safari takes anything <= 0.001 seconds and maps it to Infinity\n if (duration <= 0.001) {\n duration = Number.POSITIVE_INFINITY;\n }\n const payload = emsgInfo.payload;\n id3Track.samples.push({\n data: payload,\n len: payload.byteLength,\n dts: pts,\n pts: pts,\n type: MetadataSchema.emsg,\n duration: duration,\n });\n }\n });\n }\n }\n return id3Track;\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error('The MP4 demuxer does not support SAMPLE-AES decryption'),\n );\n }\n\n destroy() {}\n}\n\nexport default MP4Demuxer;\n","import type { ParsedVideoSample } from '../tsdemuxer';\nimport {\n DemuxedVideoTrack,\n VideoSample,\n VideoSampleUnit,\n} from '../../types/demuxer';\nimport { logger } from '../../utils/logger';\n\nclass BaseVideoParser {\n protected VideoSample: ParsedVideoSample | null = null;\n\n protected createVideoSample(\n key: boolean,\n pts: number | undefined,\n dts: number | undefined,\n debug: string,\n ): ParsedVideoSample {\n return {\n key,\n frame: false,\n pts,\n dts,\n units: [],\n debug,\n length: 0,\n };\n }\n\n protected getLastNalUnit(\n samples: VideoSample[],\n ): VideoSampleUnit | undefined {\n let VideoSample = this.VideoSample;\n let lastUnit: VideoSampleUnit | undefined;\n // try to fallback to previous sample if current one is empty\n if (!VideoSample || VideoSample.units.length === 0) {\n VideoSample = samples[samples.length - 1];\n }\n if (VideoSample?.units) {\n const units = VideoSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n protected pushAccessUnit(\n VideoSample: ParsedVideoSample,\n videoTrack: DemuxedVideoTrack,\n ) {\n if (VideoSample.units.length && VideoSample.frame) {\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (VideoSample.pts === undefined) {\n const samples = videoTrack.samples;\n const nbSamples = samples.length;\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n VideoSample.pts = lastSample.pts;\n VideoSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n videoTrack.dropped++;\n return;\n }\n }\n videoTrack.samples.push(VideoSample as VideoSample);\n }\n if (VideoSample.debug.length) {\n logger.log(\n VideoSample.pts + '/' + VideoSample.dts + ':' + VideoSample.debug,\n );\n }\n }\n}\n\nexport default BaseVideoParser;\n","/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n */\n\nimport { logger } from '../../utils/logger';\n\nclass ExpGolomb {\n private data: Uint8Array;\n public bytesAvailable: number;\n private word: number;\n private bitsAvailable: number;\n\n constructor(data: Uint8Array) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord(): void {\n const data = this.data;\n const bytesAvailable = this.bytesAvailable;\n const position = data.byteLength - bytesAvailable;\n const workingBytes = new Uint8Array(4);\n const availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits(count: number): void {\n let skipBytes; // :int\n count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= skipBytes << 3;\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits(size: number): number {\n let bits = Math.min(this.bitsAvailable, size); // :uint\n const valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n } else {\n throw new Error('no bits available');\n }\n\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return (valu << bits) | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ(): number {\n let leadingZeroCount; // :uint\n for (\n leadingZeroCount = 0;\n leadingZeroCount < this.bitsAvailable;\n ++leadingZeroCount\n ) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG(): void {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG(): void {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG(): number {\n const clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG(): number {\n const valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean(): boolean {\n return this.readBits(1) === 1;\n }\n\n // ():int\n readUByte(): number {\n return this.readBits(8);\n }\n\n // ():int\n readUShort(): number {\n return this.readBits(16);\n }\n\n // ():int\n readUInt(): number {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList(count: number): void {\n let lastScale = 8;\n let nextScale = 8;\n let deltaScale;\n for (let j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = nextScale === 0 ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @returns an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS(): {\n width: number;\n height: number;\n pixelRatio: [number, number];\n } {\n let frameCropLeftOffset = 0;\n let frameCropRightOffset = 0;\n let frameCropTopOffset = 0;\n let frameCropBottomOffset = 0;\n let numRefFramesInPicOrderCntCycle;\n let scalingListCount;\n let i;\n const readUByte = this.readUByte.bind(this);\n const readBits = this.readBits.bind(this);\n const readUEG = this.readUEG.bind(this);\n const readBoolean = this.readBoolean.bind(this);\n const skipBits = this.skipBits.bind(this);\n const skipEG = this.skipEG.bind(this);\n const skipUEG = this.skipUEG.bind(this);\n const skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n const profileIdc = readUByte(); // profile_idc\n readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n readUByte(); // level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (\n profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128\n ) {\n const chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // separate_colour_plane_flag\n\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) {\n // seq_scaling_matrix_present_flag\n scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) {\n // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n const picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG();\n } // offset_for_ref_frame[ i ]\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n const picWidthInMbsMinus1 = readUEG();\n const picHeightInMapUnitsMinus1 = readUEG();\n const frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) {\n // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio: [number, number] = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1:\n pixelRatio = [1, 1];\n break;\n case 2:\n pixelRatio = [12, 11];\n break;\n case 3:\n pixelRatio = [10, 11];\n break;\n case 4:\n pixelRatio = [16, 11];\n break;\n case 5:\n pixelRatio = [40, 33];\n break;\n case 6:\n pixelRatio = [24, 11];\n break;\n case 7:\n pixelRatio = [20, 11];\n break;\n case 8:\n pixelRatio = [32, 11];\n break;\n case 9:\n pixelRatio = [80, 33];\n break;\n case 10:\n pixelRatio = [18, 11];\n break;\n case 11:\n pixelRatio = [15, 11];\n break;\n case 12:\n pixelRatio = [64, 33];\n break;\n case 13:\n pixelRatio = [160, 99];\n break;\n case 14:\n pixelRatio = [4, 3];\n break;\n case 15:\n pixelRatio = [3, 2];\n break;\n case 16:\n pixelRatio = [2, 1];\n break;\n case 255: {\n pixelRatio = [\n (readUByte() << 8) | readUByte(),\n (readUByte() << 8) | readUByte(),\n ];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil(\n (picWidthInMbsMinus1 + 1) * 16 -\n frameCropLeftOffset * 2 -\n frameCropRightOffset * 2,\n ),\n height:\n (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 -\n (frameMbsOnlyFlag ? 2 : 4) *\n (frameCropTopOffset + frameCropBottomOffset),\n pixelRatio: pixelRatio,\n };\n }\n\n readSliceType() {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n","import BaseVideoParser from './base-video-parser';\nimport {\n DemuxedVideoTrack,\n DemuxedUserdataTrack,\n VideoSampleUnit,\n} from '../../types/demuxer';\nimport {\n appendUint8Array,\n parseSEIMessageFromNALu,\n} from '../../utils/mp4-tools';\nimport ExpGolomb from './exp-golomb';\nimport type { PES } from '../tsdemuxer';\n\nclass AvcVideoParser extends BaseVideoParser {\n public parseAVCPES(\n track: DemuxedVideoTrack,\n textTrack: DemuxedUserdataTrack,\n pes: PES,\n last: boolean,\n duration: number,\n ) {\n const units = this.parseAVCNALu(track, pes.data);\n const debug = false;\n let VideoSample = this.VideoSample;\n let push: boolean;\n let spsfound = false;\n // free pes.data to save up some memory\n (pes as any).data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (VideoSample && units.length && !track.audFound) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = this.createVideoSample(\n false,\n pes.pts,\n pes.dts,\n '',\n );\n }\n\n units.forEach((unit) => {\n switch (unit.type) {\n // NDR\n case 1: {\n let iskey = false;\n push = true;\n const data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n const sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n // if (sliceType === 2 || sliceType === 7) {\n if (\n sliceType === 2 ||\n sliceType === 4 ||\n sliceType === 7 ||\n sliceType === 9\n ) {\n iskey = true;\n }\n }\n\n if (iskey) {\n // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push\n if (VideoSample?.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n }\n\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(\n true,\n pes.pts,\n pes.dts,\n '',\n );\n }\n\n if (debug) {\n VideoSample.debug += 'NDR ';\n }\n\n VideoSample.frame = true;\n VideoSample.key = iskey;\n\n break;\n // IDR\n }\n case 5:\n push = true;\n // handle PES not starting with AUD\n // if we have frame data already, that cannot belong to the same frame, so force a push\n if (VideoSample?.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(\n true,\n pes.pts,\n pes.dts,\n '',\n );\n }\n\n if (debug) {\n VideoSample.debug += 'IDR ';\n }\n\n VideoSample.key = true;\n VideoSample.frame = true;\n break;\n // SEI\n case 6: {\n push = true;\n if (debug && VideoSample) {\n VideoSample.debug += 'SEI ';\n }\n parseSEIMessageFromNALu(\n unit.data,\n 1,\n pes.pts as number,\n textTrack.samples,\n );\n break;\n // SPS\n }\n case 7: {\n push = true;\n spsfound = true;\n if (debug && VideoSample) {\n VideoSample.debug += 'SPS ';\n }\n const sps = unit.data;\n const expGolombDecoder = new ExpGolomb(sps);\n const config = expGolombDecoder.readSPS();\n\n if (\n !track.sps ||\n track.width !== config.width ||\n track.height !== config.height ||\n track.pixelRatio?.[0] !== config.pixelRatio[0] ||\n track.pixelRatio?.[1] !== config.pixelRatio[1]\n ) {\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [sps];\n track.duration = duration;\n const codecarray = sps.subarray(1, 4);\n let codecstring = 'avc1.';\n for (let i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n codecstring += h;\n }\n track.codec = codecstring;\n }\n\n break;\n }\n // PPS\n case 8:\n push = true;\n if (debug && VideoSample) {\n VideoSample.debug += 'PPS ';\n }\n\n track.pps = [unit.data];\n\n break;\n // AUD\n case 9:\n push = true;\n track.audFound = true;\n if (VideoSample) {\n this.pushAccessUnit(VideoSample, track);\n }\n\n VideoSample = this.VideoSample = this.createVideoSample(\n false,\n pes.pts,\n pes.dts,\n debug ? 'AUD ' : '',\n );\n break;\n // Filler Data\n case 12:\n push = true;\n break;\n default:\n push = false;\n if (VideoSample) {\n VideoSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (VideoSample && push) {\n const units = VideoSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && VideoSample) {\n this.pushAccessUnit(VideoSample, track);\n this.VideoSample = null;\n }\n }\n\n private parseAVCNALu(\n track: DemuxedVideoTrack,\n array: Uint8Array,\n ): Array<{\n data: Uint8Array;\n type: number;\n state?: number;\n }> {\n const len = array.byteLength;\n let state = track.naluState || 0;\n const lastState = state;\n const units: VideoSampleUnit[] = [];\n let i = 0;\n let value: number;\n let overflow: number;\n let unitType: number;\n let lastUnitStart = -1;\n let lastUnitType: number = 0;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n overflow = i - state - 1;\n if (lastUnitStart >= 0) {\n const unit: VideoSampleUnit = {\n data: array.subarray(lastUnitStart, overflow),\n type: lastUnitType,\n };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n if (lastState && i <= 4 - lastState) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(\n 0,\n lastUnit.data.byteLength - lastState,\n );\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n lastUnit.data = appendUint8Array(\n lastUnit.data,\n array.subarray(0, overflow),\n );\n lastUnit.state = 0;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n const unit: VideoSampleUnit = {\n data: array.subarray(lastUnitStart, len),\n type: lastUnitType,\n state: state,\n };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n lastUnit.data = appendUint8Array(lastUnit.data, array);\n }\n }\n track.naluState = state;\n return units;\n }\n}\n\nexport default AvcVideoParser;\n","/**\n * SAMPLE-AES decrypter\n */\n\nimport { HlsConfig } from '../config';\nimport Decrypter from '../crypt/decrypter';\nimport { HlsEventEmitter } from '../events';\nimport type {\n AudioSample,\n VideoSample,\n VideoSampleUnit,\n DemuxedVideoTrackBase,\n KeyData,\n} from '../types/demuxer';\nimport { discardEPB } from '../utils/mp4-tools';\n\nclass SampleAesDecrypter {\n private keyData: KeyData;\n private decrypter: Decrypter;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig, keyData: KeyData) {\n this.keyData = keyData;\n this.decrypter = new Decrypter(config, {\n removePKCS7Padding: false,\n });\n }\n\n decryptBuffer(encryptedData: Uint8Array | ArrayBuffer): Promise<ArrayBuffer> {\n return this.decrypter.decrypt(\n encryptedData,\n this.keyData.key.buffer,\n this.keyData.iv.buffer,\n );\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n private decryptAacSample(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void,\n ) {\n const curUnit = samples[sampleIndex].unit;\n if (curUnit.length <= 16) {\n // No encrypted portion in this sample (first 16 bytes is not\n // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),\n return;\n }\n const encryptedData = curUnit.subarray(\n 16,\n curUnit.length - (curUnit.length % 16),\n );\n const encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length,\n );\n\n this.decryptBuffer(encryptedBuffer).then((decryptedBuffer: ArrayBuffer) => {\n const decryptedData = new Uint8Array(decryptedBuffer);\n curUnit.set(decryptedData, 16);\n\n if (!this.decrypter.isSync()) {\n this.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void,\n ) {\n for (; ; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n this.decryptAacSample(samples, sampleIndex, callback);\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData(decodedData: Uint8Array) {\n const encryptedDataLen =\n Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n const encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (\n let inputPos = 32;\n inputPos < decodedData.length - 16;\n inputPos += 160, outputPos += 16\n ) {\n encryptedData.set(\n decodedData.subarray(inputPos, inputPos + 16),\n outputPos,\n );\n }\n\n return encryptedData;\n }\n\n getAvcDecryptedUnit(\n decodedData: Uint8Array,\n decryptedData: ArrayLike<number> | ArrayBuffer | SharedArrayBuffer,\n ) {\n const uint8DecryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (\n let outputPos = 32;\n outputPos < decodedData.length - 16;\n outputPos += 160, inputPos += 16\n ) {\n decodedData.set(\n uint8DecryptedData.subarray(inputPos, inputPos + 16),\n outputPos,\n );\n }\n\n return decodedData;\n }\n\n decryptAvcSample(\n samples: VideoSample[],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void,\n curUnit: VideoSampleUnit,\n ) {\n const decodedData = discardEPB(curUnit.data);\n const encryptedData = this.getAvcEncryptedData(decodedData);\n\n this.decryptBuffer(encryptedData.buffer).then(\n (decryptedBuffer: ArrayBuffer) => {\n curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);\n\n if (!this.decrypter.isSync()) {\n this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n },\n );\n }\n\n decryptAvcSamples(\n samples: DemuxedVideoTrackBase['samples'],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void,\n ) {\n if (samples instanceof Uint8Array) {\n throw new Error('Cannot decrypt samples of type Uint8Array');\n }\n\n for (; ; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n const curUnits = samples[sampleIndex].units;\n for (; ; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n const curUnit = curUnits[unitIndex];\n if (\n curUnit.data.length <= 48 ||\n (curUnit.type !== 1 && curUnit.type !== 5)\n ) {\n continue;\n }\n\n this.decryptAvcSample(\n samples,\n sampleIndex,\n unitIndex,\n callback,\n curUnit,\n );\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n }\n}\n\nexport default SampleAesDecrypter;\n","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n */\n\nimport * as ADTS from './audio/adts';\nimport * as MpegAudio from './audio/mpegaudio';\nimport * as AC3 from './audio/ac3-demuxer';\nimport AvcVideoParser from './video/avc-video-parser';\nimport SampleAesDecrypter from './sample-aes';\nimport { Events } from '../events';\nimport { appendUint8Array, RemuxerTrackIdConfig } from '../utils/mp4-tools';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport type { HlsConfig } from '../config';\nimport type { HlsEventEmitter } from '../events';\nimport {\n DemuxedVideoTrack,\n DemuxedAudioTrack,\n DemuxedTrack,\n Demuxer,\n DemuxerResult,\n VideoSample,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n ElementaryStreamData,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport { AudioFrame } from '../types/demuxer';\n\nexport type ParsedTimestamp = {\n pts?: number;\n dts?: number;\n};\n\nexport type PES = ParsedTimestamp & {\n data: Uint8Array;\n len: number;\n};\n\nexport type ParsedVideoSample = ParsedTimestamp &\n Omit<VideoSample, 'pts' | 'dts'>;\n\nexport interface TypeSupported {\n mpeg: boolean;\n mp3: boolean;\n ac3: boolean;\n}\n\nconst PACKET_LENGTH = 188;\n\nclass TSDemuxer implements Demuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n private typeSupported: TypeSupported;\n\n private sampleAes: SampleAesDecrypter | null = null;\n private pmtParsed: boolean = false;\n private audioCodec?: string;\n private videoCodec?: string;\n private _duration: number = 0;\n private _pmtId: number = -1;\n\n private _videoTrack?: DemuxedVideoTrack;\n private _audioTrack?: DemuxedAudioTrack;\n private _id3Track?: DemuxedMetadataTrack;\n private _txtTrack?: DemuxedUserdataTrack;\n private aacOverFlow: AudioFrame | null = null;\n private remainderData: Uint8Array | null = null;\n private videoParser: AvcVideoParser;\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported: TypeSupported,\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.videoParser = new AvcVideoParser();\n }\n\n static probe(data: Uint8Array) {\n const syncOffset = TSDemuxer.syncOffset(data);\n if (syncOffset > 0) {\n logger.warn(\n `MPEG2-TS detected but first sync word found @ offset ${syncOffset}`,\n );\n }\n return syncOffset !== -1;\n }\n\n static syncOffset(data: Uint8Array): number {\n const length = data.length;\n let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;\n let i = 0;\n while (i < scanwindow) {\n // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47\n let foundPat = false;\n let packetStart = -1;\n let tsPackets = 0;\n for (let j = i; j < length; j += PACKET_LENGTH) {\n if (\n data[j] === 0x47 &&\n (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)\n ) {\n tsPackets++;\n if (packetStart === -1) {\n packetStart = j;\n // First sync word found at offset, increase scan length (#5251)\n if (packetStart !== 0) {\n scanwindow =\n Math.min(\n packetStart + PACKET_LENGTH * 99,\n data.length - PACKET_LENGTH,\n ) + 1;\n }\n }\n if (!foundPat) {\n foundPat = parsePID(data, j) === 0;\n }\n // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)\n if (\n foundPat &&\n tsPackets > 1 &&\n ((packetStart === 0 && tsPackets > 2) ||\n j + PACKET_LENGTH > scanwindow)\n ) {\n return packetStart;\n }\n } else if (tsPackets) {\n // Exit if sync word found, but does not contain contiguous packets\n return -1;\n } else {\n break;\n }\n }\n i++;\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n */\n static createTrack(\n type: 'audio' | 'video' | 'id3' | 'text',\n duration?: number,\n ): DemuxedTrack {\n return {\n container:\n type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n duration: type === 'audio' ? duration : undefined,\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n */\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string,\n videoCodec: string,\n trackDuration: number,\n ) {\n this.pmtParsed = false;\n this._pmtId = -1;\n\n this._videoTrack = TSDemuxer.createTrack('video') as DemuxedVideoTrack;\n this._audioTrack = TSDemuxer.createTrack(\n 'audio',\n trackDuration,\n ) as DemuxedAudioTrack;\n this._id3Track = TSDemuxer.createTrack('id3') as DemuxedMetadataTrack;\n this._txtTrack = TSDemuxer.createTrack('text') as DemuxedUserdataTrack;\n this._audioTrack.segmentCodec = 'aac';\n\n // flush any partial content\n this.aacOverFlow = null;\n this.remainderData = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = trackDuration;\n }\n\n public resetTimeStamp() {}\n\n public resetContiguity(): void {\n const { _audioTrack, _videoTrack, _id3Track } = this;\n if (_audioTrack) {\n _audioTrack.pesData = null;\n }\n if (_videoTrack) {\n _videoTrack.pesData = null;\n }\n if (_id3Track) {\n _id3Track.pesData = null;\n }\n this.aacOverFlow = null;\n this.remainderData = null;\n }\n\n public demux(\n data: Uint8Array,\n timeOffset: number,\n isSampleAes = false,\n flush = false,\n ): DemuxerResult {\n if (!isSampleAes) {\n this.sampleAes = null;\n }\n\n let pes: PES | null;\n\n const videoTrack = this._videoTrack as DemuxedVideoTrack;\n const audioTrack = this._audioTrack as DemuxedAudioTrack;\n const id3Track = this._id3Track as DemuxedMetadataTrack;\n const textTrack = this._txtTrack as DemuxedUserdataTrack;\n\n let videoPid = videoTrack.pid;\n let videoData = videoTrack.pesData;\n let audioPid = audioTrack.pid;\n let id3Pid = id3Track.pid;\n let audioData = audioTrack.pesData;\n let id3Data = id3Track.pesData;\n let unknownPID: number | null = null;\n let pmtParsed = this.pmtParsed;\n let pmtId = this._pmtId;\n\n let len = data.length;\n if (this.remainderData) {\n data = appendUint8Array(this.remainderData, data);\n len = data.length;\n this.remainderData = null;\n }\n\n if (len < PACKET_LENGTH && !flush) {\n this.remainderData = data;\n return {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n }\n\n const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));\n len -= (len - syncOffset) % PACKET_LENGTH;\n if (len < data.byteLength && !flush) {\n this.remainderData = new Uint8Array(\n data.buffer,\n len,\n data.buffer.byteLength - len,\n );\n }\n\n // loop through TS packets\n let tsPacketErrors = 0;\n for (let start = syncOffset; start < len; start += PACKET_LENGTH) {\n if (data[start] === 0x47) {\n const stt = !!(data[start + 1] & 0x40);\n const pid = parsePID(data, start);\n const atf = (data[start + 3] & 0x30) >> 4;\n\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n let offset: number;\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === start + PACKET_LENGTH) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case videoPid:\n if (stt) {\n if (videoData && (pes = parsePES(videoData))) {\n this.videoParser.parseAVCPES(\n videoTrack,\n textTrack,\n pes,\n false,\n this._duration,\n );\n }\n\n videoData = { data: [], size: 0 };\n }\n if (videoData) {\n videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n videoData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case audioPid:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n case 'ac3':\n if (__USE_M2TS_ADVANCED_CODECS__) {\n this.parseAC3PES(audioTrack, pes);\n }\n break;\n }\n }\n audioData = { data: [], size: 0 };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n audioData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case id3Pid:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n }\n\n id3Data = { data: [], size: 0 };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));\n id3Data.size += start + PACKET_LENGTH - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n pmtId = this._pmtId = parsePAT(data, offset);\n // logger.log('PMT PID:' + this._pmtId);\n break;\n case pmtId: {\n if (stt) {\n offset += data[offset] + 1;\n }\n\n const parsedPIDs = parsePMT(\n data,\n offset,\n this.typeSupported,\n isSampleAes,\n this.observer,\n );\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n videoPid = parsedPIDs.videoPid;\n if (videoPid > 0) {\n videoTrack.pid = videoPid;\n videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;\n }\n\n audioPid = parsedPIDs.audioPid;\n if (audioPid > 0) {\n audioTrack.pid = audioPid;\n audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;\n }\n id3Pid = parsedPIDs.id3Pid;\n if (id3Pid > 0) {\n id3Track.pid = id3Pid;\n }\n\n if (unknownPID !== null && !pmtParsed) {\n logger.warn(\n `MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`,\n );\n unknownPID = null;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset - 188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n }\n case 0x11:\n case 0x1fff:\n break;\n default:\n unknownPID = pid;\n break;\n }\n } else {\n tsPacketErrors++;\n }\n }\n\n if (tsPacketErrors > 0) {\n emitParsingError(\n this.observer,\n new Error(\n `Found ${tsPacketErrors} TS packet/s that do not start with 0x47`,\n ),\n );\n }\n\n videoTrack.pesData = videoData;\n audioTrack.pesData = audioData;\n id3Track.pesData = id3Data;\n\n const demuxResult: DemuxerResult = {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n\n if (flush) {\n this.extractRemainingSamples(demuxResult);\n }\n\n return demuxResult;\n }\n\n public flush(): DemuxerResult | Promise<DemuxerResult> {\n const { remainderData } = this;\n this.remainderData = null;\n let result: DemuxerResult;\n if (remainderData) {\n result = this.demux(remainderData, -1, false, true);\n } else {\n result = {\n videoTrack: this._videoTrack as DemuxedVideoTrack,\n audioTrack: this._audioTrack as DemuxedAudioTrack,\n id3Track: this._id3Track as DemuxedMetadataTrack,\n textTrack: this._txtTrack as DemuxedUserdataTrack,\n };\n }\n this.extractRemainingSamples(result);\n if (this.sampleAes) {\n return this.decrypt(result, this.sampleAes);\n }\n return result;\n }\n\n private extractRemainingSamples(demuxResult: DemuxerResult) {\n const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult;\n const videoData = videoTrack.pesData;\n const audioData = audioTrack.pesData;\n const id3Data = id3Track.pesData;\n // try to parse last PES packets\n let pes: PES | null;\n if (videoData && (pes = parsePES(videoData))) {\n this.videoParser.parseAVCPES(\n videoTrack as DemuxedVideoTrack,\n textTrack as DemuxedUserdataTrack,\n pes,\n true,\n this._duration,\n );\n videoTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n videoTrack.pesData = videoData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n case 'ac3':\n if (__USE_M2TS_ADVANCED_CODECS__) {\n this.parseAC3PES(audioTrack, pes);\n }\n break;\n }\n audioTrack.pesData = null;\n } else {\n if (audioData?.size) {\n logger.log(\n 'last AAC PES packet truncated,might overlap between fragments',\n );\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n }\n\n public demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult> {\n const demuxResult = this.demux(\n data,\n timeOffset,\n true,\n !this.config.progressive,\n );\n const sampleAes = (this.sampleAes = new SampleAesDecrypter(\n this.observer,\n this.config,\n keyData,\n ));\n return this.decrypt(demuxResult, sampleAes);\n }\n\n private decrypt(\n demuxResult: DemuxerResult,\n sampleAes: SampleAesDecrypter,\n ): Promise<DemuxerResult> {\n return new Promise((resolve) => {\n const { audioTrack, videoTrack } = demuxResult;\n if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {\n sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {\n if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n } else {\n resolve(demuxResult);\n }\n });\n } else if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n }\n });\n }\n\n public destroy() {\n this._duration = 0;\n }\n\n private parseAACPES(track: DemuxedAudioTrack, pes: PES) {\n let startOffset = 0;\n const aacOverFlow = this.aacOverFlow;\n let data = pes.data;\n if (aacOverFlow) {\n this.aacOverFlow = null;\n const frameMissingBytes = aacOverFlow.missing;\n const sampleLength = aacOverFlow.sample.unit.byteLength;\n // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);\n if (frameMissingBytes === -1) {\n data = appendUint8Array(aacOverFlow.sample.unit, data);\n } else {\n const frameOverflowBytes = sampleLength - frameMissingBytes;\n aacOverFlow.sample.unit.set(\n data.subarray(0, frameMissingBytes),\n frameOverflowBytes,\n );\n track.samples.push(aacOverFlow.sample);\n startOffset = aacOverFlow.missing;\n }\n }\n // look for ADTS header (0xFFFx)\n let offset: number;\n let len: number;\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset !== startOffset) {\n let reason: string;\n const recoverable = offset < len - 1;\n if (recoverable) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n } else {\n reason = 'No ADTS header found in AAC PES';\n }\n emitParsingError(this.observer, new Error(reason), recoverable);\n if (!recoverable) {\n return;\n }\n }\n\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n this.audioCodec as string,\n );\n\n let pts: number;\n if (pes.pts !== undefined) {\n pts = pes.pts;\n } else if (aacOverFlow) {\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n const frameDuration = ADTS.getFrameDuration(track.samplerate as number);\n pts = aacOverFlow.sample.pts + frameDuration;\n } else {\n logger.warn('[tsdemuxer]: AAC PES unknown PTS');\n return;\n }\n\n // scan for aac samples\n let frameIndex = 0;\n let frame;\n while (offset < len) {\n frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n offset += frame.length;\n if (!frame.missing) {\n frameIndex++;\n for (; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n } else {\n this.aacOverFlow = frame;\n break;\n }\n }\n }\n\n private parseMPEGPES(track: DemuxedAudioTrack, pes: PES) {\n const data = pes.data;\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n const pts = pes.pts;\n if (pts === undefined) {\n logger.warn('[tsdemuxer]: MPEG PES unknown PTS');\n return;\n }\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n const frame = MpegAudio.appendFrame(\n track,\n data,\n offset,\n pts,\n frameIndex,\n );\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n\n private parseAC3PES(track: DemuxedAudioTrack, pes: PES) {\n if (__USE_M2TS_ADVANCED_CODECS__) {\n const data = pes.data;\n const pts = pes.pts;\n if (pts === undefined) {\n logger.warn('[tsdemuxer]: AC3 PES unknown PTS');\n return;\n }\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let parsed;\n\n while (\n offset < length &&\n (parsed = AC3.appendFrame(track, data, offset, pts, frameIndex++)) > 0\n ) {\n offset += parsed;\n }\n }\n }\n\n private parseID3PES(id3Track: DemuxedMetadataTrack, pes: PES) {\n if (pes.pts === undefined) {\n logger.warn('[tsdemuxer]: ID3 PES unknown PTS');\n return;\n }\n const id3Sample = Object.assign({}, pes as Required<PES>, {\n type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n id3Track.samples.push(id3Sample);\n }\n}\n\nfunction parsePID(data: Uint8Array, offset: number): number {\n // pid is a 13-bit field starting at the last bit of TS[1]\n return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];\n}\n\nfunction parsePAT(data: Uint8Array, offset: number): number {\n // skip the PSI header and parse the first PMT entry\n return ((data[offset + 10] & 0x1f) << 8) | data[offset + 11];\n}\n\nfunction parsePMT(\n data: Uint8Array,\n offset: number,\n typeSupported: TypeSupported,\n isSampleAes: boolean,\n observer: HlsEventEmitter,\n) {\n const result = {\n audioPid: -1,\n videoPid: -1,\n id3Pid: -1,\n segmentVideoCodec: 'avc',\n segmentAudioCodec: 'aac',\n };\n const sectionLength = ((data[offset + 1] & 0x0f) << 8) | data[offset + 2];\n const tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n const programInfoLength =\n ((data[offset + 10] & 0x0f) << 8) | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n const pid = parsePID(data, offset);\n const esInfoLength = ((data[offset + 3] & 0x0f) << 8) | data[offset + 4];\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');\n break;\n }\n /* falls through */\n case 0x0f: // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n // logger.log('AAC PID:' + pid);\n if (result.audioPid === -1) {\n result.audioPid = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3Pid === -1) {\n result.id3Pid = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('H.264');\n break;\n }\n /* falls through */\n case 0x1b: // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n // logger.log('AVC PID:' + pid);\n if (result.videoPid === -1) {\n result.videoPid = pid;\n result.segmentVideoCodec = 'avc';\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (!typeSupported.mpeg && !typeSupported.mp3) {\n logger.log('MPEG audio found, not supported in this browser');\n } else if (result.audioPid === -1) {\n result.audioPid = pid;\n result.segmentAudioCodec = 'mp3';\n }\n break;\n\n case 0xc1: // SAMPLE-AES AC3\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('AC-3');\n break;\n }\n /* falls through */\n case 0x81:\n if (__USE_M2TS_ADVANCED_CODECS__) {\n if (!typeSupported.ac3) {\n logger.log('AC-3 audio found, not supported in this browser');\n } else if (result.audioPid === -1) {\n result.audioPid = pid;\n result.segmentAudioCodec = 'ac3';\n }\n } else {\n logger.warn('AC-3 in M2TS support not included in build');\n }\n break;\n\n case 0x06:\n // stream_type 6 can mean a lot of different things in case of DVB.\n // We need to look at the descriptors. Right now, we're only interested\n // in AC-3 audio, so we do the descriptor parsing only when we don't have\n // an audio PID yet.\n if (result.audioPid === -1 && esInfoLength > 0) {\n let parsePos = offset + 5;\n let remaining = esInfoLength;\n\n while (remaining > 2) {\n const descriptorId = data[parsePos];\n\n switch (descriptorId) {\n case 0x6a: // DVB Descriptor for AC-3\n if (__USE_M2TS_ADVANCED_CODECS__) {\n if (typeSupported.ac3 !== true) {\n logger.log(\n 'AC-3 audio found, not supported in this browser for now',\n );\n } else {\n result.audioPid = pid;\n result.segmentAudioCodec = 'ac3';\n }\n } else {\n logger.warn('AC-3 in M2TS support not included in build');\n }\n break;\n }\n\n const descriptorLen = data[parsePos + 1] + 2;\n parsePos += descriptorLen;\n remaining -= descriptorLen;\n }\n }\n break;\n\n case 0xc2: // SAMPLE-AES EC3\n /* falls through */\n case 0x87:\n emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'));\n return result;\n\n case 0x24:\n emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'));\n return result;\n\n default:\n // logger.log('unknown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += esInfoLength + 5;\n }\n return result;\n}\n\nfunction emitParsingError(\n observer: HlsEventEmitter,\n error: Error,\n levelRetry?: boolean,\n) {\n logger.warn(`parsing error: ${error.message}`);\n observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n levelRetry,\n error,\n reason: error.message,\n });\n}\n\nfunction logEncryptedSamplesFoundInUnencryptedStream(type: string) {\n logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);\n}\n\nfunction parsePES(stream: ElementaryStreamData): PES | null {\n let i = 0;\n let frag: Uint8Array;\n let pesLen: number;\n let pesHdrLen: number;\n let pesPts: number | undefined;\n let pesDts: number | undefined;\n const data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n data[0] = appendUint8Array(data[0], data[1]);\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n\n const pesFlags = frag[7];\n if (pesFlags & 0xc0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts =\n (frag[9] & 0x0e) * 536870912 + // 1 << 29\n (frag[10] & 0xff) * 4194304 + // 1 << 22\n (frag[11] & 0xfe) * 16384 + // 1 << 14\n (frag[12] & 0xff) * 128 + // 1 << 7\n (frag[13] & 0xfe) / 2;\n\n if (pesFlags & 0x40) {\n pesDts =\n (frag[14] & 0x0e) * 536870912 + // 1 << 29\n (frag[15] & 0xff) * 4194304 + // 1 << 22\n (frag[16] & 0xfe) * 16384 + // 1 << 14\n (frag[17] & 0xff) * 128 + // 1 << 7\n (frag[18] & 0xfe) / 2;\n\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(\n `${Math.round(\n (pesPts - pesDts) / 90000,\n )}s delta between PTS and DTS, align them`,\n );\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n let payloadStartOffset = pesHdrLen + 9;\n if (stream.size <= payloadStartOffset) {\n return null;\n }\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n const pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };\n }\n return null;\n}\n\nexport default TSDemuxer;\n","/**\n * MP3 demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport { getID3Data, getTimeStamp } from '../id3';\nimport { getAudioBSID } from './dolby';\nimport { logger } from '../../utils/logger';\nimport * as MpegAudio from './mpegaudio';\n\nclass MP3Demuxer extends BaseAudioDemuxer {\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/mpeg',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'mp3',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n static probe(data: Uint8Array | undefined): boolean {\n if (!data) {\n return false;\n }\n\n // check if data contains ID3 timestamp and MPEG sync word\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n const id3Data = getID3Data(data, 0);\n let offset = id3Data?.length || 0;\n\n // Check for ac-3|ec-3 sync bytes and return false if present\n if (\n id3Data &&\n data[offset] === 0x0b &&\n data[offset + 1] === 0x77 &&\n getTimeStamp(id3Data) !== undefined &&\n // check the bsid to confirm ac-3 or ec-3 (not mp3)\n getAudioBSID(data, offset) <= 16\n ) {\n return false;\n }\n\n for (let length = data.length; offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return MpegAudio.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n if (this.basePTS === null) {\n return;\n }\n return MpegAudio.appendFrame(\n track,\n data,\n offset,\n this.basePTS,\n this.frameIndex,\n );\n }\n}\n\nexport default MP3Demuxer;\n","export const getAudioBSID = (data: Uint8Array, offset: number): number => {\n // check the bsid to confirm ac-3 | ec-3\n let bsid = 0;\n let numBits = 5;\n offset += numBits;\n const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage\n const mask = new Uint32Array(1); // unsigned 32 bit mask value\n const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage\n while (numBits > 0) {\n byte[0] = data[offset];\n // read remaining bits, upto 8 bits at a time\n const bits = Math.min(numBits, 8);\n const shift = 8 - bits;\n mask[0] = (0xff000000 >>> (24 + shift)) << shift;\n temp[0] = (byte[0] & mask[0]) >> shift;\n bsid = !bsid ? temp[0] : (bsid << bits) | temp[0];\n offset += 1;\n numBits -= bits;\n }\n return bsid;\n};\n","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame(\n codec?: string,\n channelCount?: number,\n ): Uint8Array | undefined {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([\n 0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80,\n ]);\n } else if (channelCount === 3) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x8e,\n ]);\n } else if (channelCount === 4) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38,\n ]);\n } else if (channelCount === 5) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38,\n ]);\n } else if (channelCount === 6) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2,\n 0x00, 0x20, 0x08, 0xe0,\n ]);\n }\n\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n }\n break;\n }\n return undefined;\n }\n}\n\nexport default AAC;\n","/**\n * Generate MP4 Box\n */\n\nimport { appendUint8Array } from '../utils/mp4-tools';\n\ntype HdlrTypes = {\n video: Uint8Array;\n audio: Uint8Array;\n};\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n public static types: Record<string, number[]>;\n private static HDLR_TYPES: HdlrTypes;\n private static STTS: Uint8Array;\n private static STSC: Uint8Array;\n private static STCO: Uint8Array;\n private static STSZ: Uint8Array;\n private static VMHD: Uint8Array;\n private static SMHD: Uint8Array;\n private static STSD: Uint8Array;\n private static FTYP: Uint8Array;\n private static DINF: Uint8Array;\n\n static init() {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n dac3: [],\n 'ac-3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: [],\n };\n\n let i: string;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3),\n ];\n }\n }\n\n const videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x76,\n 0x69,\n 0x64,\n 0x65, // handler_type: 'vide'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x56,\n 0x69,\n 0x64,\n 0x65,\n 0x6f,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'VideoHandler'\n ]);\n\n const audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x73,\n 0x6f,\n 0x75,\n 0x6e, // handler_type: 'soun'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x53,\n 0x6f,\n 0x75,\n 0x6e,\n 0x64,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n video: videoHdlr,\n audio: audioHdlr,\n };\n\n const dref = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01, // entry_count\n 0x00,\n 0x00,\n 0x00,\n 0x0c, // entry_size\n 0x75,\n 0x72,\n 0x6c,\n 0x20, // 'url' type\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x01, // entry_flags\n ]);\n\n const stco = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x01, // flags\n 0x00,\n 0x00, // graphicsmode\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00, // balance\n 0x00,\n 0x00, // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n ]); // entry_count\n\n const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n const minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(\n MP4.types.ftyp,\n majorBrand,\n minorVersion,\n majorBrand,\n avc1Brand,\n );\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box(type, ...payload: Uint8Array[]) {\n let size = 8;\n let i = payload.length;\n const len = i;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n\n const result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.mdhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x55,\n 0xc4, // 'und' language (undetermined)\n 0x00,\n 0x00,\n ]),\n );\n }\n\n static mdia(track) {\n return MP4.box(\n MP4.types.mdia,\n MP4.mdhd(track.timescale, track.duration),\n MP4.hdlr(track.type),\n MP4.minf(track),\n );\n }\n\n static mfhd(sequenceNumber) {\n return MP4.box(\n MP4.types.mfhd,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00,\n 0x00, // flags\n sequenceNumber >> 24,\n (sequenceNumber >> 16) & 0xff,\n (sequenceNumber >> 8) & 0xff,\n sequenceNumber & 0xff, // sequence_number\n ]),\n );\n }\n\n static minf(track) {\n if (track.type === 'audio') {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.smhd, MP4.SMHD),\n MP4.DINF,\n MP4.stbl(track),\n );\n } else {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.vmhd, MP4.VMHD),\n MP4.DINF,\n MP4.stbl(track),\n );\n }\n }\n\n static moof(sn, baseMediaDecodeTime, track) {\n return MP4.box(\n MP4.types.moof,\n MP4.mfhd(sn),\n MP4.traf(track, baseMediaDecodeTime),\n );\n }\n\n static moov(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(\n null,\n [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)]\n .concat(boxes)\n .concat(MP4.mvex(tracks)),\n );\n }\n\n static mvex(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);\n }\n\n static mvhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n const bytes = new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x01,\n 0x00,\n 0x00, // 1.0 rate\n 0x01,\n 0x00, // 1.0 volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0xff,\n 0xff,\n 0xff,\n 0xff, // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp(track) {\n const samples = track.samples || [];\n const bytes = new Uint8Array(4 + samples.length);\n let i;\n let flags;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] =\n (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n flags.hasRedundancy;\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl(track) {\n return MP4.box(\n MP4.types.stbl,\n MP4.stsd(track),\n MP4.box(MP4.types.stts, MP4.STTS),\n MP4.box(MP4.types.stsc, MP4.STSC),\n MP4.box(MP4.types.stsz, MP4.STSZ),\n MP4.box(MP4.types.stco, MP4.STCO),\n );\n }\n\n static avc1(track) {\n let sps: number[] = [];\n let pps: number[] = [];\n let i;\n let data;\n let len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xff);\n sps.push(len & 0xff);\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xff);\n pps.push(len & 0xff);\n\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n const avcc = MP4.box(\n MP4.types.avcC,\n new Uint8Array(\n [\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xe0 | track.sps.length, // 3bit reserved (111) + numOfSequenceParameterSets\n ]\n .concat(sps)\n .concat([\n track.pps.length, // numOfPictureParameterSets\n ])\n .concat(pps),\n ),\n ); // \"PPS\"\n const width = track.width;\n const height = track.height;\n const hSpacing = track.pixelRatio[0];\n const vSpacing = track.pixelRatio[1];\n\n return MP4.box(\n MP4.types.avc1,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00, // pre_defined\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n (width >> 8) & 0xff,\n width & 0xff, // width\n (height >> 8) & 0xff,\n height & 0xff, // height\n 0x00,\n 0x48,\n 0x00,\n 0x00, // horizresolution\n 0x00,\n 0x48,\n 0x00,\n 0x00, // vertresolution\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // frame_count\n 0x12,\n 0x64,\n 0x61,\n 0x69,\n 0x6c, // dailymotion/hls.js\n 0x79,\n 0x6d,\n 0x6f,\n 0x74,\n 0x69,\n 0x6f,\n 0x6e,\n 0x2f,\n 0x68,\n 0x6c,\n 0x73,\n 0x2e,\n 0x6a,\n 0x73,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // compressorname\n 0x00,\n 0x18, // depth = 24\n 0x11,\n 0x11,\n ]), // pre_defined = -1\n avcc,\n MP4.box(\n MP4.types.btrt,\n new Uint8Array([\n 0x00,\n 0x1c,\n 0x9c,\n 0x80, // bufferSizeDB\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0, // maxBitrate\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0,\n ]),\n ), // avgBitrate\n MP4.box(\n MP4.types.pasp,\n new Uint8Array([\n hSpacing >> 24, // hSpacing\n (hSpacing >> 16) & 0xff,\n (hSpacing >> 8) & 0xff,\n hSpacing & 0xff,\n vSpacing >> 24, // vSpacing\n (vSpacing >> 16) & 0xff,\n (vSpacing >> 8) & 0xff,\n vSpacing & 0xff,\n ]),\n ),\n );\n }\n\n static esds(track) {\n const configlen = track.config.length;\n return new Uint8Array(\n [\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17 + configlen, // length\n 0x00,\n 0x01, // es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f + configlen, // length\n 0x40, // codec : mpeg4_audio\n 0x15, // stream_type\n 0x00,\n 0x00,\n 0x00, // buffer_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // maxBitrate\n 0x00,\n 0x00,\n 0x00,\n 0x00, // avgBitrate\n\n 0x05, // descriptor_type\n ]\n .concat([configlen])\n .concat(track.config)\n .concat([0x06, 0x01, 0x02]),\n ); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static audioStsd(track) {\n const samplerate = track.samplerate;\n return new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n track.channelCount, // channelcount\n 0x00,\n 0x10, // sampleSize:16bits\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved2\n (samplerate >> 8) & 0xff,\n samplerate & 0xff, //\n 0x00,\n 0x00,\n ]);\n }\n\n static mp4a(track) {\n return MP4.box(\n MP4.types.mp4a,\n MP4.audioStsd(track),\n MP4.box(MP4.types.esds, MP4.esds(track)),\n );\n }\n\n static mp3(track) {\n return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));\n }\n\n static ac3(track) {\n return MP4.box(\n MP4.types['ac-3'],\n MP4.audioStsd(track),\n MP4.box(MP4.types.dac3, track.config),\n );\n }\n\n static stsd(track) {\n if (track.type === 'audio') {\n if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n if (track.segmentCodec === 'ac3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));\n }\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd(track) {\n const id = track.id;\n const duration = track.duration * track.timescale;\n const width = track.width;\n const height = track.height;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.tkhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x07, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (id >> 24) & 0xff,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00, // layer\n 0x00,\n 0x00, // alternate_group\n 0x00,\n 0x00, // non-audio track volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n (width >> 8) & 0xff,\n width & 0xff,\n 0x00,\n 0x00, // width\n (height >> 8) & 0xff,\n height & 0xff,\n 0x00,\n 0x00, // height\n ]),\n );\n }\n\n static traf(track, baseMediaDecodeTime) {\n const sampleDependencyTable = MP4.sdtp(track);\n const id = track.id;\n const upperWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime / (UINT32_MAX + 1),\n );\n const lowerWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime % (UINT32_MAX + 1),\n );\n return MP4.box(\n MP4.types.traf,\n MP4.box(\n MP4.types.tfhd,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n ]),\n ),\n MP4.box(\n MP4.types.tfdt,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n upperWordBaseMediaDecodeTime >> 24,\n (upperWordBaseMediaDecodeTime >> 16) & 0xff,\n (upperWordBaseMediaDecodeTime >> 8) & 0xff,\n upperWordBaseMediaDecodeTime & 0xff,\n lowerWordBaseMediaDecodeTime >> 24,\n (lowerWordBaseMediaDecodeTime >> 16) & 0xff,\n (lowerWordBaseMediaDecodeTime >> 8) & 0xff,\n lowerWordBaseMediaDecodeTime & 0xff,\n ]),\n ),\n MP4.trun(\n track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8,\n ), // mdat header\n sampleDependencyTable,\n );\n }\n\n /**\n * Generate a track box.\n * @param track a track definition\n */\n static trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex(track) {\n const id = track.id;\n return MP4.box(\n MP4.types.trex,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x01, // default_sample_description_index\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_duration\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_size\n 0x00,\n 0x01,\n 0x00,\n 0x01, // default_sample_flags\n ]),\n );\n }\n\n static trun(track, offset) {\n const samples = track.samples || [];\n const len = samples.length;\n const arraylen = 12 + 16 * len;\n const array = new Uint8Array(arraylen);\n let i;\n let sample;\n let duration;\n let size;\n let flags;\n let cts;\n offset += 8 + arraylen;\n array.set(\n [\n track.type === 'video' ? 0x01 : 0x00, // version 1 for video with signed-int sample_composition_time_offset\n 0x00,\n 0x0f,\n 0x01, // flags\n (len >>> 24) & 0xff,\n (len >>> 16) & 0xff,\n (len >>> 8) & 0xff,\n len & 0xff, // sample_count\n (offset >>> 24) & 0xff,\n (offset >>> 16) & 0xff,\n (offset >>> 8) & 0xff,\n offset & 0xff, // data_offset\n ],\n 0,\n );\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set(\n [\n (duration >>> 24) & 0xff,\n (duration >>> 16) & 0xff,\n (duration >>> 8) & 0xff,\n duration & 0xff, // sample_duration\n (size >>> 24) & 0xff,\n (size >>> 16) & 0xff,\n (size >>> 8) & 0xff,\n size & 0xff, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & (0xf0 << 8),\n flags.degradPrio & 0x0f, // sample_flags\n (cts >>> 24) & 0xff,\n (cts >>> 16) & 0xff,\n (cts >>> 8) & 0xff,\n cts & 0xff, // sample_composition_time_offset\n ],\n 12 + 16 * i,\n );\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n const movie = MP4.moov(tracks);\n const result = appendUint8Array(MP4.FTYP, movie);\n return result;\n }\n}\n\nexport default MP4;\n","const MPEG_TS_CLOCK_FREQ_HZ = 90000;\n\nexport type RationalTimestamp = {\n baseTime: number; // ticks\n timescale: number; // ticks per second\n};\n\nexport function toTimescaleFromBase(\n baseTime: number,\n destScale: number,\n srcBase: number = 1,\n round: boolean = false,\n): number {\n const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\n\nexport function toTimescaleFromScale(\n baseTime: number,\n destScale: number,\n srcScale: number = 1,\n round: boolean = false,\n): number {\n return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);\n}\n\nexport function toMsFromMpegTsClock(\n baseTime: number,\n round: boolean = false,\n): number {\n return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\n\nexport function toMpegTsClockFromTimescale(\n baseTime: number,\n srcScale: number = 1,\n): number {\n return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n}\n","import AAC from './aac-helper';\nimport MP4 from './mp4-generator';\nimport type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport {\n InitSegmentData,\n Remuxer,\n RemuxerResult,\n RemuxedMetadata,\n RemuxedTrack,\n RemuxedUserdata,\n} from '../types/remuxer';\nimport { PlaylistLevelType } from '../types/loader';\nimport {\n RationalTimestamp,\n toMsFromMpegTsClock,\n} from '../utils/timescale-conversion';\nimport type {\n AudioSample,\n VideoSample,\n DemuxedAudioTrack,\n DemuxedVideoTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n} from '../types/demuxer';\nimport type { TrackSet } from '../types/track';\nimport type { SourceBufferName } from '../types/buffer';\nimport type { Fragment } from '../loader/fragment';\nimport type { HlsConfig } from '../config';\n\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds\nconst AAC_SAMPLES_PER_FRAME = 1024;\nconst MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;\nconst AC3_SAMPLES_PER_FRAME = 1536;\n\nlet chromeVersion: number | null = null;\nlet safariWebkitVersion: number | null = null;\n\nexport default class MP4Remuxer implements Remuxer {\n private observer: HlsEventEmitter;\n private config: HlsConfig;\n private typeSupported: any;\n private ISGenerated: boolean = false;\n private _initPTS: RationalTimestamp | null = null;\n private _initDTS: RationalTimestamp | null = null;\n private nextAvcDts: number | null = null;\n private nextAudioPts: number | null = null;\n private videoSampleDuration: number | null = null;\n private isAudioContiguous: boolean = false;\n private isVideoContiguous: boolean = false;\n private videoTrackConfig?: {\n width?: number;\n height?: number;\n pixelRatio?: [number, number];\n };\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported,\n vendor = '',\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n if (safariWebkitVersion === null) {\n const result = navigator.userAgent.match(/Safari\\/(\\d+)/i);\n safariWebkitVersion = result ? parseInt(result[1]) : 0;\n }\n }\n\n destroy() {\n // @ts-ignore\n this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;\n }\n\n resetTimeStamp(defaultTimeStamp: RationalTimestamp | null) {\n logger.log('[mp4-remuxer]: initPTS & initDTS reset');\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetNextTimestamp() {\n logger.log('[mp4-remuxer]: reset next timestamp');\n this.isVideoContiguous = false;\n this.isAudioContiguous = false;\n }\n\n resetInitSegment() {\n logger.log('[mp4-remuxer]: ISGenerated flag reset');\n this.ISGenerated = false;\n this.videoTrackConfig = undefined;\n }\n\n getVideoStartPts(videoSamples) {\n let rolloverDetected = false;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n const delta = sample.pts - minPTS;\n if (delta < -4294967296) {\n // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n return normalizePts(minPTS, sample.pts);\n } else if (delta > 0) {\n return minPTS;\n } else {\n return sample.pts;\n }\n }, videoSamples[0].pts);\n if (rolloverDetected) {\n logger.debug('PTS rollover detected');\n }\n return startPTS;\n }\n\n remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedVideoTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n flush: boolean,\n playlistType: PlaylistLevelType,\n ): RemuxerResult {\n let video: RemuxedTrack | undefined;\n let audio: RemuxedTrack | undefined;\n let initSegment: InitSegmentData | undefined;\n let text: RemuxedUserdata | undefined;\n let id3: RemuxedMetadata | undefined;\n let independent: boolean | undefined;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n\n // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.\n // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the \"pid\"\n // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.\n // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),\n // then we can remux one track without waiting for the other.\n const hasAudio = audioTrack.pid > -1;\n const hasVideo = videoTrack.pid > -1;\n const length = videoTrack.samples.length;\n const enoughAudioSamples = audioTrack.samples.length > 0;\n const enoughVideoSamples = (flush && length > 0) || length > 1;\n const canRemuxAvc =\n ((!hasAudio || enoughAudioSamples) &&\n (!hasVideo || enoughVideoSamples)) ||\n this.ISGenerated ||\n flush;\n\n if (canRemuxAvc) {\n if (this.ISGenerated) {\n const config = this.videoTrackConfig;\n if (\n config &&\n (videoTrack.width !== config.width ||\n videoTrack.height !== config.height ||\n videoTrack.pixelRatio?.[0] !== config.pixelRatio?.[0] ||\n videoTrack.pixelRatio?.[1] !== config.pixelRatio?.[1])\n ) {\n this.resetInitSegment();\n }\n } else {\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset,\n );\n }\n\n const isVideoContiguous = this.isVideoContiguous;\n let firstKeyFrameIndex = -1;\n let firstKeyFramePTS;\n\n if (enoughVideoSamples) {\n firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);\n if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {\n independent = true;\n if (firstKeyFrameIndex > 0) {\n logger.warn(\n `[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`,\n );\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);\n videoTrack.dropped += firstKeyFrameIndex;\n videoTimeOffset +=\n (videoTrack.samples[0].pts - startPTS) /\n videoTrack.inputTimeScale;\n firstKeyFramePTS = videoTimeOffset;\n } else if (firstKeyFrameIndex === -1) {\n logger.warn(\n `[mp4-remuxer]: No keyframe found out of ${length} video samples`,\n );\n independent = false;\n }\n }\n }\n\n if (this.ISGenerated) {\n if (enoughAudioSamples && enoughVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n const tsDelta =\n normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;\n const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\n }\n\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.\n if (enoughAudioSamples) {\n // if initSegment was generated without audio samples, regenerate it again\n if (!audioTrack.samplerate) {\n logger.warn(\n '[mp4-remuxer]: regenerate InitSegment as audio detected',\n );\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset,\n );\n }\n audio = this.remuxAudio(\n audioTrack,\n audioTimeOffset,\n this.isAudioContiguous,\n accurateTimeOffset,\n hasVideo ||\n enoughVideoSamples ||\n playlistType === PlaylistLevelType.AUDIO\n ? videoTimeOffset\n : undefined,\n );\n if (enoughVideoSamples) {\n const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.inputTimeScale) {\n logger.warn(\n '[mp4-remuxer]: regenerate InitSegment as video detected',\n );\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset,\n );\n }\n video = this.remuxVideo(\n videoTrack,\n videoTimeOffset,\n isVideoContiguous,\n audioTrackLength,\n );\n }\n } else if (enoughVideoSamples) {\n video = this.remuxVideo(\n videoTrack,\n videoTimeOffset,\n isVideoContiguous,\n 0,\n );\n }\n if (video) {\n video.firstKeyFrame = firstKeyFrameIndex;\n video.independent = firstKeyFrameIndex !== -1;\n video.firstKeyFramePTS = firstKeyFramePTS;\n }\n }\n }\n\n // Allow ID3 and text to remux, even if more audio/video samples are required\n if (this.ISGenerated && this._initPTS && this._initDTS) {\n if (id3Track.samples.length) {\n id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n this._initPTS,\n this._initDTS,\n );\n }\n\n if (textTrack.samples.length) {\n text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n this._initPTS,\n );\n }\n }\n\n return {\n audio,\n video,\n initSegment,\n independent,\n text,\n id3,\n };\n }\n\n generateIS(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedVideoTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n ): InitSegmentData | undefined {\n const audioSamples = audioTrack.samples;\n const videoSamples = videoTrack.samples;\n const typeSupported = this.typeSupported;\n const tracks: TrackSet = {};\n const _initPTS = this._initPTS;\n let computePTSDTS = !_initPTS || accurateTimeOffset;\n let container = 'audio/mp4';\n let initPTS: number | undefined;\n let initDTS: number | undefined;\n let timescale: number | undefined;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n switch (audioTrack.segmentCodec) {\n case 'mp3':\n if (typeSupported.mpeg) {\n // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) {\n // Firefox\n audioTrack.codec = 'mp3';\n }\n break;\n\n case 'ac3':\n audioTrack.codec = 'ac-3';\n break;\n }\n tracks.audio = {\n id: 'audio',\n container: container,\n codec: audioTrack.codec,\n initSegment:\n audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg\n ? new Uint8Array(0)\n : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount,\n },\n };\n if (computePTSDTS) {\n timescale = audioTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS =\n audioSamples[0].pts - Math.round(timescale * timeOffset);\n } else {\n computePTSDTS = false;\n }\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n videoTrack.timescale = videoTrack.inputTimeScale;\n tracks.video = {\n id: 'main',\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height,\n },\n };\n if (computePTSDTS) {\n timescale = videoTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n const startPTS = this.getVideoStartPts(videoSamples);\n const startOffset = Math.round(timescale * timeOffset);\n initDTS = Math.min(\n initDTS as number,\n normalizePts(videoSamples[0].dts, startPTS) - startOffset,\n );\n initPTS = Math.min(initPTS as number, startPTS - startOffset);\n } else {\n computePTSDTS = false;\n }\n }\n this.videoTrackConfig = {\n width: videoTrack.width,\n height: videoTrack.height,\n pixelRatio: videoTrack.pixelRatio,\n };\n }\n\n if (Object.keys(tracks).length) {\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = {\n baseTime: initPTS as number,\n timescale: timescale as number,\n };\n this._initDTS = {\n baseTime: initDTS as number,\n timescale: timescale as number,\n };\n } else {\n initPTS = timescale = undefined;\n }\n\n return {\n tracks,\n initPTS,\n timescale,\n };\n }\n }\n\n remuxVideo(\n track: DemuxedVideoTrack,\n timeOffset: number,\n contiguous: boolean,\n audioTrackLength: number,\n ): RemuxedTrack | undefined {\n const timeScale: number = track.inputTimeScale;\n const inputSamples: Array<VideoSample> = track.samples;\n const outputSamples: Array<Mp4Sample> = [];\n const nbSamples = inputSamples.length;\n const initPTS = this._initPTS as RationalTimestamp;\n let nextAvcDts = this.nextAvcDts;\n let offset = 8;\n let mp4SampleDuration = this.videoSampleDuration;\n let firstDTS;\n let lastDTS;\n let minPTS: number = Number.POSITIVE_INFINITY;\n let maxPTS: number = Number.NEGATIVE_INFINITY;\n let sortSamples = false;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n if (!contiguous || nextAvcDts === null) {\n const pts = timeOffset * timeScale;\n const cts =\n inputSamples[0].pts -\n normalizePts(inputSamples[0].dts, inputSamples[0].pts);\n if (\n chromeVersion &&\n nextAvcDts !== null &&\n Math.abs(pts - cts - nextAvcDts) < 15000\n ) {\n // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome\n contiguous = true;\n } else {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\n }\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n const initTime = (initPTS.baseTime * timeScale) / initPTS.timescale;\n for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);\n sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || deltapts;\n });\n }\n\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[inputSamples.length - 1].dts;\n\n // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n const inputDuration = lastDTS - firstDTS;\n const averageSampleDuration = inputDuration\n ? Math.round(inputDuration / (nbSamples - 1))\n : mp4SampleDuration || track.inputTimeScale / 30;\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n delta,\n true,\n )} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(\n 3,\n )}`,\n );\n } else {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n -delta,\n true,\n )} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(\n 3,\n )}`,\n );\n }\n if (\n !foundOverlap ||\n nextAvcDts >= inputSamples[0].pts ||\n chromeVersion\n ) {\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n if (foundHole) {\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n } else {\n for (let i = 0; i < inputSamples.length; i++) {\n if (inputSamples[i].dts > firstPTS) {\n break;\n }\n inputSamples[i].dts -= delta;\n inputSamples[i].pts -= delta;\n }\n }\n logger.log(\n `Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(\n firstPTS,\n true,\n )}/${toMsFromMpegTsClock(\n firstDTS,\n true,\n )}, delta: ${toMsFromMpegTsClock(delta, true)} ms`,\n );\n }\n }\n }\n\n firstDTS = Math.max(0, firstDTS);\n\n let nbNalu = 0;\n let naluLen = 0;\n let dtsStep = firstDTS;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // ensure sample monotonic DTS\n if (sample.dts < dtsStep) {\n sample.dts = dtsStep;\n dtsStep += (averageSampleDuration / 4) | 0 || 1;\n } else {\n dtsStep = sample.dts;\n }\n\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n const mdatSize = naluLen + 4 * nbNalu + 8;\n let mdat;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating video mdat ${mdatSize}`,\n });\n return;\n }\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n let stretchedLastFrame = false;\n let minDtsDelta = Number.POSITIVE_INFINITY;\n let minPtsDelta = Number.POSITIVE_INFINITY;\n let maxDtsDelta = Number.NEGATIVE_INFINITY;\n let maxPtsDelta = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < nbSamples; i++) {\n const VideoSample = inputSamples[i];\n const VideoSampleUnits = VideoSample.units;\n let mp4SampleLength = 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {\n const unit = VideoSampleUnits[j];\n const unitData = unit.data;\n const unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n let ptsDelta;\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;\n ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;\n } else {\n const config = this.config;\n const lastFrameDuration =\n i > 0\n ? VideoSample.dts - inputSamples[i - 1].dts\n : averageSampleDuration;\n ptsDelta =\n i > 0\n ? VideoSample.pts - inputSamples[i - 1].pts\n : averageSampleDuration;\n if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n const gapTolerance = Math.floor(config.maxBufferHole * timeScale);\n const deltaToFrameEnd =\n (audioTrackLength\n ? minPTS + audioTrackLength * timeScale\n : this.nextAudioPts) - VideoSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n } else {\n stretchedLastFrame = true;\n }\n logger.log(\n `[mp4-remuxer]: It is approximately ${\n deltaToFrameEnd / 90\n } ms to the next segment; using duration ${\n mp4SampleDuration / 90\n } ms for the last video frame.`,\n );\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n const compositionTimeOffset = Math.round(\n VideoSample.pts - VideoSample.dts,\n );\n minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);\n maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);\n minPtsDelta = Math.min(minPtsDelta, ptsDelta);\n maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);\n\n outputSamples.push(\n new Mp4Sample(\n VideoSample.key,\n mp4SampleDuration,\n mp4SampleLength,\n compositionTimeOffset,\n ),\n );\n }\n\n if (outputSamples.length) {\n if (chromeVersion) {\n if (chromeVersion < 70) {\n // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n const flags = outputSamples[0].flags;\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n } else if (safariWebkitVersion) {\n // Fix for \"CNN special report, with CC\" in test-streams (Safari browser only)\n // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.\n if (\n maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta &&\n averageSampleDuration / maxDtsDelta < 0.025 &&\n outputSamples[0].cts === 0\n ) {\n logger.warn(\n 'Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.',\n );\n let dts = firstDTS;\n for (let i = 0, len = outputSamples.length; i < len; i++) {\n const nextDts = dts + outputSamples[i].duration;\n const pts = dts + outputSamples[i].cts;\n if (i < len - 1) {\n const nextPts = nextDts + outputSamples[i + 1].cts;\n outputSamples[i].duration = nextPts - pts;\n } else {\n outputSamples[i].duration = i\n ? outputSamples[i - 1].duration\n : averageSampleDuration;\n }\n outputSamples[i].cts = 0;\n dts = nextDts;\n }\n }\n }\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n mp4SampleDuration =\n stretchedLastFrame || !mp4SampleDuration\n ? averageSampleDuration\n : mp4SampleDuration;\n this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;\n this.videoSampleDuration = mp4SampleDuration;\n this.isVideoContiguous = true;\n const moof = MP4.moof(\n track.sequenceNumber++,\n firstDTS,\n Object.assign({}, track, {\n samples: outputSamples,\n }),\n );\n const type: SourceBufferName = 'video';\n const data = {\n data1: moof,\n data2: mdat,\n startPTS: minPTS / timeScale,\n endPTS: (maxPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: (nextAvcDts as number) / timeScale,\n type,\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: track.dropped,\n };\n track.samples = [];\n track.dropped = 0;\n return data;\n }\n\n getSamplesPerFrame(track: DemuxedAudioTrack) {\n switch (track.segmentCodec) {\n case 'mp3':\n return MPEG_AUDIO_SAMPLE_PER_FRAME;\n case 'ac3':\n return AC3_SAMPLES_PER_FRAME;\n default:\n return AAC_SAMPLES_PER_FRAME;\n }\n }\n\n remuxAudio(\n track: DemuxedAudioTrack,\n timeOffset: number,\n contiguous: boolean,\n accurateTimeOffset: boolean,\n videoTimeOffset?: number,\n ): RemuxedTrack | undefined {\n const inputTimeScale: number = track.inputTimeScale;\n const mp4timeScale: number = track.samplerate\n ? track.samplerate\n : inputTimeScale;\n const scaleFactor: number = inputTimeScale / mp4timeScale;\n const mp4SampleDuration: number = this.getSamplesPerFrame(track);\n const inputSampleDuration: number = mp4SampleDuration * scaleFactor;\n const initPTS = this._initPTS as RationalTimestamp;\n const rawMPEG: boolean =\n track.segmentCodec === 'mp3' && this.typeSupported.mpeg;\n const outputSamples: Array<Mp4Sample> = [];\n const alignedWithVideo = videoTimeOffset !== undefined;\n\n let inputSamples: Array<AudioSample> = track.samples;\n let offset: number = rawMPEG ? 0 : 8;\n let nextAudioPts: number = this.nextAudioPts || -1;\n\n // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n const timeOffsetMpegTS = timeOffset * inputTimeScale;\n const initTime = (initPTS.baseTime * inputTimeScale) / initPTS.timescale;\n this.isAudioContiguous = contiguous =\n contiguous ||\n ((inputSamples.length &&\n nextAudioPts > 0 &&\n ((accurateTimeOffset &&\n Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000) ||\n Math.abs(\n normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) -\n nextAudioPts,\n ) <\n 20 * inputSampleDuration)) as boolean);\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);\n });\n\n if (!contiguous || nextAudioPts < 0) {\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter((sample) => sample.pts >= 0);\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (!inputSamples.length) {\n return;\n }\n\n if (videoTimeOffset === 0) {\n // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence\n nextAudioPts = 0;\n } else if (accurateTimeOffset && !alignedWithVideo) {\n // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS\n nextAudioPts = Math.max(0, timeOffsetMpegTS);\n } else {\n // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n }\n }\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n if (track.segmentCodec === 'aac') {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {\n // First, let's see how far off this frame is from where we expect it to be\n const sample = inputSamples[i];\n const pts = sample.pts;\n const delta = pts - nextPts;\n const duration = Math.abs((1000 * delta) / inputTimeScale);\n\n // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync\n if (\n delta <= -maxAudioFramesDrift * inputSampleDuration &&\n alignedWithVideo\n ) {\n if (i === 0) {\n logger.warn(\n `Audio frame @ ${(pts / inputTimeScale).toFixed(\n 3,\n )}s overlaps nextAudioPts by ${Math.round(\n (1000 * delta) / inputTimeScale,\n )} ms.`,\n );\n this.nextAudioPts = nextAudioPts = nextPts = pts;\n }\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n // 4: remuxing with video (videoTimeOffset !== undefined)\n else if (\n delta >= maxAudioFramesDrift * inputSampleDuration &&\n duration < MAX_SILENT_FRAME_DURATION &&\n alignedWithVideo\n ) {\n let missing = Math.round(delta / inputSampleDuration);\n // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from\n // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.\n nextPts = pts - missing * inputSampleDuration;\n if (nextPts < 0) {\n missing--;\n nextPts += inputSampleDuration;\n }\n if (i === 0) {\n this.nextAudioPts = nextAudioPts = nextPts;\n }\n logger.warn(\n `[mp4-remuxer]: Injecting ${missing} audio frame @ ${(\n nextPts / inputTimeScale\n ).toFixed(3)}s due to ${Math.round(\n (1000 * delta) / inputTimeScale,\n )} ms gap.`,\n );\n for (let j = 0; j < missing; j++) {\n const newStamp = Math.max(nextPts as number, 0);\n let fillFrame = AAC.getSilentFrame(\n track.manifestCodec || track.codec,\n track.channelCount,\n );\n if (!fillFrame) {\n logger.log(\n '[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.',\n );\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, {\n unit: fillFrame,\n pts: newStamp,\n });\n nextPts += inputSampleDuration;\n i++;\n }\n }\n sample.pts = nextPts;\n nextPts += inputSampleDuration;\n }\n }\n let firstPTS: number | null = null;\n let lastPTS: number | null = null;\n let mdat: any;\n let mdatSize: number = 0;\n let sampleLength: number = inputSamples.length;\n while (sampleLength--) {\n mdatSize += inputSamples[sampleLength].unit.byteLength;\n }\n for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) {\n const audioSample = inputSamples[j];\n const unit = audioSample.unit;\n let pts = audioSample.pts;\n if (lastPTS !== null) {\n // If we have more than one sample, set the duration of the sample to the \"real\" duration; the PTS diff with\n // the previous sample\n const prevSample = outputSamples[j - 1];\n prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n if (contiguous && track.segmentCodec === 'aac') {\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n // remember first PTS of our audioSamples\n firstPTS = pts;\n if (mdatSize > 0) {\n /* concatenate the audio data and construct the mdat in place\n (need 8 more bytes to fill length and mdat type) */\n mdatSize += offset;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating audio mdat ${mdatSize}`,\n });\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n }\n mdat.set(unit, offset);\n const unitLen = unit.byteLength;\n offset += unitLen;\n // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG\n // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration\n // becomes the PTS diff with the previous sample\n outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));\n lastPTS = pts;\n }\n\n // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones\n const nbSamples = outputSamples.length;\n if (!nbSamples) {\n return;\n }\n\n // The next audio sample PTS should be equal to last sample PTS + duration\n const lastSample = outputSamples[outputSamples.length - 1];\n this.nextAudioPts = nextAudioPts =\n lastPTS! + scaleFactor * lastSample.duration;\n\n // Set the track samples from inputSamples to outputSamples before remuxing\n const moof = rawMPEG\n ? new Uint8Array(0)\n : MP4.moof(\n track.sequenceNumber++,\n firstPTS! / scaleFactor,\n Object.assign({}, track, { samples: outputSamples }),\n );\n\n // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared\n track.samples = [];\n const start = firstPTS! / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const type: SourceBufferName = 'audio';\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type,\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples,\n };\n\n this.isAudioContiguous = true;\n return audioData;\n }\n\n remuxEmptyAudio(\n track: DemuxedAudioTrack,\n timeOffset: number,\n contiguous: boolean,\n videoData: Fragment,\n ): RemuxedTrack | undefined {\n const inputTimeScale: number = track.inputTimeScale;\n const mp4timeScale: number = track.samplerate\n ? track.samplerate\n : inputTimeScale;\n const scaleFactor: number = inputTimeScale / mp4timeScale;\n const nextAudioPts: number | null = this.nextAudioPts;\n // sync with video's timestamp\n const initDTS = this._initDTS as RationalTimestamp;\n const init90kHz = (initDTS.baseTime * 90000) / initDTS.timescale;\n const startDTS: number =\n (nextAudioPts !== null\n ? nextAudioPts\n : videoData.startDTS * inputTimeScale) + init90kHz;\n const endDTS: number = videoData.endDTS * inputTimeScale + init90kHz;\n // one sample's duration value\n const frameDuration: number = scaleFactor * AAC_SAMPLES_PER_FRAME;\n // samples count of this segment's duration\n const nbSamples: number = Math.ceil((endDTS - startDTS) / frameDuration);\n // silent frame\n const silentFrame: Uint8Array | undefined = AAC.getSilentFrame(\n track.manifestCodec || track.codec,\n track.channelCount,\n );\n\n logger.warn('[mp4-remuxer]: remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace(\n '[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec',\n );\n return;\n }\n\n const samples: Array<any> = [];\n for (let i = 0; i < nbSamples; i++) {\n const stamp = startDTS + i * frameDuration;\n samples.push({ unit: silentFrame, pts: stamp, dts: stamp });\n }\n track.samples = samples;\n\n return this.remuxAudio(track, timeOffset, contiguous, false);\n }\n}\n\nexport function normalizePts(value: number, reference: number | null): number {\n let offset;\n if (reference === null) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n}\n\nfunction findKeyframeIndex(samples: Array<VideoSample>): number {\n for (let i = 0; i < samples.length; i++) {\n if (samples[i].key) {\n return i;\n }\n }\n return -1;\n}\n\nexport function flushTextTrackMetadataCueSamples(\n track: DemuxedMetadataTrack,\n timeOffset: number,\n initPTS: RationalTimestamp,\n initDTS: RationalTimestamp,\n): RemuxedMetadata | undefined {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts =\n normalizePts(\n sample.pts - (initPTS.baseTime * inputTimeScale) / initPTS.timescale,\n timeOffset * inputTimeScale,\n ) / inputTimeScale;\n sample.dts =\n normalizePts(\n sample.dts - (initDTS.baseTime * inputTimeScale) / initDTS.timescale,\n timeOffset * inputTimeScale,\n ) / inputTimeScale;\n }\n const samples = track.samples;\n track.samples = [];\n return {\n samples,\n };\n}\n\nexport function flushTextTrackUserdataCueSamples(\n track: DemuxedUserdataTrack,\n timeOffset: number,\n initPTS: RationalTimestamp,\n): RemuxedUserdata | undefined {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts =\n normalizePts(\n sample.pts - (initPTS.baseTime * inputTimeScale) / initPTS.timescale,\n timeOffset * inputTimeScale,\n ) / inputTimeScale;\n }\n track.samples.sort((a, b) => a.pts - b.pts);\n const samples = track.samples;\n track.samples = [];\n return {\n samples,\n };\n}\n\ntype Mp4SampleFlags = {\n isLeading: 0;\n isDependedOn: 0;\n hasRedundancy: 0;\n degradPrio: 0;\n dependsOn: 1 | 2;\n isNonSync: 0 | 1;\n};\n\nclass Mp4Sample {\n public size: number;\n public duration: number;\n public cts: number;\n public flags: Mp4SampleFlags;\n\n constructor(\n isKeyframe: boolean,\n duration: number,\n size: number,\n cts: number,\n ) {\n this.duration = duration;\n this.size = size;\n this.cts = cts;\n this.flags = {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: isKeyframe ? 2 : 1,\n isNonSync: isKeyframe ? 0 : 1,\n };\n }\n}\n","import {\n flushTextTrackMetadataCueSamples,\n flushTextTrackUserdataCueSamples,\n} from './mp4-remuxer';\nimport {\n InitData,\n InitDataTrack,\n patchEncyptionData,\n} from '../utils/mp4-tools';\nimport {\n getDuration,\n getStartDTS,\n offsetStartDTS,\n parseInitSegment,\n} from '../utils/mp4-tools';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport { logger } from '../utils/logger';\nimport { getCodecCompatibleName } from '../utils/codecs';\nimport type { TrackSet } from '../types/track';\nimport type {\n InitSegmentData,\n RemuxedTrack,\n Remuxer,\n RemuxerResult,\n} from '../types/remuxer';\nimport type {\n DemuxedAudioTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n PassthroughTrack,\n} from '../types/demuxer';\nimport type { DecryptData } from '../loader/level-key';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nclass PassThroughRemuxer implements Remuxer {\n private emitInitSegment: boolean = false;\n private audioCodec?: string;\n private videoCodec?: string;\n private initData?: InitData;\n private initPTS: RationalTimestamp | null = null;\n private initTracks?: TrackSet;\n private lastEndTime: number | null = null;\n\n public destroy() {}\n\n public resetTimeStamp(defaultInitPTS: RationalTimestamp | null) {\n this.initPTS = defaultInitPTS;\n this.lastEndTime = null;\n }\n\n public resetNextTimestamp() {\n this.lastEndTime = null;\n }\n\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n decryptdata: DecryptData | null,\n ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));\n this.emitInitSegment = true;\n }\n\n private generateInitSegment(initSegment: Uint8Array | undefined): void {\n let { audioCodec, videoCodec } = this;\n if (!initSegment?.byteLength) {\n this.initTracks = undefined;\n this.initData = undefined;\n return;\n }\n const initData = (this.initData = parseInitSegment(initSegment));\n\n // Get codec from initSegment or fallback to default\n if (initData.audio) {\n audioCodec = getParsedTrackCodec(\n initData.audio,\n ElementaryStreamTypes.AUDIO,\n );\n }\n\n if (initData.video) {\n videoCodec = getParsedTrackCodec(\n initData.video,\n ElementaryStreamTypes.VIDEO,\n );\n }\n\n const tracks: TrackSet = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = {\n container: 'video/mp4',\n codec: audioCodec + ',' + videoCodec,\n initSegment,\n id: 'main',\n };\n } else if (initData.audio) {\n tracks.audio = {\n container: 'audio/mp4',\n codec: audioCodec,\n initSegment,\n id: 'audio',\n };\n } else if (initData.video) {\n tracks.video = {\n container: 'video/mp4',\n codec: videoCodec,\n initSegment,\n id: 'main',\n };\n } else {\n logger.warn(\n '[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.',\n );\n }\n this.initTracks = tracks;\n }\n\n public remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: PassthroughTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n ): RemuxerResult {\n let { initPTS, lastEndTime } = this;\n const result: RemuxerResult = {\n audio: undefined,\n video: undefined,\n text: textTrack,\n id3: id3Track,\n initSegment: undefined,\n };\n\n // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the\n // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update\n // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.\n if (!Number.isFinite(lastEndTime!)) {\n lastEndTime = this.lastEndTime = timeOffset || 0;\n }\n\n // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only\n // audio or video (or both); adding it to video was an arbitrary choice.\n const data = videoTrack.samples;\n if (!data?.length) {\n return result;\n }\n\n const initSegment: InitSegmentData = {\n initPTS: undefined,\n timescale: 1,\n };\n let initData = this.initData;\n if (!initData?.length) {\n this.generateInitSegment(data);\n initData = this.initData;\n }\n if (!initData?.length) {\n // We can't remux if the initSegment could not be generated\n logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');\n return result;\n }\n if (this.emitInitSegment) {\n initSegment.tracks = this.initTracks as TrackSet;\n this.emitInitSegment = false;\n }\n\n const duration = getDuration(data, initData);\n const startDTS = getStartDTS(initData, data);\n const decodeTime = startDTS === null ? timeOffset : startDTS;\n if (\n isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) ||\n (initSegment.timescale !== initPTS.timescale && accurateTimeOffset)\n ) {\n initSegment.initPTS = decodeTime - timeOffset;\n if (initPTS && initPTS.timescale === 1) {\n logger.warn(\n `Adjusting initPTS by ${initSegment.initPTS - initPTS.baseTime}`,\n );\n }\n this.initPTS = initPTS = {\n baseTime: initSegment.initPTS,\n timescale: 1,\n };\n }\n\n const startTime = audioTrack\n ? decodeTime - initPTS.baseTime / initPTS.timescale\n : (lastEndTime as number);\n const endTime = startTime + duration;\n offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);\n\n if (duration > 0) {\n this.lastEndTime = endTime;\n } else {\n logger.warn('Duration parsed from mp4 should be greater than zero');\n this.resetNextTimestamp();\n }\n\n const hasAudio = !!initData.audio;\n const hasVideo = !!initData.video;\n\n let type: any = '';\n if (hasAudio) {\n type += 'audio';\n }\n\n if (hasVideo) {\n type += 'video';\n }\n\n const track: RemuxedTrack = {\n data1: data,\n startPTS: startTime,\n startDTS: startTime,\n endPTS: endTime,\n endDTS: endTime,\n type,\n hasAudio,\n hasVideo,\n nb: 1,\n dropped: 0,\n };\n\n result.audio = track.type === 'audio' ? track : undefined;\n result.video = track.type !== 'audio' ? track : undefined;\n result.initSegment = initSegment;\n result.id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n initPTS,\n initPTS,\n );\n\n if (textTrack.samples.length) {\n result.text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n initPTS,\n );\n }\n\n return result;\n }\n}\n\nfunction isInvalidInitPts(\n initPTS: RationalTimestamp | null,\n startDTS: number,\n timeOffset: number,\n duration: number,\n): initPTS is null {\n if (initPTS === null) {\n return true;\n }\n // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second\n const minDuration = Math.max(duration, 1);\n const startTime = startDTS - initPTS.baseTime / initPTS.timescale;\n return Math.abs(startTime - timeOffset) > minDuration;\n}\n\nfunction getParsedTrackCodec(\n track: InitDataTrack,\n type: ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO,\n): string {\n const parsedCodec = track?.codec;\n if (parsedCodec && parsedCodec.length > 4) {\n return parsedCodec;\n }\n if (type === ElementaryStreamTypes.AUDIO) {\n if (\n parsedCodec === 'ec-3' ||\n parsedCodec === 'ac-3' ||\n parsedCodec === 'alac'\n ) {\n return parsedCodec;\n }\n if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {\n // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity\n const preferManagedMediaSource = false;\n return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);\n }\n const result = 'mp4a.40.5';\n logger.info(\n `Parsed audio codec \"${parsedCodec}\" or audio object type not handled. Using \"${result}\"`,\n );\n return result;\n }\n // Provide defaults based on codec type\n // This allows for some playback of some fmp4 playlists without CODECS defined in manifest\n logger.warn(`Unhandled video codec \"${parsedCodec}\"`);\n if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {\n return 'hvc1.1.6.L120.90';\n }\n if (parsedCodec === 'av01') {\n return 'av01.0.04M.08';\n }\n return 'avc1.42e01e';\n}\nexport default PassThroughRemuxer;\n","/** returns `undefined` is `self` is missing, e.g. in node */\nexport const optionalSelf = typeof self !== 'undefined' ? self : undefined;\n","import type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from './audio/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer, { TypeSupported } from '../demux/tsdemuxer';\nimport MP3Demuxer from './audio/mp3demuxer';\nimport { AC3Demuxer } from './audio/ac3-demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\nimport { logger } from '../utils/logger';\nimport type { Demuxer, DemuxerResult, KeyData } from '../types/demuxer';\nimport type { Remuxer } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\nimport type { HlsConfig } from '../config';\nimport type { DecryptData } from '../loader/level-key';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\nimport { optionalSelf } from '../utils/global';\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = self.performance.now.bind(self.performance);\n} catch (err) {\n logger.debug('Unable to use Performance API on this environment');\n now = optionalSelf?.Date.now;\n}\n\ntype MuxConfig =\n | { demux: typeof MP4Demuxer; remux: typeof PassThroughRemuxer }\n | { demux: typeof TSDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof AC3Demuxer; remux: typeof MP4Remuxer }\n | { demux: typeof AACDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof MP3Demuxer; remux: typeof MP4Remuxer };\n\nconst muxConfig: MuxConfig[] = [\n { demux: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer },\n];\n\nif (__USE_M2TS_ADVANCED_CODECS__) {\n muxConfig.splice(2, 0, { demux: AC3Demuxer, remux: MP4Remuxer });\n}\n\nexport default class Transmuxer {\n public async: boolean = false;\n private observer: HlsEventEmitter;\n private typeSupported: TypeSupported;\n private config: HlsConfig;\n private vendor: string;\n private id: PlaylistLevelType;\n private demuxer?: Demuxer;\n private remuxer?: Remuxer;\n private decrypter?: Decrypter;\n private probe!: Function;\n private decryptionPromise: Promise<TransmuxerResult> | null = null;\n private transmuxConfig!: TransmuxConfig;\n private currentTransmuxState!: TransmuxState;\n\n constructor(\n observer: HlsEventEmitter,\n typeSupported: TypeSupported,\n config: HlsConfig,\n vendor: string,\n id: PlaylistLevelType,\n ) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n this.id = id;\n }\n\n configure(transmuxConfig: TransmuxConfig) {\n this.transmuxConfig = transmuxConfig;\n if (this.decrypter) {\n this.decrypter.reset();\n }\n }\n\n push(\n data: ArrayBuffer,\n decryptdata: DecryptData | null,\n chunkMeta: ChunkMetadata,\n state?: TransmuxState,\n ): TransmuxerResult | Promise<TransmuxerResult> {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n\n let uintData: Uint8Array = new Uint8Array(data);\n const { currentTransmuxState, transmuxConfig } = this;\n if (state) {\n this.currentTransmuxState = state;\n }\n\n const {\n contiguous,\n discontinuity,\n trackSwitch,\n accurateTimeOffset,\n timeOffset,\n initSegmentChange,\n } = state || currentTransmuxState;\n const {\n audioCodec,\n videoCodec,\n defaultInitPts,\n duration,\n initSegmentData,\n } = transmuxConfig;\n\n const keyData = getEncryptionType(uintData, decryptdata);\n if (keyData && keyData.method === 'AES-128') {\n const decrypter = this.getDecrypter();\n // Software decryption is synchronous; webCrypto is not\n if (decrypter.isSync()) {\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n let decryptedData = decrypter.softwareDecrypt(\n uintData,\n keyData.key.buffer,\n keyData.iv.buffer,\n );\n // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress\n const loadingParts = chunkMeta.part > -1;\n if (loadingParts) {\n decryptedData = decrypter.flush();\n }\n if (!decryptedData) {\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n uintData = new Uint8Array(decryptedData);\n } else {\n this.decryptionPromise = decrypter\n .webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer)\n .then((decryptedData): TransmuxerResult => {\n // Calling push here is important; if flush() is called while this is still resolving, this ensures that\n // the decrypted data has been transmuxed\n const result = this.push(\n decryptedData,\n null,\n chunkMeta,\n ) as TransmuxerResult;\n this.decryptionPromise = null;\n return result;\n });\n return this.decryptionPromise!;\n }\n }\n\n const resetMuxers = this.needsProbing(discontinuity, trackSwitch);\n if (resetMuxers) {\n const error = this.configureTransmuxer(uintData);\n if (error) {\n logger.warn(`[transmuxer] ${error.message}`);\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n reason: error.message,\n });\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n }\n\n if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {\n this.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n duration,\n decryptdata,\n );\n }\n\n if (discontinuity || initSegmentChange || resetMuxers) {\n this.resetInitialTimestamp(defaultInitPts);\n }\n\n if (!contiguous) {\n this.resetContiguity();\n }\n\n const result = this.transmux(\n uintData,\n keyData,\n timeOffset,\n accurateTimeOffset,\n chunkMeta,\n );\n const currentState = this.currentTransmuxState;\n\n currentState.contiguous = true;\n currentState.discontinuity = false;\n currentState.trackSwitch = false;\n\n stats.executeEnd = now();\n return result;\n }\n\n // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)\n flush(\n chunkMeta: ChunkMetadata,\n ): TransmuxerResult[] | Promise<TransmuxerResult[]> {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n\n const { decrypter, currentTransmuxState, decryptionPromise } = this;\n\n if (decryptionPromise) {\n // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore\n // only flushing is required for async decryption\n return decryptionPromise.then(() => {\n return this.flush(chunkMeta);\n });\n }\n\n const transmuxResults: TransmuxerResult[] = [];\n const { timeOffset } = currentTransmuxState;\n if (decrypter) {\n // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults\n // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,\n // or for progressive downloads with small segments)\n const decryptedData = decrypter.flush();\n if (decryptedData) {\n // Push always returns a TransmuxerResult if decryptdata is null\n transmuxResults.push(\n this.push(decryptedData, null, chunkMeta) as TransmuxerResult,\n );\n }\n }\n\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n // If probing failed, then Hls.js has been given content its not able to handle\n stats.executeEnd = now();\n return [emptyResult(chunkMeta)];\n }\n\n const demuxResultOrPromise = demuxer.flush(timeOffset);\n if (isPromise(demuxResultOrPromise)) {\n // Decrypt final SAMPLE-AES samples\n return demuxResultOrPromise.then((demuxResult) => {\n this.flushRemux(transmuxResults, demuxResult, chunkMeta);\n return transmuxResults;\n });\n }\n\n this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);\n return transmuxResults;\n }\n\n private flushRemux(\n transmuxResults: TransmuxerResult[],\n demuxResult: DemuxerResult,\n chunkMeta: ChunkMetadata,\n ) {\n const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult;\n const { accurateTimeOffset, timeOffset } = this.currentTransmuxState;\n logger.log(\n `[transmuxer.ts]: Flushed fragment ${chunkMeta.sn}${\n chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : ''\n } of level ${chunkMeta.level}`,\n );\n const remuxResult = this.remuxer!.remux(\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n timeOffset,\n accurateTimeOffset,\n true,\n this.id,\n );\n transmuxResults.push({\n remuxResult,\n chunkMeta,\n });\n\n chunkMeta.transmuxing.executeEnd = now();\n }\n\n resetInitialTimestamp(defaultInitPts: RationalTimestamp | null) {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetTimeStamp(defaultInitPts);\n remuxer.resetTimeStamp(defaultInitPts);\n }\n\n resetContiguity() {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetContiguity();\n remuxer.resetNextTimestamp();\n }\n\n resetInitSegment(\n initSegmentData: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n decryptdata: DecryptData | null,\n ) {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n trackDuration,\n );\n remuxer.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n decryptdata,\n );\n }\n\n destroy(): void {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = undefined;\n }\n if (this.remuxer) {\n this.remuxer.destroy();\n this.remuxer = undefined;\n }\n }\n\n private transmux(\n data: Uint8Array,\n keyData: KeyData | null,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n ): TransmuxerResult | Promise<TransmuxerResult> {\n let result: TransmuxerResult | Promise<TransmuxerResult>;\n if (keyData && keyData.method === 'SAMPLE-AES') {\n result = this.transmuxSampleAes(\n data,\n keyData,\n timeOffset,\n accurateTimeOffset,\n chunkMeta,\n );\n } else {\n result = this.transmuxUnencrypted(\n data,\n timeOffset,\n accurateTimeOffset,\n chunkMeta,\n );\n }\n return result;\n }\n\n private transmuxUnencrypted(\n data: Uint8Array,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n ): TransmuxerResult {\n const { audioTrack, videoTrack, id3Track, textTrack } = (\n this.demuxer as Demuxer\n ).demux(data, timeOffset, false, !this.config.progressive);\n const remuxResult = this.remuxer!.remux(\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n timeOffset,\n accurateTimeOffset,\n false,\n this.id,\n );\n return {\n remuxResult,\n chunkMeta,\n };\n }\n\n private transmuxSampleAes(\n data: Uint8Array,\n decryptData: KeyData,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n ): Promise<TransmuxerResult> {\n return (this.demuxer as Demuxer)\n .demuxSampleAes(data, decryptData, timeOffset)\n .then((demuxResult) => {\n const remuxResult = this.remuxer!.remux(\n demuxResult.audioTrack,\n demuxResult.videoTrack,\n demuxResult.id3Track,\n demuxResult.textTrack,\n timeOffset,\n accurateTimeOffset,\n false,\n this.id,\n );\n return {\n remuxResult,\n chunkMeta,\n };\n });\n }\n\n private configureTransmuxer(data: Uint8Array): void | Error {\n const { config, observer, typeSupported, vendor } = this;\n // probe for content type\n let mux;\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n if (muxConfig[i].demux?.probe(data)) {\n mux = muxConfig[i];\n break;\n }\n }\n if (!mux) {\n return new Error('Failed to find demuxer by probing fragment data');\n }\n // so let's check that current remuxer and demuxer are still valid\n const demuxer = this.demuxer;\n const remuxer = this.remuxer;\n const Remuxer: MuxConfig['remux'] = mux.remux;\n const Demuxer: MuxConfig['demux'] = mux.demux;\n if (!remuxer || !(remuxer instanceof Remuxer)) {\n this.remuxer = new Remuxer(observer, config, typeSupported, vendor);\n }\n if (!demuxer || !(demuxer instanceof Demuxer)) {\n this.demuxer = new Demuxer(observer, config, typeSupported);\n this.probe = Demuxer.probe;\n }\n }\n\n private needsProbing(discontinuity: boolean, trackSwitch: boolean): boolean {\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;\n }\n\n private getDecrypter(): Decrypter {\n let decrypter = this.decrypter;\n if (!decrypter) {\n decrypter = this.decrypter = new Decrypter(this.config);\n }\n return decrypter;\n }\n}\n\nfunction getEncryptionType(\n data: Uint8Array,\n decryptData: DecryptData | null,\n): KeyData | null {\n let encryptionType: KeyData | null = null;\n if (\n data.byteLength > 0 &&\n decryptData?.key != null &&\n decryptData.iv !== null &&\n decryptData.method != null\n ) {\n encryptionType = decryptData as KeyData;\n }\n return encryptionType;\n}\n\nconst emptyResult = (chunkMeta): TransmuxerResult => ({\n remuxResult: {},\n chunkMeta,\n});\n\nexport function isPromise<T>(p: Promise<T> | any): p is Promise<T> {\n return 'then' in p && p.then instanceof Function;\n}\n\nexport class TransmuxConfig {\n public audioCodec?: string;\n public videoCodec?: string;\n public initSegmentData?: Uint8Array;\n public duration: number;\n public defaultInitPts: RationalTimestamp | null;\n\n constructor(\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n initSegmentData: Uint8Array | undefined,\n duration: number,\n defaultInitPts?: RationalTimestamp,\n ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.initSegmentData = initSegmentData;\n this.duration = duration;\n this.defaultInitPts = defaultInitPts || null;\n }\n}\n\nexport class TransmuxState {\n public discontinuity: boolean;\n public contiguous: boolean;\n public accurateTimeOffset: boolean;\n public trackSwitch: boolean;\n public timeOffset: number;\n public initSegmentChange: boolean;\n\n constructor(\n discontinuity: boolean,\n contiguous: boolean,\n accurateTimeOffset: boolean,\n trackSwitch: boolean,\n timeOffset: number,\n initSegmentChange: boolean,\n ) {\n this.discontinuity = discontinuity;\n this.contiguous = contiguous;\n this.accurateTimeOffset = accurateTimeOffset;\n this.trackSwitch = trackSwitch;\n this.timeOffset = timeOffset;\n this.initSegmentChange = initSegmentChange;\n }\n}\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import Transmuxer, { isPromise } from '../demux/transmuxer';\nimport { Events } from '../events';\nimport { ILogFunction, enableLogs, logger } from '../utils/logger';\nimport { EventEmitter } from 'eventemitter3';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport type { RemuxedTrack, RemuxerResult } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\n\nif (typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {\n startWorker(self);\n}\n\nfunction startWorker(self) {\n const observer = new EventEmitter();\n const forwardMessage = (ev, data) => {\n self.postMessage({ event: ev, data: data });\n };\n\n // forward events to main thread\n observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n observer.on(Events.ERROR, forwardMessage);\n\n // forward logger events to main thread\n const forwardWorkerLogs = () => {\n for (const logFn in logger) {\n const func: ILogFunction = (message?) => {\n forwardMessage('workerLog', {\n logType: logFn,\n message,\n });\n };\n\n logger[logFn] = func;\n }\n };\n\n self.addEventListener('message', (ev) => {\n const data = ev.data;\n switch (data.cmd) {\n case 'init': {\n const config = JSON.parse(data.config);\n self.transmuxer = new Transmuxer(\n observer,\n data.typeSupported,\n config,\n '',\n data.id,\n );\n enableLogs(config.debug, data.id);\n forwardWorkerLogs();\n forwardMessage('init', null);\n break;\n }\n case 'configure': {\n self.transmuxer.configure(data.config);\n break;\n }\n case 'demux': {\n const transmuxResult: TransmuxerResult | Promise<TransmuxerResult> =\n self.transmuxer.push(\n data.data,\n data.decryptdata,\n data.chunkMeta,\n data.state,\n );\n if (isPromise(transmuxResult)) {\n self.transmuxer.async = true;\n transmuxResult\n .then((data) => {\n emitTransmuxComplete(self, data);\n })\n .catch((error) => {\n forwardMessage(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta: data.chunkMeta,\n fatal: false,\n error,\n err: error,\n reason: `transmuxer-worker push error`,\n });\n });\n } else {\n self.transmuxer.async = false;\n emitTransmuxComplete(self, transmuxResult);\n }\n break;\n }\n case 'flush': {\n const id = data.chunkMeta;\n let transmuxResult = self.transmuxer.flush(id);\n const asyncFlush = isPromise(transmuxResult);\n if (asyncFlush || self.transmuxer.async) {\n if (!isPromise(transmuxResult)) {\n transmuxResult = Promise.resolve(transmuxResult);\n }\n transmuxResult\n .then((results: Array<TransmuxerResult>) => {\n handleFlushResult(self, results as Array<TransmuxerResult>, id);\n })\n .catch((error) => {\n forwardMessage(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta: data.chunkMeta,\n fatal: false,\n error,\n err: error,\n reason: `transmuxer-worker flush error`,\n });\n });\n } else {\n handleFlushResult(\n self,\n transmuxResult as Array<TransmuxerResult>,\n id,\n );\n }\n break;\n }\n default:\n break;\n }\n });\n}\n\nfunction emitTransmuxComplete(\n self: any,\n transmuxResult: TransmuxerResult,\n): boolean {\n if (isEmptyResult(transmuxResult.remuxResult)) {\n return false;\n }\n const transferable: Array<ArrayBuffer> = [];\n const { audio, video } = transmuxResult.remuxResult;\n if (audio) {\n addToTransferable(transferable, audio);\n }\n if (video) {\n addToTransferable(transferable, video);\n }\n self.postMessage(\n { event: 'transmuxComplete', data: transmuxResult },\n transferable,\n );\n return true;\n}\n\n// Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)\n// in order to minimize message passing overhead\nfunction addToTransferable(\n transferable: Array<ArrayBuffer>,\n track: RemuxedTrack,\n) {\n if (track.data1) {\n transferable.push(track.data1.buffer);\n }\n if (track.data2) {\n transferable.push(track.data2.buffer);\n }\n}\n\nfunction handleFlushResult(\n self: any,\n results: Array<TransmuxerResult>,\n chunkMeta: ChunkMetadata,\n) {\n const parsed = results.reduce(\n (parsed, result) => emitTransmuxComplete(self, result) || parsed,\n false,\n );\n if (!parsed) {\n // Emit at least one \"transmuxComplete\" message even if media is not found to update stream-controller state to PARSING\n self.postMessage({ event: 'transmuxComplete', data: results[0] });\n }\n self.postMessage({ event: 'flush', data: chunkMeta });\n}\n\nfunction isEmptyResult(remuxResult: RemuxerResult) {\n return (\n !remuxResult.audio &&\n !remuxResult.video &&\n !remuxResult.text &&\n !remuxResult.id3 &&\n !remuxResult.initSegment\n );\n}\n","import {\n WorkerContext,\n hasUMDWorker,\n injectWorker,\n loadWorker,\n} from './inject-worker';\nimport { Events } from '../events';\nimport Transmuxer, {\n TransmuxConfig,\n TransmuxState,\n isPromise,\n} from '../demux/transmuxer';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { EventEmitter } from 'eventemitter3';\nimport { Fragment, Part } from '../loader/fragment';\nimport type { ChunkMetadata, TransmuxerResult } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { HlsEventEmitter, HlsListeners } from '../events';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { TypeSupported } from './tsdemuxer';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nexport default class TransmuxerInterface {\n public error: Error | null = null;\n private hls: Hls;\n private id: PlaylistLevelType;\n private observer: HlsEventEmitter;\n private frag: Fragment | null = null;\n private part: Part | null = null;\n private useWorker: boolean;\n private workerContext: WorkerContext | null = null;\n private onwmsg?: (\n event: MessageEvent<{ event: string; data?: any } | null>,\n ) => void;\n private transmuxer: Transmuxer | null = null;\n private onTransmuxComplete: (transmuxResult: TransmuxerResult) => void;\n private onFlush: (chunkMeta: ChunkMetadata) => void;\n\n constructor(\n hls: Hls,\n id: PlaylistLevelType,\n onTransmuxComplete: (transmuxResult: TransmuxerResult) => void,\n onFlush: (chunkMeta: ChunkMetadata) => void,\n ) {\n const config = hls.config;\n this.hls = hls;\n this.id = id;\n this.useWorker = !!config.enableWorker;\n this.onTransmuxComplete = onTransmuxComplete;\n this.onFlush = onFlush;\n\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n if (ev === Events.ERROR) {\n this.error = data.error;\n }\n this.hls.trigger(ev, data);\n };\n\n // forward events to main thread\n this.observer = new EventEmitter() as HlsEventEmitter;\n this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n this.observer.on(Events.ERROR, forwardMessage);\n\n const MediaSource = getMediaSource(config.preferManagedMediaSource) || {\n isTypeSupported: () => false,\n };\n const m2tsTypeSupported: TypeSupported = {\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n ac3: __USE_M2TS_ADVANCED_CODECS__\n ? MediaSource.isTypeSupported('audio/mp4; codecs=\"ac-3\"')\n : false,\n };\n\n if (this.useWorker && typeof Worker !== 'undefined') {\n const canCreateWorker = config.workerPath || hasUMDWorker();\n if (canCreateWorker) {\n try {\n if (config.workerPath) {\n logger.log(`loading Web Worker ${config.workerPath} for \"${id}\"`);\n this.workerContext = loadWorker(config.workerPath);\n } else {\n logger.log(`injecting Web Worker for \"${id}\"`);\n this.workerContext = injectWorker();\n }\n this.onwmsg = (event) => this.onWorkerMessage(event);\n const { worker } = this.workerContext;\n worker.addEventListener('message', this.onwmsg);\n worker.onerror = (event) => {\n const error = new Error(\n `${event.message} (${event.filename}:${event.lineno})`,\n );\n config.enableWorker = false;\n logger.warn(`Error in \"${id}\" Web Worker, fallback to inline`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal: false,\n event: 'demuxerWorker',\n error,\n });\n };\n worker.postMessage({\n cmd: 'init',\n typeSupported: m2tsTypeSupported,\n vendor: '',\n id: id,\n config: JSON.stringify(config),\n });\n } catch (err) {\n logger.warn(\n `Error setting up \"${id}\" Web Worker, fallback to inline`,\n err,\n );\n this.resetWorker();\n this.error = null;\n this.transmuxer = new Transmuxer(\n this.observer,\n m2tsTypeSupported,\n config,\n '',\n id,\n );\n }\n return;\n }\n }\n\n this.transmuxer = new Transmuxer(\n this.observer,\n m2tsTypeSupported,\n config,\n '',\n id,\n );\n }\n\n resetWorker() {\n if (this.workerContext) {\n const { worker, objectURL } = this.workerContext;\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n worker.removeEventListener('message', this.onwmsg as any);\n worker.onerror = null;\n worker.terminate();\n this.workerContext = null;\n }\n }\n\n destroy() {\n if (this.workerContext) {\n this.resetWorker();\n this.onwmsg = undefined;\n } else {\n const transmuxer = this.transmuxer;\n if (transmuxer) {\n transmuxer.destroy();\n this.transmuxer = null;\n }\n }\n const observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n }\n this.frag = null;\n // @ts-ignore\n this.observer = null;\n // @ts-ignore\n this.hls = null;\n }\n\n push(\n data: ArrayBuffer,\n initSegmentData: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n frag: Fragment,\n part: Part | null,\n duration: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n defaultInitPTS?: RationalTimestamp,\n ) {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer } = this;\n const timeOffset = part ? part.start : frag.start;\n // TODO: push \"clear-lead\" decrypt data for unencrypted fragments in streams with encrypted ones\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n\n const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);\n const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);\n const snDiff = lastFrag ? chunkMeta.sn - (lastFrag.sn as number) : -1;\n const partDiff = this.part ? chunkMeta.part - this.part.index : -1;\n const progressive =\n snDiff === 0 &&\n chunkMeta.id > 1 &&\n chunkMeta.id === lastFrag?.stats.chunkCount;\n const contiguous =\n !trackSwitch &&\n (snDiff === 1 ||\n (snDiff === 0 && (partDiff === 1 || (progressive && partDiff <= 0))));\n const now = self.performance.now();\n\n if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {\n frag.stats.parsing.start = now;\n }\n if (part && (partDiff || !contiguous)) {\n part.stats.parsing.start = now;\n }\n const initSegmentChange = !(\n lastFrag && frag.initSegment?.url === lastFrag.initSegment?.url\n );\n const state = new TransmuxState(\n discontinuity,\n contiguous,\n accurateTimeOffset,\n trackSwitch,\n timeOffset,\n initSegmentChange,\n );\n if (!contiguous || discontinuity || initSegmentChange) {\n logger.log(`[transmuxer-interface, ${frag.type}]: Starting new transmux session for sn: ${chunkMeta.sn} p: ${chunkMeta.part} level: ${chunkMeta.level} id: ${chunkMeta.id}\n discontinuity: ${discontinuity}\n trackSwitch: ${trackSwitch}\n contiguous: ${contiguous}\n accurateTimeOffset: ${accurateTimeOffset}\n timeOffset: ${timeOffset}\n initSegmentChange: ${initSegmentChange}`);\n const config = new TransmuxConfig(\n audioCodec,\n videoCodec,\n initSegmentData,\n duration,\n defaultInitPTS,\n );\n this.configureTransmuxer(config);\n }\n\n this.frag = frag;\n this.part = part;\n\n // Frags with sn of 'initSegment' are not transmuxed\n if (this.workerContext) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n this.workerContext.worker.postMessage(\n {\n cmd: 'demux',\n data,\n decryptdata,\n chunkMeta,\n state,\n },\n data instanceof ArrayBuffer ? [data] : [],\n );\n } else if (transmuxer) {\n const transmuxResult = transmuxer.push(\n data,\n decryptdata,\n chunkMeta,\n state,\n );\n if (isPromise(transmuxResult)) {\n transmuxer.async = true;\n transmuxResult\n .then((data) => {\n this.handleTransmuxComplete(data);\n })\n .catch((error) => {\n this.transmuxerError(\n error,\n chunkMeta,\n 'transmuxer-interface push error',\n );\n });\n } else {\n transmuxer.async = false;\n this.handleTransmuxComplete(transmuxResult as TransmuxerResult);\n }\n }\n }\n\n flush(chunkMeta: ChunkMetadata) {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer } = this;\n if (this.workerContext) {\n 1;\n this.workerContext.worker.postMessage({\n cmd: 'flush',\n chunkMeta,\n });\n } else if (transmuxer) {\n let transmuxResult = transmuxer.flush(chunkMeta);\n const asyncFlush = isPromise(transmuxResult);\n if (asyncFlush || transmuxer.async) {\n if (!isPromise(transmuxResult)) {\n transmuxResult = Promise.resolve(transmuxResult);\n }\n transmuxResult\n .then((data) => {\n this.handleFlushResult(data, chunkMeta);\n })\n .catch((error) => {\n this.transmuxerError(\n error,\n chunkMeta,\n 'transmuxer-interface flush error',\n );\n });\n } else {\n this.handleFlushResult(\n transmuxResult as Array<TransmuxerResult>,\n chunkMeta,\n );\n }\n }\n }\n\n private transmuxerError(\n error: Error,\n chunkMeta: ChunkMetadata,\n reason: string,\n ) {\n if (!this.hls) {\n return;\n }\n this.error = error;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta,\n frag: this.frag || undefined,\n fatal: false,\n error,\n err: error,\n reason,\n });\n }\n\n private handleFlushResult(\n results: Array<TransmuxerResult>,\n chunkMeta: ChunkMetadata,\n ) {\n results.forEach((result) => {\n this.handleTransmuxComplete(result);\n });\n this.onFlush(chunkMeta);\n }\n\n private onWorkerMessage(\n event: MessageEvent<{ event: string; data?: any } | null>,\n ) {\n const data = event.data;\n if (!data?.event) {\n logger.warn(\n `worker message received with no ${data ? 'event name' : 'data'}`,\n );\n return;\n }\n const hls = this.hls;\n if (!this.hls) {\n return;\n }\n switch (data.event) {\n case 'init': {\n const objectURL = this.workerContext?.objectURL;\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n break;\n }\n\n case 'transmuxComplete': {\n this.handleTransmuxComplete(data.data);\n break;\n }\n\n case 'flush': {\n this.onFlush(data.data);\n break;\n }\n\n // pass logs from the worker thread to the main logger\n case 'workerLog':\n if (logger[data.data.logType]) {\n logger[data.data.logType](data.data.message);\n }\n break;\n\n default: {\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event as keyof HlsListeners, data.data);\n break;\n }\n }\n }\n\n private configureTransmuxer(config: TransmuxConfig) {\n const { transmuxer } = this;\n if (this.workerContext) {\n this.workerContext.worker.postMessage({\n cmd: 'configure',\n config,\n });\n } else if (transmuxer) {\n transmuxer.configure(config);\n }\n }\n\n private handleTransmuxComplete(result: TransmuxerResult) {\n result.chunkMeta.transmuxing.end = self.performance.now();\n this.onTransmuxComplete(result);\n }\n}\n","// ensure the worker ends up in the bundle\n// If the worker should not be included this gets aliased to empty.js\nimport './transmuxer-worker';\n\nexport function hasUMDWorker(): boolean {\n return typeof __HLS_WORKER_BUNDLE__ === 'function';\n}\n\nexport type WorkerContext = {\n worker: Worker;\n objectURL?: string;\n scriptURL?: string;\n};\n\nexport function injectWorker(): WorkerContext {\n const blob = new self.Blob(\n [\n `var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`,\n ],\n {\n type: 'text/javascript',\n },\n );\n const objectURL = self.URL.createObjectURL(blob);\n const worker = new self.Worker(objectURL);\n\n return {\n worker,\n objectURL,\n };\n}\n\nexport function loadWorker(path: string): WorkerContext {\n const scriptURL = new self.URL(path, self.location.href).href;\n const worker = new self.Worker(scriptURL);\n\n return {\n worker,\n scriptURL,\n };\n}\n","import type { BufferInfo } from '../utils/buffer-helper';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { FragmentTracker } from './fragment-tracker';\n\nexport const STALL_MINIMUM_DURATION_MS = 250;\nexport const MAX_START_GAP_JUMP = 2.0;\nexport const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\nexport const SKIP_BUFFER_RANGE_START = 0.05;\n\nexport default class GapController {\n private config: HlsConfig;\n private media: HTMLMediaElement | null = null;\n private fragmentTracker: FragmentTracker;\n private hls: Hls;\n private nudgeRetry: number = 0;\n private stallReported: boolean = false;\n private stalled: number | null = null;\n private moved: boolean = false;\n private seeking: boolean = false;\n\n constructor(config, media, fragmentTracker, hls) {\n this.config = config;\n this.media = media;\n this.fragmentTracker = fragmentTracker;\n this.hls = hls;\n }\n\n public destroy() {\n this.media = null;\n // @ts-ignore\n this.hls = this.fragmentTracker = null;\n }\n\n /**\n * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n *\n * @param lastCurrentTime - Previously read playhead position\n */\n public poll(lastCurrentTime: number, activeFrag: Fragment | null) {\n const { config, media, stalled } = this;\n if (media === null) {\n return;\n }\n const { currentTime, seeking } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n this.moved = true;\n if (!seeking) {\n this.nudgeRetry = 0;\n }\n if (stalled !== null) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n logger.warn(\n `playback not stuck anymore @${currentTime}, after ${Math.round(\n stalledDuration,\n )}ms`,\n );\n this.stallReported = false;\n }\n this.stalled = null;\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n this.stalled = null;\n return;\n }\n\n // The playhead should not be moving\n if (\n (media.paused && !seeking) ||\n media.ended ||\n media.playbackRate === 0 ||\n !BufferHelper.getBuffered(media).length\n ) {\n this.nudgeRetry = 0;\n return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const nextStart = bufferInfo.nextStart || 0;\n\n if (seeking) {\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferGap =\n !nextStart ||\n (activeFrag && activeFrag.start <= currentTime) ||\n (nextStart - currentTime > MAX_START_GAP_JUMP &&\n !this.fragmentTracker.getPartialFragment(currentTime));\n if (hasEnoughBuffer || noBufferGap) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n if (!this.moved && this.stalled !== null) {\n // There is no playable buffer (seeked, waiting for buffer)\n const isBuffered = bufferInfo.len > 0;\n if (!isBuffered && !nextStart) {\n return;\n }\n // Jump start gaps within jump threshold\n const startJump =\n Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n\n // When joining a live stream with audio tracks, account for live playlist window sliding by allowing\n // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment\n // that begins over 1 target duration after the video start position.\n const level = this.hls.levels\n ? this.hls.levels[this.hls.currentLevel]\n : null;\n const isLive = level?.details?.live;\n const maxStartGapJump = isLive\n ? level!.details!.targetduration * 2\n : MAX_START_GAP_JUMP;\n const partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);\n if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {\n if (!media.paused) {\n this._trySkipBufferHole(partialOrGap);\n }\n return;\n }\n }\n\n // Start tracking stall time\n const tnow = self.performance.now();\n if (stalled === null) {\n this.stalled = tnow;\n return;\n }\n\n const stalledDuration = tnow - stalled;\n if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo);\n if (!this.media) {\n return;\n }\n }\n\n const bufferedWithHoles = BufferHelper.bufferInfo(\n media,\n currentTime,\n config.maxBufferHole,\n );\n this._tryFixBufferStall(bufferedWithHoles, stalledDuration);\n }\n\n /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDurationMs - The amount of time Hls.js has been stalling for.\n * @private\n */\n private _tryFixBufferStall(\n bufferInfo: BufferInfo,\n stalledDurationMs: number,\n ) {\n const { config, fragmentTracker, media } = this;\n if (media === null) {\n return;\n }\n const currentTime = media.currentTime;\n\n const partial = fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n const targetTime = this._trySkipBufferHole(partial);\n // we return here in this case, meaning\n // the branch below only executes when we haven't seeked to a new position\n if (targetTime || !this.media) {\n return;\n }\n }\n\n // if we haven't had to skip over a buffer hole of a partial fragment\n // we may just have to \"nudge\" the playlist as the browser decoding/rendering engine\n // needs to cross some sort of threshold covering all source-buffers content\n // to start playing properly.\n if (\n (bufferInfo.len > config.maxBufferHole ||\n (bufferInfo.nextStart &&\n bufferInfo.nextStart - currentTime < config.maxBufferHole)) &&\n stalledDurationMs > config.highBufferWatchdogPeriod * 1000\n ) {\n logger.warn('Trying to nudge playhead over buffer-hole');\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n private _reportStall(bufferInfo: BufferInfo) {\n const { hls, media, stallReported } = this;\n if (!stallReported && media) {\n // Report stalled error once\n this.stallReported = true;\n const error = new Error(\n `Playback stalling at @${\n media.currentTime\n } due to low buffer (${JSON.stringify(bufferInfo)})`,\n );\n logger.warn(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n error,\n buffer: bufferInfo.len,\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n private _trySkipBufferHole(partial: Fragment | null): number {\n const { config, hls, media } = this;\n if (media === null) {\n return 0;\n }\n\n // Check if currentTime is between unbuffered regions of partial fragments\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const startTime =\n currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;\n if (startTime) {\n const bufferStarved = bufferInfo.len <= config.maxBufferHole;\n const waiting =\n bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;\n const gapLength = startTime - currentTime;\n if (gapLength > 0 && (bufferStarved || waiting)) {\n // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial\n if (gapLength > config.maxBufferHole) {\n const { fragmentTracker } = this;\n let startGap = false;\n if (currentTime === 0) {\n const startFrag = fragmentTracker.getAppendedFrag(\n 0,\n PlaylistLevelType.MAIN,\n );\n if (startFrag && startTime < startFrag.end) {\n startGap = true;\n }\n }\n if (!startGap) {\n const startProvisioned =\n partial ||\n fragmentTracker.getAppendedFrag(\n currentTime,\n PlaylistLevelType.MAIN,\n );\n if (startProvisioned) {\n let moreToLoad = false;\n let pos = startProvisioned.end;\n while (pos < startTime) {\n const provisioned = fragmentTracker.getPartialFragment(pos);\n if (provisioned) {\n pos += provisioned.duration;\n } else {\n moreToLoad = true;\n break;\n }\n }\n if (moreToLoad) {\n return 0;\n }\n }\n }\n }\n const targetTime = Math.max(\n startTime + SKIP_BUFFER_RANGE_START,\n currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS,\n );\n logger.warn(\n `skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`,\n );\n this.moved = true;\n this.stalled = null;\n media.currentTime = targetTime;\n if (partial && !partial.gap) {\n const error = new Error(\n `fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`,\n );\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n error,\n reason: error.message,\n frag: partial,\n });\n }\n return targetTime;\n }\n }\n return 0;\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n private _tryNudgeBuffer() {\n const { config, hls, media, nudgeRetry } = this;\n if (media === null) {\n return;\n }\n const currentTime = media.currentTime;\n this.nudgeRetry++;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n const error = new Error(\n `Nudging 'currentTime' from ${currentTime} to ${targetTime}`,\n );\n logger.warn(error.message);\n media.currentTime = targetTime;\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n error,\n fatal: false,\n });\n } else {\n const error = new Error(\n `Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`,\n );\n logger.error(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n error,\n fatal: true,\n });\n }\n }\n}\n","import BaseStreamController, { State } from './base-stream-controller';\nimport { changeTypeSupported } from '../is-supported';\nimport { Events } from '../events';\nimport { BufferHelper, BufferInfo } from '../utils/buffer-helper';\nimport { FragmentState } from './fragment-tracker';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { ElementaryStreamTypes, Fragment } from '../loader/fragment';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport GapController, { MAX_START_GAP_JUMP } from './gap-controller';\nimport { ErrorDetails } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { Level } from '../types/level';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type KeyLoader from '../loader/key-loader';\nimport type { TransmuxerResult } from '../types/transmuxer';\nimport type { TrackSet } from '../types/track';\nimport type { SourceBufferName } from '../types/buffer';\nimport type {\n AudioTrackSwitchedData,\n AudioTrackSwitchingData,\n BufferCreatedData,\n BufferEOSData,\n BufferFlushedData,\n ErrorData,\n FragBufferedData,\n FragLoadedData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n LevelLoadedData,\n LevelLoadingData,\n LevelsUpdatedData,\n ManifestParsedData,\n MediaAttachedData,\n} from '../types/events';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nexport default class StreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n private audioCodecSwap: boolean = false;\n private gapController: GapController | null = null;\n private level: number = -1;\n private _forceStartLoad: boolean = false;\n private altAudio: boolean = false;\n private audioOnly: boolean = false;\n private fragPlaying: Fragment | null = null;\n private onvplaying: EventListener | null = null;\n private onvseeked: EventListener | null = null;\n private fragLastKbps: number = 0;\n private couldBacktrack: boolean = false;\n private backtrackFragment: Fragment | null = null;\n private audioCodecSwitch: boolean = false;\n private videoBuffer: any | null = null;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader,\n ) {\n super(\n hls,\n fragmentTracker,\n keyLoader,\n '[stream-controller]',\n PlaylistLevelType.MAIN,\n );\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this,\n );\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this,\n );\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n super.onHandlerDestroying();\n }\n\n public startLoad(startPosition: number): void {\n if (this.levels) {\n const { lastCurrentTime, hls } = this;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n if (hls.config.testBandwidth && this.levels.length > 1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n } else {\n startLevel = hls.firstAutoLevel;\n }\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n hls.nextLoadLevel = startLevel;\n this.level = hls.loadLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(\n `Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(\n 3,\n )}`,\n );\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n this.tick();\n } else {\n this._forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n public stopLoad() {\n this._forceStartLoad = false;\n super.stopLoad();\n }\n\n protected doTick() {\n switch (this.state) {\n case State.WAITING_LEVEL: {\n const { levels, level } = this;\n const currentLevel = levels?.[level];\n const details = currentLevel?.details;\n if (\n details &&\n (!details.live || this.levelLastLoaded === currentLevel)\n ) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.IDLE;\n break;\n } else if (this.hls.nextLoadLevel !== this.level) {\n this.state = State.IDLE;\n break;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY:\n {\n const now = self.performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || this.media?.seeking) {\n const { levels, level } = this;\n const currentLevel = levels?.[level];\n this.resetStartWhenNotLoaded(currentLevel || null);\n this.state = State.IDLE;\n }\n }\n break;\n default:\n break;\n }\n if (this.state === State.IDLE) {\n this.doTickIdle();\n }\n this.onTickEnd();\n }\n\n protected onTickEnd() {\n super.onTickEnd();\n this.checkBuffer();\n this.checkFragmentChanged();\n }\n\n private doTickIdle() {\n const { hls, levelLastLoaded, levels, media } = this;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch not enabled\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (\n levelLastLoaded === null ||\n (!media && (this.startFragRequested || !hls.config.startFragPrefetch))\n ) {\n return;\n }\n\n // If the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n return;\n }\n\n const level = hls.nextLoadLevel;\n if (!levels?.[level]) {\n return;\n }\n\n const levelInfo = levels[level];\n\n // if buffer length is less than maxBufLen try to load a new fragment\n\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null) {\n return;\n }\n\n const lastDetails = this.getLevelDetails();\n if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {\n const data: BufferEOSData = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(Events.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n\n // set next load level : this will trigger a playlist load if needed\n if (hls.loadLevel !== level && hls.manualLevel === -1) {\n this.log(`Adapting to level ${level} from level ${this.level}`);\n }\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (\n !levelDetails ||\n this.state === State.WAITING_LEVEL ||\n (levelDetails.live && this.levelLastLoaded !== levelInfo)\n ) {\n this.level = level;\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n const bufferLen = bufferInfo.len;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s\n const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);\n\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n if (\n this.backtrackFragment &&\n this.backtrackFragment.start > bufferInfo.end\n ) {\n this.backtrackFragment = null;\n }\n const targetBufferTime = this.backtrackFragment\n ? this.backtrackFragment.start\n : bufferInfo.end;\n let frag = this.getNextFragment(targetBufferTime, levelDetails);\n // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)\n if (\n this.couldBacktrack &&\n !this.fragPrevious &&\n frag &&\n frag.sn !== 'initSegment' &&\n this.fragmentTracker.getState(frag) !== FragmentState.OK\n ) {\n const backtrackSn = (this.backtrackFragment ?? frag).sn as number;\n const fragIdx = backtrackSn - levelDetails.startSN;\n const backtrackFrag = levelDetails.fragments[fragIdx - 1];\n if (backtrackFrag && frag.cc === backtrackFrag.cc) {\n frag = backtrackFrag;\n this.fragmentTracker.removeFragment(backtrackFrag);\n }\n } else if (this.backtrackFragment && bufferInfo.len) {\n this.backtrackFragment = null;\n }\n // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags\n if (frag && this.isLoopLoading(frag, targetBufferTime)) {\n const gapStart = frag.gap;\n if (!gapStart) {\n // Cleanup the fragment tracker before trying to find the next unbuffered fragment\n const type =\n this.audioOnly && !this.altAudio\n ? ElementaryStreamTypes.AUDIO\n : ElementaryStreamTypes.VIDEO;\n const mediaBuffer =\n (type === ElementaryStreamTypes.VIDEO\n ? this.videoBuffer\n : this.mediaBuffer) || this.media;\n if (mediaBuffer) {\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n }\n }\n frag = this.getNextFragmentLoopLoading(\n frag,\n levelDetails,\n bufferInfo,\n PlaylistLevelType.MAIN,\n maxBufLen,\n );\n }\n if (!frag) {\n return;\n }\n if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {\n frag = frag.initSegment;\n }\n\n this.loadFragment(frag, levelInfo, targetBufferTime);\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number,\n ) {\n // Check if fragment is not loaded\n const fragState = this.fragmentTracker.getState(frag);\n this.fragCurrent = frag;\n if (\n fragState === FragmentState.NOT_LOADED ||\n fragState === FragmentState.PARTIAL\n ) {\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, level);\n } else if (this.bitrateTest) {\n this.log(\n `Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`,\n );\n this._loadBitrateTestFrag(frag, level);\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, level, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n\n private getBufferedFrag(position) {\n return this.fragmentTracker.getBufferedFrag(\n position,\n PlaylistLevelType.MAIN,\n );\n }\n\n private followingBufferedFrag(frag: Fragment | null) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.end + 0.5);\n }\n return null;\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n public immediateLevelSwitch() {\n this.abortCurrentFrag();\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n public nextLevelSwitch() {\n const { levels, media } = this;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media?.readyState) {\n let fetchdelay;\n const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.start - 1);\n }\n const levelDetails = this.getLevelDetails();\n if (levelDetails?.live) {\n const bufferInfo = this.getMainFwdBufferInfo();\n // Do not flush in live stream with low buffer\n if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {\n return;\n }\n }\n if (!media.paused && levels) {\n // add a safety delay of 1s\n const nextLevelId = this.hls.nextLoadLevel;\n const nextLevel = levels[nextLevelId];\n const fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay =\n (this.fragCurrent.duration * nextLevel.maxBitrate) /\n (1000 * fragLastKbps) +\n 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // this.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n this.abortCurrentFrag();\n // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.\n const maxStart = nextBufferedFrag.maxStartPTS\n ? nextBufferedFrag.maxStartPTS\n : nextBufferedFrag.start;\n const fragDuration = nextBufferedFrag.duration;\n const startPts = Math.max(\n bufferedFrag.end,\n maxStart +\n Math.min(\n Math.max(\n fragDuration - this.config.maxFragLookUpTolerance,\n fragDuration * (this.couldBacktrack ? 0.5 : 0.125),\n ),\n fragDuration * (this.couldBacktrack ? 0.75 : 0.25),\n ),\n );\n this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n private abortCurrentFrag() {\n const fragCurrent = this.fragCurrent;\n this.fragCurrent = null;\n this.backtrackFragment = null;\n if (fragCurrent) {\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n switch (this.state) {\n case State.KEY_LOADING:\n case State.FRAG_LOADING:\n case State.FRAG_LOADING_WAITING_RETRY:\n case State.PARSING:\n case State.PARSED:\n this.state = State.IDLE;\n break;\n }\n this.nextLoadPosition = this.getLoadPosition();\n }\n\n protected flushMainBuffer(startOffset: number, endOffset: number) {\n super.flushMainBuffer(\n startOffset,\n endOffset,\n this.altAudio ? 'video' : null,\n );\n }\n\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ) {\n super.onMediaAttached(event, data);\n const media = data.media;\n this.onvplaying = this.onMediaPlaying.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n media.addEventListener('playing', this.onvplaying as EventListener);\n media.addEventListener('seeked', this.onvseeked as EventListener);\n this.gapController = new GapController(\n this.config,\n media,\n this.fragmentTracker,\n this.hls,\n );\n }\n\n protected onMediaDetaching() {\n const { media } = this;\n if (media && this.onvplaying && this.onvseeked) {\n media.removeEventListener('playing', this.onvplaying);\n media.removeEventListener('seeked', this.onvseeked);\n this.onvplaying = this.onvseeked = null;\n this.videoBuffer = null;\n }\n this.fragPlaying = null;\n if (this.gapController) {\n this.gapController.destroy();\n this.gapController = null;\n }\n super.onMediaDetaching();\n }\n\n private onMediaPlaying() {\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n }\n\n private onMediaSeeked() {\n const media = this.media;\n const currentTime = media ? media.currentTime : null;\n if (Number.isFinite(currentTime)) {\n this.log(`Media seeked to ${(currentTime as number).toFixed(3)}`);\n }\n\n // If seeked was issued before buffer was appended do not tick immediately\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null || bufferInfo.len === 0) {\n this.warn(\n `Main forward buffer length on \"seeked\" event ${\n bufferInfo ? bufferInfo.len : 'empty'\n })`,\n );\n return;\n }\n\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n }\n\n private onManifestLoading() {\n // reset buffer on manifest loading\n this.log('Trigger BUFFER_RESET');\n this.hls.trigger(Events.BUFFER_RESET, undefined);\n this.fragmentTracker.removeAllFragments();\n this.couldBacktrack = false;\n this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;\n this.levels =\n this.fragPlaying =\n this.backtrackFragment =\n this.levelLastLoaded =\n null;\n this.altAudio = this.audioOnly = this.startFragRequested = false;\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n // detect if we have different kind of audio codecs used amongst playlists\n let aac = false;\n let heaac = false;\n data.levels.forEach((level) => {\n const codec = level.audioCodec;\n if (codec) {\n aac = aac || codec.indexOf('mp4a.40.2') !== -1;\n heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;\n }\n });\n this.audioCodecSwitch = aac && heaac && !changeTypeSupported();\n if (this.audioCodecSwitch) {\n this.log(\n 'Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC',\n );\n }\n\n this.levels = data.levels;\n this.startFragRequested = false;\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { levels } = this;\n if (!levels || this.state !== State.IDLE) {\n return;\n }\n const level = levels[data.level];\n if (\n !level.details ||\n (level.details.live && this.levelLastLoaded !== level) ||\n this.waitForCdnTuneIn(level.details)\n ) {\n this.state = State.WAITING_LEVEL;\n }\n }\n\n private onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const { levels } = this;\n const newLevelId = data.level;\n const newDetails = data.details;\n const duration = newDetails.totalduration;\n\n if (!levels) {\n this.warn(`Levels were reset while loading level ${newLevelId}`);\n return;\n }\n this.log(\n `Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${\n newDetails.lastPartSn\n ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]`\n : ''\n }, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`,\n );\n\n const curLevel = levels[newLevelId];\n const fragCurrent = this.fragCurrent;\n if (\n fragCurrent &&\n (this.state === State.FRAG_LOADING ||\n this.state === State.FRAG_LOADING_WAITING_RETRY)\n ) {\n if (fragCurrent.level !== data.level && fragCurrent.loader) {\n this.abortCurrentFrag();\n }\n }\n\n let sliding = 0;\n if (newDetails.live || curLevel.details?.live) {\n this.checkLiveUpdate(newDetails);\n if (newDetails.deltaUpdateFailed) {\n return;\n }\n sliding = this.alignPlaylists(\n newDetails,\n curLevel.details,\n this.levelLastLoaded?.details,\n );\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = curLevel;\n\n this.hls.trigger(Events.LEVEL_UPDATED, {\n details: newDetails,\n level: newLevelId,\n });\n\n // only switch back to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n if (this.waitForCdnTuneIn(newDetails)) {\n // Wait for Low-Latency CDN Tune-in\n return;\n }\n this.state = State.IDLE;\n }\n\n if (!this.startFragRequested) {\n this.setStartPosition(newDetails, sliding);\n } else if (newDetails.live) {\n this.synchronizeToLiveEdge(newDetails);\n }\n\n // trigger handler right now\n this.tick();\n }\n\n protected _handleFragmentLoadProgress(data: FragLoadedData) {\n const { frag, part, payload } = data;\n const { levels } = this;\n if (!levels) {\n this.warn(\n `Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`,\n );\n return;\n }\n const currentLevel = levels[frag.level];\n const details = currentLevel.details as LevelDetails;\n if (!details) {\n this.warn(\n `Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`,\n );\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n const videoCodec = currentLevel.videoCodec;\n\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n const accurateTimeOffset = details.PTSKnown || !details.live;\n const initSegmentData = frag.initSegment?.data;\n const audioCodec = this._getAudioCodec(currentLevel);\n\n // transmux the MPEG-TS data to ISO-BMFF segments\n // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);\n const transmuxer = (this.transmuxer =\n this.transmuxer ||\n new TransmuxerInterface(\n this.hls,\n PlaylistLevelType.MAIN,\n this._handleTransmuxComplete.bind(this),\n this._handleTransmuxerFlush.bind(this),\n ));\n const partIndex = part ? part.index : -1;\n const partial = partIndex !== -1;\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount,\n payload.byteLength,\n partIndex,\n partial,\n );\n const initPTS = this.initPTS[frag.cc];\n\n transmuxer.push(\n payload,\n initSegmentData,\n audioCodec,\n videoCodec,\n frag,\n part,\n details.totalduration,\n accurateTimeOffset,\n chunkMeta,\n initPTS,\n );\n }\n\n private onAudioTrackSwitching(\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData,\n ) {\n // if any URL found on new audio track, it is an alternate audio track\n const fromAltAudio = this.altAudio;\n const altAudio = !!data.url;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n this.log(\n 'Switching on main audio, use media.buffered to schedule main fragment loading',\n );\n this.mediaBuffer = this.media;\n const fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent) {\n this.log('Switching to main audio track, cancel main fragment load');\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n // destroy transmuxer to force init segment generation (following audio switch)\n this.resetTransmuxer();\n // switch to IDLE state to load new fragment\n this.resetLoadingState();\n } else if (this.audioOnly) {\n // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off\n this.resetTransmuxer();\n }\n const hls = this.hls;\n // If switching from alt to main audio, flush all audio and trigger track switched\n if (fromAltAudio) {\n hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: Number.POSITIVE_INFINITY,\n type: null,\n });\n this.fragmentTracker.removeAllFragments();\n }\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);\n }\n }\n\n private onAudioTrackSwitched(\n event: Events.AUDIO_TRACK_SWITCHED,\n data: AudioTrackSwitchedData,\n ) {\n const trackId = data.id;\n const altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n const videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n this.log(\n 'Switching on alternate audio, use video.buffered to schedule main fragment loading',\n );\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n private onBufferCreated(\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData,\n ) {\n const tracks = data.tracks;\n let mediaTrack;\n let name;\n let alternate = false;\n for (const type in tracks) {\n const track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n const videoTrack = tracks[type];\n if (videoTrack) {\n this.videoBuffer = videoTrack.buffer;\n }\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n this.log(\n `Alternate track found, use ${name}.buffered to schedule main fragment loading`,\n );\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n private onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n const { frag, part } = data;\n if (frag && frag.type !== PlaylistLevelType.MAIN) {\n return;\n }\n if (this.fragContextChanged(frag)) {\n // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n // Avoid setting state back to IDLE, since that will interfere with a level switch\n this.warn(\n `Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${\n frag.level\n } finished buffering, but was aborted. state: ${this.state}`,\n );\n if (this.state === State.PARSED) {\n this.state = State.IDLE;\n }\n return;\n }\n const stats = part ? part.stats : frag.stats;\n this.fragLastKbps = Math.round(\n (8 * stats.total) / (stats.buffering.end - stats.loading.first),\n );\n if (frag.sn !== 'initSegment') {\n this.fragPrevious = frag;\n }\n this.fragBufferedComplete(frag, part);\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n this.state = State.ERROR;\n return;\n }\n switch (data.details) {\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_PARSING_ERROR:\n case ErrorDetails.FRAG_DECRYPT_ERROR:\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE\n if (\n !data.levelRetry &&\n this.state === State.WAITING_LEVEL &&\n data.context?.type === PlaylistContextType.LEVEL\n ) {\n this.state = State.IDLE;\n }\n break;\n case ErrorDetails.BUFFER_APPEND_ERROR:\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (!data.parent || data.parent !== 'main') {\n return;\n }\n if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {\n this.resetLoadingState();\n return;\n }\n if (this.reduceLengthAndFlushBuffer(data)) {\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n break;\n case ErrorDetails.INTERNAL_EXCEPTION:\n this.recoverWorkerError(data);\n break;\n default:\n break;\n }\n }\n\n // Checks the health of the buffer and attempts to resolve playback stalls.\n private checkBuffer() {\n const { media, gapController } = this;\n if (!media || !gapController || !media.readyState) {\n // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n return;\n }\n\n if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {\n // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers\n const activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;\n gapController.poll(this.lastCurrentTime, activeFrag);\n }\n\n this.lastCurrentTime = media.currentTime;\n }\n\n private onFragLoadEmergencyAborted() {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tickImmediate();\n }\n\n private onBufferFlushed(\n event: Events.BUFFER_FLUSHED,\n { type }: BufferFlushedData,\n ) {\n if (\n type !== ElementaryStreamTypes.AUDIO ||\n (this.audioOnly && !this.altAudio)\n ) {\n const mediaBuffer =\n (type === ElementaryStreamTypes.VIDEO\n ? this.videoBuffer\n : this.mediaBuffer) || this.media;\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n this.tick();\n }\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData,\n ) {\n if (this.level > -1 && this.fragCurrent) {\n this.level = this.fragCurrent.level;\n }\n this.levels = data.levels;\n }\n\n public swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n */\n protected seekToStartPos() {\n const { media } = this;\n if (!media) {\n return;\n }\n const currentTime = media.currentTime;\n let startPosition = this.startPosition;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n if (startPosition >= 0 && currentTime < startPosition) {\n if (media.seeking) {\n this.log(\n `could not seek to ${startPosition}, already seeking at ${currentTime}`,\n );\n return;\n }\n const buffered = BufferHelper.getBuffered(media);\n const bufferStart = buffered.length ? buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n if (\n delta > 0 &&\n (delta < this.config.maxBufferHole ||\n delta < this.config.maxFragLookUpTolerance)\n ) {\n this.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n this.log(\n `seek to target start position ${startPosition} from current time ${currentTime}`,\n );\n media.currentTime = startPosition;\n }\n }\n\n private _getAudioCodec(currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap && audioCodec) {\n this.log('Swapping audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n\n return audioCodec;\n }\n\n private _loadBitrateTestFrag(frag: Fragment, level: Level) {\n frag.bitrateTest = true;\n this._doFragLoad(frag, level).then((data) => {\n const { hls } = this;\n if (!data || this.fragContextChanged(frag)) {\n return;\n }\n level.fragmentError = 0;\n this.state = State.IDLE;\n this.startFragRequested = false;\n this.bitrateTest = false;\n const stats = frag.stats;\n // Bitrate tests fragments are neither parsed nor buffered\n stats.parsing.start =\n stats.parsing.end =\n stats.buffering.start =\n stats.buffering.end =\n self.performance.now();\n hls.trigger(Events.FRAG_LOADED, data as FragLoadedData);\n frag.bitrateTest = false;\n });\n }\n\n private _handleTransmuxComplete(transmuxResult: TransmuxerResult) {\n const id = 'main';\n const { hls } = this;\n const { remuxResult, chunkMeta } = transmuxResult;\n\n const context = this.getCurrentContext(chunkMeta);\n if (!context) {\n this.resetWhenMissingContext(chunkMeta);\n return;\n }\n const { frag, part, level } = context;\n const { video, text, id3, initSegment } = remuxResult;\n const { details } = level;\n // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track\n const audio = this.altAudio ? undefined : remuxResult.audio;\n\n // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n if (this.fragContextChanged(frag)) {\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n\n this.state = State.PARSING;\n\n if (initSegment) {\n if (initSegment?.tracks) {\n const mapFragment = frag.initSegment || frag;\n this._bufferInitSegment(\n level,\n initSegment.tracks,\n mapFragment,\n chunkMeta,\n );\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag: mapFragment,\n id,\n tracks: initSegment.tracks,\n });\n }\n\n // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038\n const initPTS = initSegment.initPTS as number;\n const timescale = initSegment.timescale as number;\n if (Number.isFinite(initPTS)) {\n this.initPTS[frag.cc] = { baseTime: initPTS, timescale };\n hls.trigger(Events.INIT_PTS_FOUND, { frag, id, initPTS, timescale });\n }\n }\n\n // Avoid buffering if backtracking this fragment\n if (video && details && frag.sn !== 'initSegment') {\n const prevFrag = details.fragments[frag.sn - 1 - details.startSN];\n const isFirstFragment = frag.sn === details.startSN;\n const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;\n if (remuxResult.independent !== false) {\n const { startPTS, endPTS, startDTS, endDTS } = video;\n if (part) {\n part.elementaryStreams[video.type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n } else {\n if (\n video.firstKeyFrame &&\n video.independent &&\n chunkMeta.id === 1 &&\n !isFirstInDiscontinuity\n ) {\n this.couldBacktrack = true;\n }\n if (video.dropped && video.independent) {\n // Backtrack if dropped frames create a gap after currentTime\n\n const bufferInfo = this.getMainFwdBufferInfo();\n const targetBufferTime =\n (bufferInfo ? bufferInfo.end : this.getLoadPosition()) +\n this.config.maxBufferHole;\n const startTime = video.firstKeyFramePTS\n ? video.firstKeyFramePTS\n : startPTS;\n if (\n !isFirstFragment &&\n targetBufferTime < startTime - this.config.maxBufferHole &&\n !isFirstInDiscontinuity\n ) {\n this.backtrack(frag);\n return;\n } else if (isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n }\n // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n frag.start,\n endPTS,\n frag.start,\n endDTS,\n true,\n );\n } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) {\n // Mark segment with a gap to skip large start gap\n frag.gap = true;\n }\n }\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n );\n if (this.backtrackFragment) {\n this.backtrackFragment = frag;\n }\n this.bufferFragmentData(\n video,\n frag,\n part,\n chunkMeta,\n isFirstFragment || isFirstInDiscontinuity,\n );\n } else if (isFirstFragment || isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n } else {\n this.backtrack(frag);\n return;\n }\n }\n\n if (audio) {\n const { startPTS, endPTS, startDTS, endDTS } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n }\n frag.setElementaryStreamInfo(\n ElementaryStreamTypes.AUDIO,\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n );\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n\n if (details && id3?.samples?.length) {\n const emittedID3: FragParsingMetadataData = {\n id,\n frag,\n details,\n samples: id3.samples,\n };\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (details && text) {\n const emittedText: FragParsingUserdataData = {\n id,\n frag,\n details,\n samples: text.samples,\n };\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n\n private _bufferInitSegment(\n currentLevel: Level,\n tracks: TrackSet,\n frag: Fragment,\n chunkMeta: ChunkMetadata,\n ) {\n if (this.state !== State.PARSING) {\n return;\n }\n\n this.audioOnly = !!tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\n delete tracks.audio;\n }\n // include levelCodec in audio and video tracks\n const { audio, video, audiovideo } = tracks;\n if (audio) {\n let audioCodec = currentLevel.audioCodec;\n const ua = navigator.userAgent.toLowerCase();\n if (this.audioCodecSwitch) {\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // In the case that AAC and HE-AAC audio codecs are signalled in manifest,\n // force HE-AAC, as it seems that most browsers prefers it.\n // don't force HE-AAC if mono stream, or in Firefox\n const audioMetadata = audio.metadata;\n if (\n audioMetadata &&\n 'channelCount' in audioMetadata &&\n (audioMetadata.channelCount || 1) !== 1 &&\n ua.indexOf('firefox') === -1\n ) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (\n audioCodec &&\n audioCodec.indexOf('mp4a.40.5') !== -1 &&\n ua.indexOf('android') !== -1 &&\n audio.container !== 'audio/mpeg'\n ) {\n // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n this.log(`Android: force audio codec to ${audioCodec}`);\n }\n if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {\n this.log(\n `Swapping manifest audio codec \"${currentLevel.audioCodec}\" for \"${audioCodec}\"`,\n );\n }\n audio.levelCodec = audioCodec;\n audio.id = 'main';\n this.log(\n `Init audio buffer, container:${\n audio.container\n }, codecs[selected/level/parsed]=[${audioCodec || ''}/${\n currentLevel.audioCodec || ''\n }/${audio.codec}]`,\n );\n }\n if (video) {\n video.levelCodec = currentLevel.videoCodec;\n video.id = 'main';\n this.log(\n `Init video buffer, container:${\n video.container\n }, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${\n video.codec\n }]`,\n );\n }\n if (audiovideo) {\n this.log(\n `Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`,\n );\n }\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n Object.keys(tracks).forEach((trackName) => {\n const track = tracks[trackName];\n const initSegment = track.initSegment;\n if (initSegment?.byteLength) {\n this.hls.trigger(Events.BUFFER_APPENDING, {\n type: trackName as SourceBufferName,\n data: initSegment,\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n });\n }\n });\n // trigger handler right now\n this.tickImmediate();\n }\n\n public getMainFwdBufferInfo(): BufferInfo | null {\n return this.getFwdBufferInfo(\n this.mediaBuffer ? this.mediaBuffer : this.media,\n PlaylistLevelType.MAIN,\n );\n }\n\n private backtrack(frag: Fragment) {\n this.couldBacktrack = true;\n // Causes findFragments to backtrack through fragments to find the keyframe\n this.backtrackFragment = frag;\n this.resetTransmuxer();\n this.flushBufferGap(frag);\n this.fragmentTracker.removeFragment(frag);\n this.fragPrevious = null;\n this.nextLoadPosition = frag.start;\n this.state = State.IDLE;\n }\n\n private checkFragmentChanged() {\n const video = this.media;\n let fragPlayingCurrent: Fragment | null = null;\n if (video && video.readyState > 1 && video.seeking === false) {\n const currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getAppendedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n this.backtrackFragment = null;\n const fragPlaying = this.fragPlaying;\n const fragCurrentLevel = fragPlayingCurrent.level;\n if (\n !fragPlaying ||\n fragPlayingCurrent.sn !== fragPlaying.sn ||\n fragPlaying.level !== fragCurrentLevel\n ) {\n this.fragPlaying = fragPlayingCurrent;\n this.hls.trigger(Events.FRAG_CHANGED, { frag: fragPlayingCurrent });\n if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {\n this.hls.trigger(Events.LEVEL_SWITCHED, {\n level: fragCurrentLevel,\n });\n }\n }\n }\n }\n }\n\n get nextLevel(): number {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get currentFrag(): Fragment | null {\n const media = this.media;\n if (media) {\n return this.fragPlaying || this.getAppendedFrag(media.currentTime);\n }\n return null;\n }\n\n get currentProgramDateTime(): Date | null {\n const media = this.media;\n if (media) {\n const currentTime = media.currentTime;\n const frag = this.currentFrag;\n if (\n frag &&\n Number.isFinite(currentTime) &&\n Number.isFinite(frag.programDateTime)\n ) {\n const epocMs =\n (frag.programDateTime as number) + (currentTime - frag.start) * 1000;\n return new Date(epocMs);\n }\n }\n return null;\n }\n\n get currentLevel(): number {\n const frag = this.currentFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get nextBufferedFrag() {\n const frag = this.currentFrag;\n if (frag) {\n return this.followingBufferedFrag(frag);\n }\n return null;\n }\n\n get forceStartLoad() {\n return this._forceStartLoad;\n }\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport PlaylistLoader from './loader/playlist-loader';\nimport ID3TrackController from './controller/id3-track-controller';\nimport LatencyController from './controller/latency-controller';\nimport LevelController from './controller/level-controller';\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport KeyLoader from './loader/key-loader';\nimport StreamController from './controller/stream-controller';\nimport { isMSESupported, isSupported } from './is-supported';\nimport { getMediaSource } from './utils/mediasource-helper';\nimport { logger, enableLogs } from './utils/logger';\nimport { enableStreamingMode, hlsDefaultConfig, mergeConfig } from './config';\nimport { EventEmitter } from 'eventemitter3';\nimport { Events } from './events';\nimport { ErrorTypes, ErrorDetails } from './errors';\nimport { isHdcpLevel, type HdcpLevel, type Level } from './types/level';\nimport type { HlsEventEmitter, HlsListeners } from './events';\nimport type AudioTrackController from './controller/audio-track-controller';\nimport type AbrController from './controller/abr-controller';\nimport type BufferController from './controller/buffer-controller';\nimport type CapLevelController from './controller/cap-level-controller';\nimport type CMCDController from './controller/cmcd-controller';\nimport type EMEController from './controller/eme-controller';\nimport type SubtitleTrackController from './controller/subtitle-track-controller';\nimport type {\n AbrComponentAPI,\n ComponentAPI,\n NetworkComponentAPI,\n} from './types/component-api';\nimport type {\n AudioSelectionOption,\n MediaPlaylist,\n SubtitleSelectionOption,\n VideoSelectionOption,\n} from './types/media-playlist';\nimport type { HlsConfig } from './config';\nimport type { BufferInfo } from './utils/buffer-helper';\nimport type AudioStreamController from './controller/audio-stream-controller';\nimport type BasePlaylistController from './controller/base-playlist-controller';\nimport type BaseStreamController from './controller/base-stream-controller';\nimport type ContentSteeringController from './controller/content-steering-controller';\nimport type ErrorController from './controller/error-controller';\nimport type FPSController from './controller/fps-controller';\n\n/**\n * The `Hls` class is the core of the HLS.js library used to instantiate player instances.\n * @public\n */\nexport default class Hls implements HlsEventEmitter {\n private static defaultConfig: HlsConfig | undefined;\n\n /**\n * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.\n */\n public readonly config: HlsConfig;\n\n /**\n * The configuration object provided on player instantiation.\n */\n public readonly userConfig: Partial<HlsConfig>;\n\n private coreComponents: ComponentAPI[];\n private networkControllers: NetworkComponentAPI[];\n private started: boolean = false;\n private _emitter: HlsEventEmitter = new EventEmitter();\n private _autoLevelCapping: number = -1;\n private _maxHdcpLevel: HdcpLevel = null;\n private abrController: AbrComponentAPI;\n private bufferController: BufferController;\n private capLevelController: CapLevelController;\n private latencyController: LatencyController;\n private levelController: LevelController;\n private streamController: StreamController;\n private audioTrackController: AudioTrackController;\n private subtitleTrackController: SubtitleTrackController;\n private emeController: EMEController;\n private cmcdController: CMCDController;\n private _media: HTMLMediaElement | null = null;\n private url: string | null = null;\n private triggeringException?: boolean;\n\n /**\n * Get the video-dev/hls.js package version.\n */\n static get version(): string {\n return __VERSION__;\n }\n\n /**\n * Check if the required MediaSource Extensions are available.\n */\n static isMSESupported(): boolean {\n return isMSESupported();\n }\n\n /**\n * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.\n */\n static isSupported(): boolean {\n return isSupported();\n }\n\n /**\n * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).\n */\n static getMediaSource(): typeof MediaSource | undefined {\n return getMediaSource();\n }\n\n static get Events(): typeof Events {\n return Events;\n }\n\n static get ErrorTypes(): typeof ErrorTypes {\n return ErrorTypes;\n }\n\n static get ErrorDetails(): typeof ErrorDetails {\n return ErrorDetails;\n }\n\n /**\n * Get the default configuration applied to new instances.\n */\n static get DefaultConfig(): HlsConfig {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * Replace the default configuration applied to new instances.\n */\n static set DefaultConfig(defaultConfig: HlsConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n * @param userConfig - Configuration options applied over `Hls.DefaultConfig`\n */\n constructor(userConfig: Partial<HlsConfig> = {}) {\n enableLogs(userConfig.debug || false, 'Hls instance');\n const config = (this.config = mergeConfig(Hls.DefaultConfig, userConfig));\n this.userConfig = userConfig;\n\n if (config.progressive) {\n enableStreamingMode(config);\n }\n\n // core controllers and network loaders\n const {\n abrController: ConfigAbrController,\n bufferController: ConfigBufferController,\n capLevelController: ConfigCapLevelController,\n errorController: ConfigErrorController,\n fpsController: ConfigFpsController,\n } = config;\n const errorController = new ConfigErrorController(this);\n const abrController = (this.abrController = new ConfigAbrController(this));\n const bufferController = (this.bufferController =\n new ConfigBufferController(this));\n const capLevelController = (this.capLevelController =\n new ConfigCapLevelController(this));\n\n const fpsController = new ConfigFpsController(this);\n const playListLoader = new PlaylistLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n const ConfigContentSteeringController = config.contentSteeringController;\n // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first\n const contentSteering = ConfigContentSteeringController\n ? new ConfigContentSteeringController(this)\n : null;\n const levelController = (this.levelController = new LevelController(\n this,\n contentSteering,\n ));\n // FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n const keyLoader = new KeyLoader(this.config);\n const streamController = (this.streamController = new StreamController(\n this,\n fragmentTracker,\n keyLoader,\n ));\n\n // Cap level controller uses streamController to flush the buffer\n capLevelController.setStreamController(streamController);\n // fpsController uses streamController to switch when frames are being dropped\n fpsController.setStreamController(streamController);\n\n const networkControllers: NetworkComponentAPI[] = [\n playListLoader,\n levelController,\n streamController,\n ];\n if (contentSteering) {\n networkControllers.splice(1, 0, contentSteering);\n }\n\n this.networkControllers = networkControllers;\n const coreComponents: ComponentAPI[] = [\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker,\n ];\n\n this.audioTrackController = this.createController(\n config.audioTrackController,\n networkControllers,\n );\n const AudioStreamControllerClass = config.audioStreamController;\n if (AudioStreamControllerClass) {\n networkControllers.push(\n new AudioStreamControllerClass(this, fragmentTracker, keyLoader),\n );\n }\n // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important\n this.subtitleTrackController = this.createController(\n config.subtitleTrackController,\n networkControllers,\n );\n const SubtitleStreamControllerClass = config.subtitleStreamController;\n if (SubtitleStreamControllerClass) {\n networkControllers.push(\n new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader),\n );\n }\n this.createController(config.timelineController, coreComponents);\n keyLoader.emeController = this.emeController = this.createController(\n config.emeController,\n coreComponents,\n );\n this.cmcdController = this.createController(\n config.cmcdController,\n coreComponents,\n );\n this.latencyController = this.createController(\n LatencyController,\n coreComponents,\n );\n\n this.coreComponents = coreComponents;\n\n // Error controller handles errors before and after all other controllers\n // This listener will be invoked after all other controllers error listeners\n networkControllers.push(errorController);\n const onErrorOut = errorController.onErrorOut;\n if (typeof onErrorOut === 'function') {\n this.on(Events.ERROR, onErrorOut, errorController);\n }\n }\n\n createController(ControllerClass, components) {\n if (ControllerClass) {\n const controllerInstance = new ControllerClass(this);\n if (components) {\n components.push(controllerInstance);\n }\n return controllerInstance;\n }\n return null;\n }\n\n // Delegate the EventEmitter through the public API of Hls.js\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any,\n ) {\n this._emitter.on(event, listener, context);\n }\n\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any,\n ) {\n this._emitter.once(event, listener, context);\n }\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E | undefined) {\n this._emitter.removeAllListeners(event);\n }\n\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E] | undefined,\n context: Context = this as any,\n once?: boolean | undefined,\n ) {\n this._emitter.off(event, listener, context, once);\n }\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][] {\n return this._emitter.listeners(event);\n }\n\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1],\n ): boolean {\n return this._emitter.emit(event, name, eventObject);\n }\n\n trigger<E extends keyof HlsListeners>(\n event: E,\n eventObject: Parameters<HlsListeners[E]>[1],\n ): boolean {\n if (this.config.debug) {\n return this.emit(event, event, eventObject);\n } else {\n try {\n return this.emit(event, event, eventObject);\n } catch (error) {\n logger.error(\n 'An internal error happened while handling event ' +\n event +\n '. Error message: \"' +\n error.message +\n '\". Here is a stacktrace:',\n error,\n );\n // Prevent recursion in error event handlers that throw #5497\n if (!this.triggeringException) {\n this.triggeringException = true;\n const fatal = event === Events.ERROR;\n this.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal,\n event,\n error,\n });\n this.triggeringException = false;\n }\n }\n }\n return false;\n }\n\n listenerCount<E extends keyof HlsListeners>(event: E): number {\n return this._emitter.listenerCount(event);\n }\n\n /**\n * Dispose of the instance\n */\n destroy() {\n logger.log('destroy');\n this.trigger(Events.DESTROYING, undefined);\n this.detachMedia();\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n this.url = null;\n\n this.networkControllers.forEach((component) => component.destroy());\n this.networkControllers.length = 0;\n\n this.coreComponents.forEach((component) => component.destroy());\n this.coreComponents.length = 0;\n // Remove any references that could be held in config options or callbacks\n const config = this.config;\n config.xhrSetup = config.fetchSetup = undefined;\n // @ts-ignore\n this.userConfig = null;\n }\n\n /**\n * Attaches Hls.js to a media element\n */\n attachMedia(media: HTMLMediaElement) {\n logger.log('attachMedia');\n this._media = media;\n this.trigger(Events.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach Hls.js from the media\n */\n detachMedia() {\n logger.log('detachMedia');\n this.trigger(Events.MEDIA_DETACHING, undefined);\n this._media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n */\n loadSource(url: string) {\n this.stopLoad();\n const media = this.media;\n const loadedSource = this.url;\n const loadingSource = (this.url = buildAbsoluteURL(\n self.location.href,\n url,\n {\n alwaysNormalize: true,\n },\n ));\n this._autoLevelCapping = -1;\n this._maxHdcpLevel = null;\n logger.log(`loadSource:${loadingSource}`);\n if (\n media &&\n loadedSource &&\n (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())\n ) {\n this.detachMedia();\n this.attachMedia(media);\n }\n // when attaching to a source URL, trigger a playlist load\n this.trigger(Events.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param startPosition - Set the start position to stream from.\n * Defaults to -1 (None: starts from earliest point)\n */\n startLoad(startPosition: number = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.started = true;\n this.networkControllers.forEach((controller) => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad() {\n logger.log('stopLoad');\n this.started = false;\n this.networkControllers.forEach((controller) => {\n controller.stopLoad();\n });\n }\n\n /**\n * Resumes stream controller segment loading if previously started.\n */\n resumeBuffering() {\n if (this.started) {\n this.networkControllers.forEach((controller) => {\n if ('fragmentLoader' in controller) {\n controller.startLoad(-1);\n }\n });\n }\n }\n\n /**\n * Stops stream controller segment loading without changing 'started' state like stopLoad().\n * This allows for media buffering to be paused without interupting playlist loading.\n */\n pauseBuffering() {\n this.networkControllers.forEach((controller) => {\n if ('fragmentLoader' in controller) {\n controller.stopLoad();\n }\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec() {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError() {\n logger.log('recoverMediaError');\n const media = this._media;\n this.detachMedia();\n if (media) {\n this.attachMedia(media);\n }\n }\n\n removeLevel(levelIndex: number) {\n this.levelController.removeLevel(levelIndex);\n }\n\n /**\n * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH\n */\n get levels(): Level[] {\n const levels = this.levelController.levels;\n return levels ? levels : [];\n }\n\n /**\n * Index of quality level (variant) currently played\n */\n get currentLevel(): number {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.\n */\n set currentLevel(newLevel: number) {\n logger.log(`set currentLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n */\n get nextLevel(): number {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @param newLevel - Pass -1 for automatic level selection\n */\n set nextLevel(newLevel: number) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n */\n get loadLevel(): number {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @param newLevel - Pass -1 for automatic level selection\n */\n set loadLevel(newLevel: number) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n */\n get nextLoadLevel(): number {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n */\n set nextLoadLevel(level: number) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n */\n get firstLevel(): number {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n */\n set firstLevel(newLevel: number) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return the desired start level for the first fragment that will be loaded.\n * The default value of -1 indicates automatic start level selection.\n * Setting hls.nextAutoLevel without setting a startLevel will result in\n * the nextAutoLevel value being used for one fragment load.\n */\n get startLevel(): number {\n const startLevel = this.levelController.startLevel;\n if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {\n return this.abrController.forcedAutoLevel;\n }\n return startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n */\n set startLevel(newLevel: number) {\n logger.log(`set startLevel:${newLevel}`);\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.minAutoLevel);\n }\n\n this.levelController.startLevel = newLevel;\n }\n\n /**\n * Whether level capping is enabled.\n * Default value is set via `config.capLevelToPlayerSize`.\n */\n get capLevelToPlayerSize(): boolean {\n return this.config.capLevelToPlayerSize;\n }\n\n /**\n * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.\n */\n set capLevelToPlayerSize(shouldStartCapping: boolean) {\n const newCapLevelToPlayerSize = !!shouldStartCapping;\n\n if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n if (newCapLevelToPlayerSize) {\n this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n } else {\n this.capLevelController.stopCapping();\n this.autoLevelCapping = -1;\n this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n }\n\n this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n }\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n get autoLevelCapping(): number {\n return this._autoLevelCapping;\n }\n\n /**\n * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.\n */\n get bandwidthEstimate(): number {\n const { bwEstimator } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimate();\n }\n\n set bandwidthEstimate(abrEwmaDefaultEstimate: number) {\n this.abrController.resetEstimator(abrEwmaDefaultEstimate);\n }\n\n /**\n * get time to first byte estimate\n * @type {number}\n */\n get ttfbEstimate(): number {\n const { bwEstimator } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimateTTFB();\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n set autoLevelCapping(newLevel: number) {\n if (this._autoLevelCapping !== newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n this.levelController.checkMaxAutoUpdated();\n }\n }\n\n get maxHdcpLevel(): HdcpLevel {\n return this._maxHdcpLevel;\n }\n\n set maxHdcpLevel(value: HdcpLevel) {\n if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {\n this._maxHdcpLevel = value;\n this.levelController.checkMaxAutoUpdated();\n }\n }\n\n /**\n * True when automatic level selection enabled\n */\n get autoLevelEnabled(): boolean {\n return this.levelController.manualLevel === -1;\n }\n\n /**\n * Level set manually (if any)\n */\n get manualLevel(): number {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n */\n get minAutoLevel(): number {\n const {\n levels,\n config: { minAutoBitrate },\n } = this;\n if (!levels) return 0;\n\n const len = levels.length;\n for (let i = 0; i < len; i++) {\n if (levels[i].maxBitrate >= minAutoBitrate) {\n return i;\n }\n }\n\n return 0;\n }\n\n /**\n * max level selectable in auto mode according to autoLevelCapping\n */\n get maxAutoLevel(): number {\n const { levels, autoLevelCapping, maxHdcpLevel } = this;\n\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels?.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n if (maxHdcpLevel) {\n for (let i = maxAutoLevel; i--; ) {\n const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];\n if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {\n return i;\n }\n }\n }\n\n return maxAutoLevel;\n }\n\n get firstAutoLevel(): number {\n return this.abrController.firstAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n */\n get nextAutoLevel(): number {\n return this.abrController.nextAutoLevel;\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon successful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n */\n set nextAutoLevel(nextLevel: number) {\n this.abrController.nextAutoLevel = nextLevel;\n }\n\n /**\n * get the datetime value relative to media.currentTime for the active level Program Date Time if present\n */\n public get playingDate(): Date | null {\n return this.streamController.currentProgramDateTime;\n }\n\n public get mainForwardBufferInfo(): BufferInfo | null {\n return this.streamController.getMainFwdBufferInfo();\n }\n\n /**\n * Find and select the best matching audio track, making a level switch when a Group change is necessary.\n * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.\n */\n public setAudioOption(\n audioOption: MediaPlaylist | AudioSelectionOption | undefined,\n ): MediaPlaylist | null {\n return this.audioTrackController?.setAudioOption(audioOption);\n }\n /**\n * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.\n * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.\n */\n public setSubtitleOption(\n subtitleOption: MediaPlaylist | SubtitleSelectionOption | undefined,\n ): MediaPlaylist | null {\n this.subtitleTrackController?.setSubtitleOption(subtitleOption);\n return null;\n }\n\n /**\n * Get the complete list of audio tracks across all media groups\n */\n get allAudioTracks(): Array<MediaPlaylist> {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.allAudioTracks : [];\n }\n\n /**\n * Get the list of selectable audio tracks\n */\n get audioTracks(): Array<MediaPlaylist> {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n */\n get audioTrack(): number {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n */\n set audioTrack(audioTrackId: number) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * get the complete list of subtitle tracks across all media groups\n */\n get allSubtitleTracks(): Array<MediaPlaylist> {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.allSubtitleTracks\n : [];\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n */\n get subtitleTracks(): Array<MediaPlaylist> {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.subtitleTracks\n : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n */\n get subtitleTrack(): number {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n get media() {\n return this._media;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n */\n set subtitleTrack(subtitleTrackId: number) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * Whether subtitle display is enabled or not\n */\n get subtitleDisplay(): boolean {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.subtitleDisplay\n : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n */\n set subtitleDisplay(value: boolean) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n\n /**\n * get mode for Low-Latency HLS loading\n */\n get lowLatencyMode(): boolean {\n return this.config.lowLatencyMode;\n }\n\n /**\n * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.\n */\n set lowLatencyMode(mode: boolean) {\n this.config.lowLatencyMode = mode;\n }\n\n /**\n * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)\n * @returns null prior to loading live Playlist\n */\n get liveSyncPosition(): number | null {\n return this.latencyController.liveSyncPosition;\n }\n\n /**\n * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)\n * @returns 0 before first playlist is loaded\n */\n get latency(): number {\n return this.latencyController.latency;\n }\n\n /**\n * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```\n * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```\n * @returns 0 before first playlist is loaded\n */\n get maxLatency(): number {\n return this.latencyController.maxLatency;\n }\n\n /**\n * target distance from the edge as calculated by the latency controller\n */\n get targetLatency(): number | null {\n return this.latencyController.targetLatency;\n }\n\n /**\n * the rate at which the edge of the current live playlist is advancing or 1 if there is none\n */\n get drift(): number | null {\n return this.latencyController.drift;\n }\n\n /**\n * set to true when startLoad is called before MANIFEST_PARSED event\n */\n get forceStartLoad(): boolean {\n return this.streamController.forceStartLoad;\n }\n}\n\nexport type {\n AudioSelectionOption,\n SubtitleSelectionOption,\n VideoSelectionOption,\n MediaPlaylist,\n ErrorDetails,\n ErrorTypes,\n Events,\n Level,\n HlsListeners,\n HlsEventEmitter,\n HlsConfig,\n BufferInfo,\n HdcpLevel,\n AbrController,\n AudioStreamController,\n AudioTrackController,\n BasePlaylistController,\n BaseStreamController,\n BufferController,\n CapLevelController,\n CMCDController,\n ContentSteeringController,\n EMEController,\n ErrorController,\n FPSController,\n SubtitleTrackController,\n};\nexport type {\n ComponentAPI,\n AbrComponentAPI,\n NetworkComponentAPI,\n} from './types/component-api';\nexport type {\n ABRControllerConfig,\n BufferControllerConfig,\n CapLevelControllerConfig,\n CMCDControllerConfig,\n EMEControllerConfig,\n DRMSystemsConfiguration,\n DRMSystemOptions,\n FPSControllerConfig,\n FragmentLoaderConfig,\n FragmentLoaderConstructor,\n HlsLoadPolicies,\n LevelControllerConfig,\n LoaderConfig,\n LoadPolicy,\n MP4RemuxerConfig,\n PlaylistLoaderConfig,\n PlaylistLoaderConstructor,\n RetryConfig,\n SelectionPreferences,\n StreamControllerConfig,\n LatencyControllerConfig,\n MetadataControllerConfig,\n TimelineControllerConfig,\n TSDemuxerConfig,\n} from './config';\nexport type { MediaKeySessionContext } from './controller/eme-controller';\nexport type { ILogger } from './utils/logger';\nexport type {\n PathwayClone,\n SteeringManifest,\n UriReplacement,\n} from './controller/content-steering-controller';\nexport type { SubtitleStreamController } from './controller/subtitle-stream-controller';\nexport type { TimelineController } from './controller/timeline-controller';\nexport type { CuesInterface } from './utils/cues';\nexport type {\n MediaKeyFunc,\n KeySystems,\n KeySystemFormats,\n} from './utils/mediakeys-helper';\nexport type { DateRange } from './loader/date-range';\nexport type { LoadStats } from './loader/load-stats';\nexport type { LevelKey } from './loader/level-key';\nexport type { LevelDetails } from './loader/level-details';\nexport type { SourceBufferName } from './types/buffer';\nexport type {\n MetadataSample,\n MetadataSchema,\n UserdataSample,\n} from './types/demuxer';\nexport type {\n HlsSkip,\n HlsUrlParameters,\n LevelAttributes,\n LevelParsed,\n VariableMap,\n} from './types/level';\nexport type { MediaDecodingInfo } from './utils/mediacapabilities-helper';\nexport type {\n PlaylistLevelType,\n HlsChunkPerformanceTiming,\n HlsPerformanceTiming,\n HlsProgressivePerformanceTiming,\n PlaylistContextType,\n PlaylistLoaderContext,\n FragmentLoaderContext,\n Loader,\n LoaderStats,\n LoaderContext,\n LoaderResponse,\n LoaderConfiguration,\n LoaderCallbacks,\n LoaderOnProgress,\n LoaderOnAbort,\n LoaderOnError,\n LoaderOnSuccess,\n LoaderOnTimeout,\n} from './types/loader';\nexport type {\n MediaAttributes,\n MediaPlaylistType,\n MainPlaylistType,\n AudioPlaylistType,\n SubtitlePlaylistType,\n} from './types/media-playlist';\nexport type { Track, TrackSet } from './types/track';\nexport type { ChunkMetadata } from './types/transmuxer';\nexport type {\n BaseSegment,\n Fragment,\n Part,\n ElementaryStreams,\n ElementaryStreamTypes,\n ElementaryStreamInfo,\n} from './loader/fragment';\nexport type {\n TrackLoadingData,\n TrackLoadedData,\n AudioTrackLoadedData,\n AudioTracksUpdatedData,\n AudioTrackSwitchedData,\n AudioTrackSwitchingData,\n BackBufferData,\n BufferAppendedData,\n BufferAppendingData,\n BufferCodecsData,\n BufferCreatedData,\n BufferEOSData,\n BufferFlushedData,\n BufferFlushingData,\n CuesParsedData,\n ErrorData,\n FPSDropData,\n FPSDropLevelCappingData,\n FragBufferedData,\n FragChangedData,\n FragDecryptedData,\n FragLoadedData,\n FragLoadEmergencyAbortedData,\n FragLoadingData,\n FragParsedData,\n FragParsingInitSegmentData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n InitPTSFoundData,\n KeyLoadedData,\n KeyLoadingData,\n LevelLoadedData,\n LevelLoadingData,\n LevelPTSUpdatedData,\n LevelsUpdatedData,\n LevelSwitchedData,\n LevelSwitchingData,\n LevelUpdatedData,\n LiveBackBufferData,\n ContentSteeringOptions,\n ManifestLoadedData,\n ManifestLoadingData,\n ManifestParsedData,\n MediaAttachedData,\n MediaAttachingData,\n NonNativeTextTrack,\n NonNativeTextTracksData,\n SteeringManifestLoadedData,\n SubtitleFragProcessedData,\n SubtitleTrackLoadedData,\n SubtitleTracksUpdatedData,\n SubtitleTrackSwitchData,\n} from './types/events';\nexport type {\n NetworkErrorAction,\n ErrorActionFlags,\n IErrorAction,\n} from './controller/error-controller';\nexport type { AttrList } from './utils/attr-list';\n"],"names":["URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","Error","path","normalizePath","buildURLFromParts","relativeParts","scheme","baseParts","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","substring","lastIndexOf","url","parts","split","reverse","join","replace","length","module","exports","isFiniteNumber","Number","isFinite","value","isSafeInteger","Math","abs","MAX_SAFE_INTEGER","Events","ErrorTypes","ErrorDetails","noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","exportLoggerFunctions","debugConfig","_len","arguments","functions","Array","_key","forEach","type","bind","func","self","console","consolePrintFn","enableLogs","id","e","logger","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","parseAttrList","_extends","this","_proto","prototype","decimalInteger","attrName","intValue","parseInt","Infinity","hexadecimalInteger","stringValue","slice","Uint8Array","i","hexadecimalIntegerAsNumber","decimalFloatingPoint","parseFloat","optionalFloat","defaultValue","enumeratedString","bool","decimalResolution","res","width","height","input","match","lastIndex","indexOf","_createClass","key","get","Object","keys","filter","attr","isSCTE35Attribute","DateRange","dateRangeAttr","dateRangeWithSameId","_startDate","_endDate","_badValueForSameId","previousAttr","hasOwnProperty","call","ID","Date","endDate","_isFiniteNumber","getTime","CLASS","duration","_isFiniteNumber2","_isFiniteNumber3","startDate","endOnNext","class","LoadStats","aborted","loaded","retry","total","chunkCount","bwEstimate","loading","start","first","end","parsing","buffering","ElementaryStreamTypes","BaseSegment","baseurl","_this$elementaryStrea","_byteRange","_url","relurl","elementaryStreams","setByteRange","previous","byteRangeEndOffset","byteRange","set","Fragment","_BaseSegment","_this","_decryptdata","rawProgramDateTime","programDateTime","tagList","sn","levelkeys","loader","keyLoader","level","cc","startPTS","endPTS","startDTS","endDTS","deltaPTS","maxStartPTS","minEndPTS","stats","data","bitrateTest","title","initSegment","endList","gap","urlId","_inheritsLoose","_proto2","setKeyFormat","keyFormat","getDecryptData","abortRequests","_this$loader","_this$keyLoader","abort","setElementaryStreamInfo","partial","min","max","clearElementaryStreamInfo","NONE","identity","keyFormats","_this$_decryptdata","encrypted","len","Part","_BaseSegment2","partAttrs","frag","index","_this2","fragOffset","independent","audio","video","audiovideo","LevelDetails","baseUrl","PTSKnown","alignedSliding","averagetargetduration","endCC","endSN","fragments","fragmentHint","partList","dateRanges","live","ageHeader","advancedDateTime","updated","advanced","availabilityDelay","misses","startCC","startSN","startTimeOffset","targetduration","totalduration","m3u8","version","canBlockReload","canSkipUntil","canSkipDateRanges","skippedSegments","recentlyRemovedDateranges","partHoldBack","holdBack","partTarget","preloadHint","renditionReports","tuneInGoal","deltaUpdateFailed","driftStartTime","driftEndTime","driftStart","driftEnd","encryptedFragments","playlistParsingError","variableList","hasVariableRefs","reloaded","partSnDiff","lastPartSn","partIndexDiff","lastPartIndex","floor","runTime","partEnd","fragmentEnd","_this$partList","_this$fragments","now","_this$partList2","_this$partList3","undefined","sliceUint8","array","decoder","isHeader","offset","isFooter","getID3Data","front","readSize","subarray","size","canParse","getTimeStamp","frames","getID3Frames","frame","isTimeStampFrame","readTimeStamp","getFrameData","String","fromCharCode","id3Data","frameData","decodeFrame","push","decodePrivFrame","decodeURLFrame","decodeTextFrame","owner","utf8ArrayToStr","privateData","buffer","description","text","timeStampFrame","byteLength","pts33Bit","timestamp","round","exitOnNull","getTextDecoder","decoded","decode","idx","c","char2","char3","out","navigator","userAgent","includes","TextDecoder","Hex","str","h","toString","UINT32_MAX","pow","RemuxerTrackIdConfig","id3","bin2str","apply","readUint16","val","readUint32","readSint32","readUint64","result","writeUint32","findBox","results","endbox","subresults","parseSegmentIndex","sidx","references","timescale","earliestPresentationTime","firstOffset","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","parseInitSegment","traks","trak","tkhd","trackId","mdhd","hdlr","hdlrType","soun","vide","stsdData","parseStsd","_objectSpread","trex","track","default","flags","stsd","sampleEntries","sampleEntriesEnd","fourCC","codec","encBox","sinf","schm","frma","avcCBox","toHex","codecBox","esdsBox","skipBERInteger","objectType","firstByte","audioObjectType","hvcCBox","profileByte","profileSpace","generalProfileIdc","profileCompat","tierFlag","levelIDC","constraintIndicator","toUpperCase","constraintString","byte","dvcCBox","profile","addLeadingZero","vpcCBox","bitDepth","av1CBox","highBitDepth","twelveBit","monochrome","chromaSubsamplingX","chromaSubsamplingY","chromaSamplePosition","bytes","limit","x","num","patchEncyptionData","decryptdata","keyId","isCommonEncryption","encBoxes","isAudio","enc","tenc","parseSinf","tencKeyId","some","b","computeRawDurationFromSamples","trun","sampleCount","appendUint8Array","data1","data2","temp","parseSamples","timeOffset","seiSamples","videoData","samples","isHEVCFlavor","map","moof","moofOffset","byteOffset","traf","baseTime","tfdt","tfhd","tfhdFlags","defaultSampleDuration","defaultSampleSizePresent","defaultSampleSize","defaultSampleFlagsPresent","tfhdOffset","delimit","baseCodec","isHEVC","dataOffsetPresent","dataOffset","firstSampleFlagsPresent","sampleDurationPresent","sampleDuration","sampleSizePresent","sampleSize","sampleFlagsPresent","sampleCompositionOffsetsPresent","compositionOffset","trunOffset","sampleOffset","ix","naluTotalSize","naluSize","isSEIMessage","parseSEIMessageFromNALu","naluHeader","naluType","unescapedData","headerSize","pts","discardEPB","seiPtr","payloadType","payloadSize","leftOver","payPtr","providerCode","userStructure","userDataType","enabled","totalBytes","byteArray","uuidStrArray","userDataBytes","uuid","userData","EPBPositions","newLength","newData","sourceIndex","shift","LevelKey","method","uri","format","formatversions","iv","keyFormatVersions","pssh","clearKeyUriToKeyIdMap","isSupported","segmentNumber","uint8View","createInitializationVector","getMediaSource","preferManagedMediaSource","MediaSource","ManagedMediaSource","WebKitMediaSource","sampleEntryCodesISO","a3ds","alac","alaw","dra1","dtsc","dtse","dtsh","enca","fLaC","flac","FLAC","g719","g726","m4ae","mha1","mha2","mhm1","mhm2","mlpa","mp4a","Opus","opus","samr","sawb","sawp","sevc","sqcp","ssmv","twos","ulaw","avc1","avc2","avc3","avc4","avcp","av01","drac","dva1","dvav","dvh1","dvhe","encv","hev1","hvc1","mjp2","mp4v","mvc1","mvc2","mvc3","mvc4","resv","rv60","s263","svc1","svc2","vp08","vp09","stpp","wvtt","areCodecsMediaSourceSupported","codecs","isCodecMediaSourceSupported","_MediaSource$isTypeSu","isTypeSupported","mimeTypeForCodec","videoCodecPreferenceValue","videoCodec","codecsSetSelectionPreferenceValue","codecSet","reduce","preferenceValue","CODEC_COMPATIBLE_NAMES","AUDIO_CODEC_REGEXP","getCodecCompatibleName","m","lowerCaseCodec","codecsToCheck","getCodecCompatibleNameLower","toLowerCase","pickMostCompleteCodecName","parsedCodec","levelCodec","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","IS_MEDIA_PLAYLIST","LEVEL_PLAYLIST_REGEX_FAST","RegExp","source","LEVEL_PLAYLIST_REGEX_SLOW","M3U8Parser","findGroup","groups","mediaGroupId","group","resolve","isMediaPlaylist","test","parseMasterPlaylist","string","parsed","contentSteering","levels","sessionData","sessionKeys","levelsWithKnownCodecs","_level$unknownCodecs","bitrate","name","NAME","resolution","setCodecs","CODECS","unknownCodecs","tag","attributes","sessionAttrs","dataId","sessionKey","parseKey","contentSteeringAttributes","pathwayId","parseStartTimeOffset","stripUnknownCodecLevels","parseMasterPlaylistMedia","groupsByType","AUDIO","audioCodec","SUBTITLES","textCodec","TYPE","medias","lang","LANGUAGE","assocLang","channels","CHANNELS","characteristics","CHARACTERISTICS","instreamId","media","groupId","autoselect","forced","URI","groupCodec","assignCodec","parseLevelPlaylist","levelUrlId","multivariantVariableList","currentInitSegment","currentSN","currentPart","discontinuityCounter","prevFrag","firstPdtIndex","createNextFrag","nextByteRange","setFragLevelKeys","assignProgramDateTime","value1","value2","skipAttrs","unshift","dateRange","isValid","levelKey","mapAttrs","init","setInitSegment","byteRangeStartOffset","serverControlAttrs","partInfAttrs","previousFragmentPart","part","preloadHintAttrs","renditionReportAttrs","pop","fragmentLength","firstFragment","lastFragment","lastSn","fragPrev","backfillProgramDateTimes","keyTagAttributes","_keyAttrs$METHOD","_keyAttrs$KEYFORMAT","keyAttrs","decryptmethod","METHOD","decrypturi","decryptiv","decryptkeyformatversions","KEYFORMATVERSIONS","decryptkeyformat","KEYFORMAT","IV","resolvedUri","startAttributes","codecsAttributeValue","filtered","typeCodes","isCodecType","groupItem","codecProperty","codecValue","parse","endProgramDateTime","_isFiniteNumber4","BYTERANGE","PlaylistContextType","PlaylistLevelType","mapContextToLevelType","context","getResponseUrl","response","PlaylistLoader","hls","loaders","create","registerListeners","startLoad","startPosition","stopLoad","destroyInternalLoaders","on","MANIFEST_LOADING","onManifestLoading","LEVEL_LOADING","onLevelLoading","AUDIO_TRACK_LOADING","onAudioTrackLoading","SUBTITLE_TRACK_LOADING","onSubtitleTrackLoading","unregisterListeners","off","createInternalLoader","config","PLoader","pLoader","Loader","getInternalLoader","resetInternalLoader","contextType","destroy","event","load","responseType","deliveryDirectives","_context$deliveryDire","loadPolicy","levelDetails","loaderContext","manifestLoadPolicy","playlistLoadPolicy","timeoutRetry","errorRetry","details","audioTracks","subtitleTracks","targetDuration","maxLowLatencyPlaylistRefresh","maxTimeToFirstByteMs","maxLoadTimeMs","legacyRetryCompatibility","loaderConfig","timeout","maxRetry","maxNumRetry","retryDelay","retryDelayMs","maxRetryDelay","maxRetryDelayMs","loaderCallbacks","onSuccess","networkDetails","performance","handleTrackOrLevelPlaylist","handleMasterPlaylist","handleManifestParsingError","onError","handleNetworkError","onTimeout","parsedResult","_M3U8Parser$parseMast","_M3U8Parser$parseMast2","subtitles","captions","audioTrack","trigger","MANIFEST_LOADED","levelId","levelType","singleLevel","handlePlaylistLoaded","ERROR","NETWORK_ERROR","MANIFEST_PARSING_ERROR","fatal","err","reason","message","code","UNKNOWN","MANIFEST_LOAD_TIMEOUT","MANIFEST_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","AUDIO_TRACK_LOAD_ERROR","SUBTITLE_TRACK_LOAD_TIMEOUT","SUBTITLE_LOAD_ERROR","errorData","parent","levelIndex","LEVEL_PARSING_ERROR","getCacheAge","isNaN","LEVEL_LOADED","AUDIO_TRACK_LOADED","SUBTITLE_TRACK_LOADED","LEVEL_EMPTY_ERROR","sendAddTrackEvent","videoEl","Event","document","createEvent","initEvent","dispatchEvent","removeCuesInRange","predicate","mode","cues","cuesFound","firstCueInRange","time","startTime","endTime","left","right","mid","getFirstCueIndexAfterTime","cue","getCuesInRange","removeCue","MetadataSchema","getCueClass","VTTCue","TextTrackCue","createCueWithDataFields","Cue","JSON","stringify","MAX_CUE_ENDTIME","POSITIVE_INFINITY","MAX_VALUE","dateRangeDateToTimelineSeconds","date","ID3TrackController","id3Track","dateRangeCuesAppended","_registerListeners","_unregisterListeners","MEDIA_ATTACHED","onMediaAttached","MEDIA_DETACHING","onMediaDetaching","FRAG_PARSING_METADATA","onFragParsingMetadata","BUFFER_FLUSHING","onBufferFlushing","LEVEL_UPDATED","onLevelUpdated","clearCurrentCues","createTrack","getID3Track","textTracks","textTrack","kind","label","addTextTrack","_this$hls$config","enableEmsgMetadataCues","enableID3MetadataCues","ID3","j","updateId3CueEnds","addCue","_this$id3Track","_ref","startOffset","endOffset","_hls$config","_ref2","hasProgramDateTime","enableDateRangeMetadataCues","ids","idsToRemove","_loop","dateTimeOffset","_loop2","appendedDateRangeCues","durationKnown","nextDateRangeWithSameClass","candidateDateRange","otherDateRange","from","LatencyController","currentTime","stallCount","_latency","timeupdateHandler","timeupdate","addEventListener","removeEventListener","_this$levelDetails","BUFFER_STALLED_ERROR","latency","computeLatency","_this$config","lowLatencyMode","maxLiveSyncPlaybackRate","targetLatency","distanceFromTarget","maxLatency","forwardBufferLength","rate","exp","edgeStalled","playbackRate","estimateLiveEdge","edge","age","liveEdge","liveMaxLatencyDuration","liveMaxLatencyDurationCount","_this$config2","liveSyncDuration","liveSyncDurationCount","userConfig","maxLiveSyncOnStallIncrease","syncPosition","drift","maxLevelUpdateAge","bufferedRanges","buffered","HdcpLevels","VideoRangeValues","HlsSkip","getSkipValue","HlsUrlParameters","msn","skip","addDirectives","URL","searchParams","href","Level","_attrs","frameRate","fragmentError","loadError","realBitrate","supportedPromise","supportedResult","_avgBitrate","_audioGroups","_subtitleGroups","_urlId","s","addGroupId","hasAudioGroup","hasGroup","hasSubtitleGroup","audioGroups","subtitleGroups","addFallback","audioGroupId","textGroupId","_this$audioGroups","_this$subtitleGroups","updateFromToPTS","fragFrom","fragTo","fragToPTS","updateFragPTSDTS","fragStartPts","fragEndPts","fragIdx","mergeDetails","oldDetails","newDetails","oldFragments","oldInit","PTSFrag","oldDateRanges","deltaDateRanges","ccOffset","intersectionFn","delta","newFrags","concat","oldFrags","oldFrag","newFrag","mapFragmentIntersection","_isFiniteNumber5","_currentInitSegment","newFragments","oldParts","newParts","oldPart","newPart","mapPartIntersection","adjustSliding","addSliding","getPartWith","partIndex","_level$details","findPart","reassignFragmentLevelIndexes","isTimeoutError","FRAG_LOAD_TIMEOUT","KEY_LOAD_TIMEOUT","getRetryConfig","isTimeout","getRetryDelay","retryConfig","retryCount","backoffFactor","backoff","getLoaderConfigWithoutReties","loderConfig","shouldRetry","loaderResponse","httpStatus","onLine","retryForHttpStatus","BinarySearch","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","findFragmentByPTS","fragPrevious","bufferEnd","maxFragLookUpTolerance","nextFragLookupTolerance","fragNext","bufferEdgeError","fragmentWithinToleranceTest","firstDuration","fragmentWithinFastStartSwitch","foundFragment","candidate","candidateLookupTolerance","pdtWithinToleranceTest","pdtBufferEnd","NetworkErrorAction","ErrorActionFlags","ErrorController","playlistError","penalizedRenditions","onErrorOut","getVariantLevelIndex","loadLevel","_data$frag","_data$level","FRAG_LOAD_ERROR","KEY_LOAD_ERROR","errorAction","getFragRetryOrSwitchAction","FRAG_PARSING_ERROR","action","FRAG_GAP","FRAG_DECRYPT_ERROR","_data$context","_data$context$levelDe","getPlaylistRetryOrSwitchAction","levelRetry","getLevelSwitchAction","KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED","restrictedHdcpLevel","hdcpLevel","keySystemError","BUFFER_ADD_CODEC_ERROR","REMUX_ALLOC_ERROR","BUFFER_APPEND_ERROR","INTERNAL_EXCEPTION","BUFFER_APPENDING_ERROR","BUFFER_FULL_ERROR","LEVEL_SWITCH_ERROR","BUFFER_SEEK_OVER_HOLE","BUFFER_NUDGE_ON_STALL","KEY_SYSTEM_ERROR","variantLevelIndex","fragLoadPolicy","keyLoadPolicy","startsWith","fragmentErrors","acc","_data$frag2","_data$context2","errorDetails","nextLevel","minAutoLevel","maxAutoLevel","autoLevelEnabled","_ret","fragErrorType","findAudioCodecAlternate","sourceBufferName","findVideoCodecAlternate","_ref3","playlistErrorType","playlistErrorGroupId","_level$audioGroups","_level$subtitleGroups","levelCandidate","fragCandidate","nextAutoLevel","_data$errorAction","sendAlternateToPenaltyBox","resolved","recoverMediaError","switchLevel","maxHdcpLevel","nextLoadLevel","BasePlaylistController","logPrefix","timer","requestScheduled","canLoad","clearTimer","clearTimeout","loadPlaylist","switchParams","playlistUri","current","foundIndex","currentGoal","hlsUrlParameters","shouldLoadPlaylist","playlist","shouldReloadPlaylist","playlistLoaded","previousDetails","elapsed","endSn","lastPart","lastAdvanced","cdnAge","segments","toFixed","getDeliveryDirectives","bufferInfo","mainForwardBufferInfo","position","reloadInterval","distanceToLiveEdgeMs","lastSegmentDuration","computeReloadInterval","estimatedTimeUntilUpdate","setTimeout","previousDeliveryDirectives","checkRetry","errorEvent","_ref$retryCount","_errorEvent$context","delay","EWMA","halfLife","estimate","weight","alpha_","estimate_","totalWeight_","sample","adjAlpha","getTotalWeight","getEstimate","zeroFactor","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultTTFB","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","defaultTTFB_","ttfb_","update","durationMs","numBytes","durationS","bandwidthInBps","sampleTTFB","ttfb","seconds","sqrt","canEstimate","getEstimateTTFB","getVideoSelectionOptions","currentVideoRange","videoPreference","preferHDR","allowedVideoRanges","matchMedia","mediaQueryList","badQuery","matches","isHdrSupported","range","logStartCodecCandidateIgnored","codeSet","AbrController","lastLevelLoadSec","lastLoadedFragLevel","firstSelection","_nextAutoLevel","nextAutoLevelKey","audioTracksByGroup","codecTiers","fragCurrent","partCurrent","bitrateTestDelay","bwEstimator","_abandonRulesCheck","timeLoading","paused","readyState","ttfbEstimate","bufferStarvationDelay","loadedFirstByte","getBwEstimate","expectedLen","averageBitrate","timeStreaming","loadRate","fragLoadedDelay","bwe","fragLevelNextLoadedDelay","levelNextBitrate","maxBitrate","getTimeToLoadFrag","nextLoadLevelBitrate","abrBandWidthUpFactor","resetEstimator","FRAG_LOAD_EMERGENCY_ABORTED","initEstimator","abrEwmaDefaultEstimate","abrEwmaSlowVoD","abrEwmaFastVoD","FRAG_LOADING","onFragLoading","FRAG_LOADED","onFragLoaded","FRAG_BUFFERED","onFragBuffered","LEVEL_SWITCHING","onLevelSwitching","onLevelLoaded","LEVELS_UPDATED","onLevelsUpdated","MAX_AUTO_LEVEL_UPDATED","onMaxAutoLevelUpdated","_data$part","ignoreFragment","setInterval","timeToFirstByteSec","bandwidth","fragSizeBits","isSwitch","timeLoadingMs","abrEwmaSlowLive","abrEwmaFastLive","abrMaxWithRealBitrate","loadedBytes","loadedDuration","fragBufferedData","processingMs","clearInterval","getAutoLevelKey","getStarvationDelay","getNextABRAutoLevel","currentFragDuration","avgbw","bwFactor","abrBandWidthFactor","bwUpFactor","bestLevel","findBestLevel","maxStarvationDelay","maxLoadingDelay","minLevel","autoLevel","currentBw","maxFetchDuration","selectionBaseLevel","firstLevel","_this$hls","allAudioTracks","currentCodecSet","currentFrameRate","audioPreference","trackGroup","tracks","hasDefault","hasAutoSelect","channelsKey","hasDefaultAudio","hasAutoSelectAudio","getAudioTracksByGroup","tiers","tier","minBitrate","minHeight","minFramerate","maxScore","videoRanges","SDR","lesserWidthOrHeight","score","videoRange","getCodecTiers","startTier","codecSets","channelsPreference","audioCodecPreference","preferStereo","hasStereo","hasCurrentVideoRange","selectedScore","_getVideoSelectionOpt","matchingVideoRanges","maxHeight","maxFramerate","selected","candidateTier","getStartCodecTier","ttfbEstimateSec","levelsSkipped","_levelInfo$supportedR","levelInfo","upSwitch","decodingInfoResults","smooth","adjustedbw","avgDuration","fetchDuration","forcedAutoLevel","v","_this$hls2","maxStartDelay","abrAutoLevel","clamped","useEstimate","loadedFirstFrag","nextABRAutoLevel","firstAutoLevel","_this$hls3","noopBuffered","BufferHelper","isBuffered","getBuffered","pos","maxHoleDuration","vbuffered","bufferedInfo","nextStart","sort","a","diff","buffered2","buf2len","buf2end","bufferStartNext","bufferLen","bufferStart","BufferOperationQueue","sourceBufferReference","buffers","queues","append","operation","pending","queue","executeNext","insertAbort","appendBlocker","execute","promise","Promise","onStart","onComplete","sb","updating","shiftAndExecuteNext","VIDEO_CODEC_PROFILE_REPLACE","BufferController","_objectUrl","operationQueue","listeners","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","lastMpegAudioChunk","appendSource","appendErrors","pendingTracks","sourceBuffer","_onEndStreaming","pauseBuffering","_onStartStreaming","resumeBuffering","_onMediaSourceOpen","_onMediaEmptied","updateMediaElementDuration","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","mediaSrc","_initSourceBuffer","hasSourceTypes","getSourceBufferTypes","MEDIA_ATTACHING","onMediaAttaching","MANIFEST_PARSED","onManifestParsed","BUFFER_RESET","onBufferReset","BUFFER_APPENDING","onBufferAppending","BUFFER_CODECS","onBufferCodecs","BUFFER_EOS","onBufferEos","FRAG_PARSED","onFragParsed","FRAG_CHANGED","onFragChanged","codecEvents","altAudio","_ms$constructor","ms","constructor","objectUrl","createObjectURL","removeAttribute","MMS","disableRemotePlayback","removeSourceChildren","createElement","src","appendChild","addSource","endOfStream","revokeObjectURL","MEDIA_DETACHED","resetBuffer","_this$mediaSource","removeBufferListeners","sourceBuffers","removeSourceBuffer","_this3","sourceBufferCount","trackNames","trackName","changeType","_trackCodec","_data$trackName","container","metadata","currentCodecFull","currentCodec","trackCodec","nextCodec","mimeType","appendChangeType","_this4","eventData","_this5","chunkMeta","chunkStats","bufferAppendingStart","fragBuffering","partBuffering","checkTimestampOffset","fragStart","executeStart","timestampOffset","appendExecutor","executeEnd","timeRanges","BUFFER_APPENDED","MEDIA_ERROR","DOMException","QUOTA_EXCEEDED_ERR","appendErrorCount","appendErrorMaxRetry","_this6","flushOperation","removeExecutor","BUFFER_FLUSHED","_this7","buffersAppendedTo","blockBuffers","trimBuffers","_this8","ending","ended","levelTargetDuration","backBufferLength","liveBackBufferLength","maxBackBufferLength","targetBackBufferPosition","flushBackBuffer","frontBufferFlushThreshold","frontBufferLength","maxBufferLength","maxFrontBufferLength","targetFrontBufferPosition","flushFrontBuffer","_this9","BACK_BUFFER_REACHED","LIVE_BACK_BUFFER_REACHED","_this10","numBufferedRanges","levelDuration","mediaDuration","msDuration","liveDurationInfinity","updateSeekableRange","setLiveSeekableRange","pendingTracksCount","createSourceBuffers","BUFFER_CREATED","BUFFER_INCOMPATIBLE_CODECS_ERROR","_this11","_track$levelCodec","addSourceBuffer","sbName","addBufferListener","_onSBUpdateStart","_onSBUpdateEnd","_onSBUpdateError","removedRanges","_this$mediaSource2","_this$mediaSource3","_isFiniteNumber6","removeStart","removeEnd","remove","appendBuffer","onUnblocked","_this12","then","blockingOperations","all","fn","listener","l","_this$media","_this$media$querySele","querySelector","node","sourceChildren","querySelectorAll","removeChild","CapLevelController","autoLevelCapping","restrictedLevels","clientRect","streamController","setStreamController","unregisterListener","stopCapping","FPS_DROP_LEVEL_CAPPING","onFpsDropLevelCapping","droppedLevel","isLevelAllowed","HTMLVideoElement","detectPlayerSize","capLevelToPlayerSize","startCapping","mediaHeight","mediaWidth","maxLevel","getMaxLevel","nextLevelSwitch","capLevelIndex","validLevels","getMaxLevelByMediaSize","getDimensions","boundsRect","getBoundingClientRect","bottom","top","restrictedLevel","curLevel","maxLevelIndex","squareSize","contentScaleFactor","pixelRatio","ignoreDevicePixelRatio","devicePixelRatio","FPSController","isVideoPlaybackQualityAvailable","lastTime","lastDroppedFrames","lastDecodedFrames","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","currentPeriod","currentDropped","currentDecoded","droppedFPS","FPS_DROP","totalDroppedFrames","fpsDroppedMonitoringThreshold","currentLevel","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","ContentSteeringController","pathwayPriority","timeToLoad","reloadTimer","started","penalizedPathways","onManifestLoaded","ttl","scheduleRefresh","loadSteeringManifest","removeLevel","levelToRemove","errorPathway","getPathwayForGroupId","pathways","updatePathwayPriority","filterParsedLevels","pathwayLevels","getLevelsForPathway","selectedIndex","selectedLevel","levelAfterChange","defaultPathway","clonePathways","pathwayClones","audioGroupCloneMap","subtitleGroupCloneMap","pathwayClone","cloneId","baseId","uriReplacement","clonedVariants","baseLevel","clonedAudioGroupId","clonedSubtitleGroupId","performUriReplacement","clonedLevel","cloneRenditionGroups","protocol","throughput","bandwidthEstimate","steeringManifestLoadPolicy","callbacks","steeringData","VERSION","TTL","reloadUri","loadedSteeringData","steeringManifest","STEERING_MANIFEST_LOADED","getResponseHeader","retryAfter","ttlMs","_this3$hls","groupCloneMap","clonedTracks","clonedTrack","stableId","perOptionKey","perVariantUri","host","HOST","PARAMS","perOptionUris","AGE_HEADER_LINE_REGEX","XhrLoader","xhrSetup","requestTimeout","retryTimeout","abortInternal","onreadystatechange","onprogress","_this$callbacks","onAbort","loadInternal","xhr","XMLHttpRequest","catch","open","openAndSendXhr","status","headers","_config$loadPolicy","header","setRequestHeader","rangeEnd","rangeStart","readystatechange","loadprogress","loadtimeout","send","useResponse","responseText","onProgress","responseURL","statusText","_this$context","lengthComputable","getAllResponseHeaders","ChunkCache","chunks","dataLength","chunk","flush","concatUint8Arrays","reset","FetchLoader","fetchSetup","request","controller","getRequest","AbortController","initParams","signal","credentials","Headers","getRequestParameters","isArrayBuffer","LENGTH","fetch","ok","FetchError","contentRange","byteRangeLength","byteRangeHeader","getByteRangeLength","contentLength","getContentLength","highWaterMark","loadProgressively","arrayBuffer","json","responseData","chunkCache","reader","body","getReader","pump","read","done","ArrayBuffer","reject","Request","chromeOrFirefox","_Error","_wrapNativeSuper","hlsDefaultConfig","autoStartLoad","defaultAudioCodec","initialLiveManifestSize","maxBufferSize","maxBufferHole","highBufferWatchdogPeriod","nudgeOffset","nudgeMaxRetry","maxMaxBufferLength","enableWorker","workerPath","enableSoftwareAES","startLevel","startFragPrefetch","fLoader","licenseXhrSetup","licenseResponseCallback","abrController","bufferController","capLevelController","errorController","fpsController","stretchShortVideoTrack","maxAudioFramesDrift","forceKeyFrameOnDiscontinuity","abrEwmaDefaultEstimateMax","minAutoBitrate","emeEnabled","widevineLicenseUrl","drmSystems","drmSystemOptions","requestMediaKeySystemAccessFunc","testBandwidth","progressive","cmcd","useMediaCapabilities","certLoadPolicy","manifestLoadingTimeOut","manifestLoadingMaxRetry","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","fragLoadingTimeOut","fragLoadingMaxRetry","fragLoadingRetryDelay","fragLoadingMaxRetryTimeout","cueHandler","Cues","enableWebVTT","enableIMSC1","enableCEA708Captions","captionsTextTrack1Label","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","captionsTextTrack3Label","captionsTextTrack3LanguageCode","captionsTextTrack4Label","captionsTextTrack4LanguageCode","renderTextTracksNatively","subtitleStreamController","subtitleTrackController","timelineController","audioStreamController","audioTrackController","emeController","cmcdController","contentSteeringController","deepCpy","obj","isArray","enableStreamingMode","currentLoader","ReadableStream","fetchSupported","LevelController","_BasePlaylistControll","_levels","_firstLevel","_maxAutoLevel","_startLevel","currentLevelIndex","manualLevelIndex","steering","onParsedComplete","resetLevels","redundantSet","generatePathwaySet","resolutionFound","videoCodecFound","audioCodecFound","levelParsed","_audioCodec","_videoCodec","avcdata","convertAVC1ToAVCOTI","FRAMERATE","HDCP","PATHWAY","RESOLUTION","VIDEO_RANGE","pathwayCount","filterAndSortMediaOptions","filteredLevels","assignTrackIdsByGroup","unsortedLevels","valueA","valueB","firstLevelInPlaylist","_this$hls$userConfig","firstLevelBitrate","startingBwEstimate","audioOnly","edata","t","forceStartLoad","MANIFEST_INCOMPATIBLE_CODECS_ERROR","el","_data$deliveryDirecti2","_data$deliveryDirecti","_this$currentLevel","f","checkMaxAutoUpdated","newLevel","OTHER_ERROR","lastLevelIndex","lastLevel","lastPathwayId","levelSwitchingData","audioGroupIds","textGroupIds","configStartLevel","FragmentState","FragmentTracker","activePartLists","endListFragments","bufferPadding","hasGaps","onBufferAppended","getAppendedFrag","activeParts","activePart","appendedPTS","getBufferedFrag","fragmentEntity","detectEvictedFragments","elementaryStream","timeRange","playlistType","appendedPart","appendedPartSn","esData","isNotBuffered","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","isFragHint","streamInfo","getBufferedTimes","isPartial","removeParts","snToKeep","fragBuffered","force","getPartialFragment","timePadding","bestFragment","bestOverlap","isEndListAppended","lastFragmentEntity","getState","hasFragment","hasParts","_this$activePartLists","removeFragmentsInRange","withGapOnly","unbufferedOnly","snToRemove","removeAllFragments","_fragmentEntity$range","_fragmentEntity$range2","_fragmentEntity$range3","MIN_CHUNK_SIZE","FragmentLoader","partLoadTimeout","LoadError","FragmentILoader","DefaultILoader","tags","createGapLoadError","createLoaderContext","resetLoader","payload","resetIV","INTERNAL_ABORTED","loadPart","updateStatsFromPart","partLoadedData","fragStats","partStats","partTotal","estTotalParts","estLoadedParts","estRemainingBytes","fragLoading","partLoading","segment","_frag$decryptdata","byteRangeStart","byteRangeEnd","fragmentLen","KeyLoader","keyUriToKeyInfo","_loader$context","detach","keyInfo","mediaKeySessionContext","createKeyLoadError","loadClear","loadingFrag","selectKeySystemFormat","keySystemFormat","_keyInfo","_keyInfo2","_keyInfo$mediaKeySess","keyLoadPromise","keyStatus","keyLoadedData","loadKeyHTTP","loadKeyEME","keySessionContextPromise","loadKey","keySessionContext","TaskLoop","_boundTick","_tickTimer","_tickInterval","_tickCallCount","tick","onHandlerDestroying","onHandlerDestroyed","clearNextTick","hasInterval","hasNextTick","millis","doTick","tickImmediate","ChunkMetadata","transmuxing","findFirstFragWithCC","_fragments$i","adjustFragmentStart","sliding","adjustSlidingStart","alignStream","lastFrag","switchDetails","shouldAlignOnDiscontinuities","referenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","findDiscontinuousReferenceFrag","alignDiscontinuities","refDetails","refFrag","refFragments","targetCC","refPDT","targetPDT","alignMediaPlaylistByPDT","AESCrypto","subtle","aesIV","decrypt","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","ksRows","keySize","keySchedule","invKeySchedule","initTable","uint8ArrayToUint32Array_","view","DataView","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","d","xi","sx","x2","x4","x8","keyBuffer","sameKey","ksRow","invKsRow","prev","sbox","networkToHostOrderSwap","word","inputArrayBuffer","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","swapWord","Decrypter","_temp","_ref$removePKCS7Paddi","removePKCS7Padding","logEnabled","softwareDecrypter","fastAesKey","remainderData","currentIV","currentResult","useSoftware","browserCrypto","crypto","webkitSubtle","isSync","outputBytes","paddingBytes","getUint8","softwareDecrypt","decryptResult","webCryptoDecrypt","logOnce","currentChunk","getValidChunk","onWebCryptoError","aesKey","splitPoint","msg","TimeRanges","r","State","BaseStreamController","_TaskLoop","fragmentTracker","transmuxer","_state","mediaBuffer","lastCurrentTime","nextLoadPosition","loadedmetadata","retryDate","fragmentLoader","levelLastLoaded","startFragRequested","decrypter","initPTS","onvseeking","onvended","_assertThisInitialized","onTickEnd","resetTransmuxer","state","_streamEnded","getLevelDetails","_this$levelLastLoaded","onMediaSeeking","onMediaEnded","resetLoadingState","tolerance","fragStartOffset","fragEndOffset","pastFragment","loadFragment","targetBufferTime","_loadFragForPlayback","_doFragLoad","fragContextChanged","_handleFragmentLoadProgress","_handleFragmentLoadComplete","resetFragmentLoading","clearTrackerIfNeeded","_this$mediaBuffer","getFwdBufferInfo","minForwardBufferLength","backtrackFragment","reduceMaxBufferLength","checkLiveUpdate","flushMainBuffer","flushScope","_loadInitSegment","decryptData","decryptedData","FRAG_DECRYPTED","tstart","tdecrypt","completeInitSegmentLoad","fragBufferedComplete","_frag$startPTS","_frag$endPTS","_this$fragCurrent","_this$fragPrevious","NaN","_this$levels","seekToStartPos","fragLoadedEndData","partsLoaded","complete","fragLoaded","progressCallback","keyLoadingPromise","KEY_LOADED","KEY_LOADING","getNextPart","doFragPartsLoad","handleFragLoadError","loadedEndOfParts","dataOnProgress","fragLoadedData","fromPart","initialPartList","loadedPart","nextPart","handleFragLoadAborted","_handleTransmuxerFlush","getCurrentContext","updateLevelTiming","getFragmentWithSN","bufferFragmentData","noBacktracking","_buffer","dropped","flushBufferGap","fragDuration","segmentFraction","bufferable","getLoadPosition","getFwdBufferInfoAtPos","bufferedFragAtPos","getMaxBufferLength","levelBitrate","maxBufLen","threshold","minLength","reducedLength","fragOrPart","getNextFragment","fragLen","getInitialLiveFragment","liveSyncPosition","getFragmentAtPosition","mapToInitFragWhenRequired","isLoopLoading","trackerState","getNextFragmentLoopLoading","gapStart","nextFragment","nextbufferInfo","contiguous","independentAttrOmitted","PDTValue","seg","findFragmentByPDT","targetSN","findFragWithCC","liveStart","loadingParts","curSNIdx","fragState","nextFrag","synchronizeToLiveEdge","withinSlidingWindow","alignPlaylists","slidingStart","firstLevelLoad","aligned","alignedSlidingStart","waitForCdnTuneIn","setStartPosition","offsetInMultivariantPlaylist","onFragmentOrKeyLoadError","filterType","_this$fragCurrent2","gapTagEncountered","_ref2$retryCount","resetStartWhenNotLoaded","resetFragmentErrors","reduceLengthAndFlushBuffer","flushBuffer","afterBufferFlushed","bufferType","bufferedTimeRanges","resetWhenMissingContext","removeUnbufferedFrags","_this$transmuxer","parsedDuration","LEVEL_PTS_UPDATED","recoverWorkerError","nextState","previousState","getSourceBuffer","SourceBuffer","WebKitSourceBuffer","isMSESupported","dummyTrack","inputTimeScale","pid","sequenceNumber","BaseAudioDemuxer","_audioTrack","_id3Track","frameIndex","cachedData","basePTS","lastPTS","resetInitSegment","trackDuration","resetTimeStamp","deaultTimestamp","resetContiguity","appendFrame","demux","lastDataIndex","initPTSFn","dts","partialData","videoTrack","demuxSampleAes","keyData","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","headerLength","frameLength","newOffset","initTrackConfig","observer","samplerate","adtsObjectType","adtsExtensionSamplingIndex","adtsChannelConfig","manifestCodec","adtsSamplingRates","adtsSamplingIndex","channelCount","emit","getAudioConfig","getFrameDuration","unit","stamp","parseFrameHeader","missing","chromeVersion","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","mpegVersion","mpegLayer","bitRateIndex","sampleRateIndex","paddingBit","channelMode","bitRate","sampleCoefficient","bytesInSlot","AACDemuxer","_BaseAudioDemuxer","segmentCodec","MpegAudio","ADTS","canGetFrameLength","emsgSchemePattern","MP4Demuxer","txtTrack","captionTrack","initData","_initData$video","_initData$audio","hasMoofData","videoSamples","segmentedData","segmentedRange","valid","remainder","moofs","last","segmentValidRange","extractID3Track","emsgs","emsgInfo","schemeIdUri","timeScale","presentationTimeDelta","presentationTime","eventDuration","leftPresentationTime","rightPresentationTime","_isSafeInteger","parseEmsg","BaseVideoParser","VideoSample","createVideoSample","units","getLastNalUnit","_VideoSample","lastUnit","pushAccessUnit","nbSamples","lastSample","ExpGolomb","bytesAvailable","bitsAvailable","loadWord","workingBytes","availableBytes","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","readUByte","readUShort","readUInt","skipScalingList","lastScale","nextScale","readSPS","numRefFramesInPicOrderCntCycle","scalingListCount","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","profileIdc","chromaFormatIdc","picOrderCntType","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","ceil","readSliceType","AvcVideoParser","_BaseVideoParser","parseAVCPES","pes","parseAVCNALu","spsfound","audFound","_VideoSample2","iskey","sliceType","_track$pixelRatio","_track$pixelRatio2","sps","codecarray","codecstring","pps","overflow","naluState","lastState","lastUnitStart","lastUnitType","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","callback","curUnit","encryptedBuffer","decryptedBuffer","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","uint8DecryptedData","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","PACKET_LENGTH","TSDemuxer","typeSupported","sampleAes","pmtParsed","_duration","_pmtId","_videoTrack","_txtTrack","aacOverFlow","videoParser","syncOffset","scanwindow","foundPat","packetStart","tsPackets","parsePID","pesData","isSampleAes","videoPid","audioPid","id3Pid","audioData","unknownPID","pmtId","tsPacketErrors","stt","parsePES","parseAACPES","parseMPEGPES","parseID3PES","parsePAT","parsedPIDs","parsePMT","segmentVideoCodec","segmentAudioCodec","emitParsingError","demuxResult","extractRemainingSamples","frameMissingBytes","sampleLength","frameOverflowBytes","recoverable","frameDuration","parseAC3PES","id3Sample","tableEnd","esInfoLength","logEncryptedSamplesFoundInUnencryptedStream","mpeg","mp3","parsePos","remaining","descriptorLen","stream","pesLen","pesHdrLen","pesPts","pesDts","splice","pesFlags","payloadStartOffset","dataLen","MP3Demuxer","bsid","numBits","mask","getAudioBSID","AAC","getSilentFrame","MP4","types","avcC","btrt","dinf","dref","esds","ftyp","mdat","mdia","mfhd","minf","moov","dac3","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsz","stts","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","upperWordDuration","lowerWordDuration","baseMediaDecodeTime","boxes","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","audioStsd","ac3","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","cts","arraylen","isLeading","paddingValue","isNonSync","degradPrio","movie","toMsFromMpegTsClock","destScale","srcBase","toTimescaleFromBase","safariWebkitVersion","MP4Remuxer","vendor","ISGenerated","_initPTS","_initDTS","nextAvcDts","nextAudioPts","videoSampleDuration","isAudioContiguous","isVideoContiguous","videoTrackConfig","defaultTimeStamp","resetNextTimestamp","getVideoStartPts","rolloverDetected","minPTS","normalizePts","remux","accurateTimeOffset","audioTimeOffset","videoTimeOffset","hasAudio","hasVideo","enoughAudioSamples","enoughVideoSamples","_videoTrack$pixelRati","_config$pixelRatio","_videoTrack$pixelRati2","_config$pixelRatio2","generateIS","firstKeyFramePTS","firstKeyFrameIndex","findKeyframeIndex","audiovideoTimestampDelta","remuxAudio","audioTrackLength","remuxVideo","firstKeyFrame","flushTextTrackMetadataCueSamples","flushTextTrackUserdataCueSamples","initDTS","audioSamples","computePTSDTS","firstDTS","lastDTS","inputSamples","outputSamples","mp4SampleDuration","maxPTS","NEGATIVE_INFINITY","sortSamples","initTime","deltadts","deltapts","inputDuration","averageSampleDuration","foundHole","foundOverlap","firstPTS","nbNalu","naluLen","dtsStep","nbUnits","sampleLen","mdatSize","MUX_ERROR","setUint32","stretchedLastFrame","minDtsDelta","minPtsDelta","maxDtsDelta","maxPtsDelta","VideoSampleUnits","mp4SampleLength","unitData","unitDataLen","ptsDelta","lastFrameDuration","gapTolerance","deltaToFrameEnd","compositionTimeOffset","Mp4Sample","nextDts","nextPts","nb","getSamplesPerFrame","scaleFactor","inputSampleDuration","rawMPEG","alignedWithVideo","timeOffsetMpegTS","newStamp","fillFrame","audioSample","unitLen","remuxEmptyAudio","init90kHz","silentFrame","reference","isKeyframe","PassThroughRemuxer","emitInitSegment","initTracks","lastEndTime","defaultInitPTS","generateInitSegment","getParsedTrackCodec","_initData","_initData2","rawDuration","videoDuration","audioDuration","trafs","trackDefault","truns","sidxMinStart","sidxMaxEnd","sidxDuration","sidxs","subSegmentDuration","dur","ref","getDuration","fmp4","getStartDTS","decodeTime","minDuration","isInvalidInitPts","upper","lower","offsetStartDTS","optionalSelf","muxConfig","Transmuxer","async","demuxer","remuxer","decryptionPromise","transmuxConfig","currentTransmuxState","configure","uintData","discontinuity","trackSwitch","initSegmentChange","defaultInitPts","initSegmentData","encryptionType","getEncryptionType","getDecrypter","emptyResult","resetMuxers","needsProbing","configureTransmuxer","resetInitialTimestamp","transmux","currentState","transmuxResults","demuxResultOrPromise","isPromise","flushRemux","_this$currentTransmux","remuxResult","transmuxSampleAes","transmuxUnencrypted","_demux","mux","_muxConfig$i$demux","Remuxer","Demuxer","p","Function","TransmuxConfig","TransmuxState","has","prefix","EE","once","addListener","emitter","TypeError","evt","_events","_eventsCount","clearEvent","EventEmitter","__proto__","eventNames","events","names","getOwnPropertySymbols","handlers","ee","listenerCount","a1","a2","a3","a4","a5","args","removeListener","removeAllListeners","prefixed","emitTransmuxComplete","transmuxResult","transferable","_transmuxResult$remux","addToTransferable","postMessage","handleFlushResult","__IN_WORKER__","forwardMessage","ev","forwardWorkerLogs","logFn","logType","cmd","startWorker","TransmuxerInterface","onTransmuxComplete","onFlush","useWorker","workerContext","onwmsg","blob","objectURL","scriptURL","m2tsTypeSupported","Worker","location","worker","Blob","__HLS_WORKER_BUNDLE__","onWorkerMessage","onerror","filename","lineno","resetWorker","_this$workerContext","terminate","_frag$initSegment","_lastFrag$initSegment","snDiff","partDiff","handleTransmuxComplete","transmuxerError","_this$workerContext2","GapController","nudgeRetry","stallReported","stalled","moved","seeking","poll","activeFrag","seeked","beginSeek","hasEnoughBuffer","noBufferGap","startJump","maxStartGapJump","partialOrGap","_trySkipBufferHole","tnow","stalledDuration","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","_tryNudgeBuffer","bufferStarved","waiting","gapLength","startGap","startFrag","startProvisioned","moreToLoad","provisioned","targetTime","StreamController","_BaseStreamController","audioCodecSwap","gapController","_forceStartLoad","fragPlaying","onvplaying","onvseeked","fragLastKbps","couldBacktrack","audioCodecSwitch","videoBuffer","onFragLoadEmergencyAborted","AUDIO_TRACK_SWITCHING","onAudioTrackSwitching","AUDIO_TRACK_SWITCHED","onAudioTrackSwitched","onBufferCreated","onBufferFlushed","doTickIdle","checkBuffer","checkFragmentChanged","getMainFwdBufferInfo","lastDetails","manualLevel","_this$backtrackFragme","backtrackFrag","_loadBitrateTestFrag","followingBufferedFrag","immediateLevelSwitch","abortCurrentFrag","fetchdelay","fragPlayingCurrent","bufferedFrag","nextBufferedFrag","maxStart","startPts","onMediaPlaying","onMediaSeeked","_sourceBuffer$prototy","aac","heaac","_curLevel$details","newLevelId","_getAudioCodec","_handleTransmuxComplete","fromAltAudio","mediaTrack","alternate","swapAudioCodec","_id3$samples","mapFragment","_bufferInitSegment","FRAG_PARSING_INIT_SEGMENT","INIT_PTS_FOUND","isFirstFragment","isFirstInDiscontinuity","backtrack","emittedID3","emittedText","FRAG_PARSING_USERDATA","ua","audioMetadata","fragCurrentLevel","LEVEL_SWITCHED","currentFrag","epocMs","Hls","coreComponents","networkControllers","_emitter","_autoLevelCapping","_maxHdcpLevel","latencyController","levelController","_media","triggeringException","defaultConfig","defaultsCopy","deprecatedSettings","policyName","policyNotSet","report","setting","deprecatedSetting","settings","mergeConfig","DefaultConfig","ConfigAbrController","ConfigBufferController","ConfigCapLevelController","ConfigErrorController","ConfigFpsController","playListLoader","id3TrackController","ConfigContentSteeringController","createController","AudioStreamControllerClass","SubtitleStreamControllerClass","codecsForVideoContainer","codecForAudioContainer","ControllerClass","components","controllerInstance","eventObject","DESTROYING","detachMedia","component","attachMedia","loadSource","loadedSource","loadingSource","setAudioOption","audioOption","_this$audioTrackContr","setSubtitleOption","subtitleOption","_this$subtitleTrackCo","shouldStartCapping","newCapLevelToPlayerSize","isHdcpLevel","currentProgramDateTime","audioTrackId","allSubtitleTracks","subtitleTrack","subtitleTrackId","subtitleDisplay"],"mappings":"8+FAEA,IACMA,EAEAC,EACAC,EACAC,EAEAC,EANAJ,EACF,iIACEC,EAAsB,2BACtBC,EAAkB,oBAClBC,EAAsB,wCAEtBC,EAAa,CAOfC,iBAAkB,SAAUC,EAASC,EAAaC,GAKhD,GAJAA,EAAOA,GAAQ,GAEfF,EAAUA,EAAQG,SAClBF,EAAcA,EAAYE,QACR,CAIhB,IAAKD,EAAKE,gBACR,OAAOJ,EAET,IAAIK,EAAwBP,EAAWQ,SAASN,GAChD,IAAKK,EACH,MAAM,IAAIE,MAAM,mCAKlB,OAHAF,EAAsBG,KAAOV,EAAWW,cACtCJ,EAAsBG,MAEjBV,EAAWY,kBAAkBL,EACrC,CACD,IAAIM,EAAgBb,EAAWQ,SAASL,GACxC,IAAKU,EACH,MAAM,IAAIJ,MAAM,uCAElB,GAAII,EAAcC,OAGhB,OAAKV,EAAKE,iBAGVO,EAAcH,KAAOV,EAAWW,cAAcE,EAAcH,MACrDV,EAAWY,kBAAkBC,IAH3BV,EAKX,IAAIY,EAAYf,EAAWQ,SAASN,GACpC,IAAKa,EACH,MAAM,IAAI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ACA,EACA,IACA,IACA,IACA,IACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,IACA,IACA,IACA,GACA,GACA,IACA,IACA,IACA,IACA,IACA,IAGI4/E,EAAY,IAAI5/E,WAAW,CAC/B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IACA,IACA,IACA,IACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,IACA,IACA,IACA,GACA,GACA,IACA,IACA,IACA,IACA,IACA,IAGFi+E,EAAI4B,WAAa,CACf53E,MAAO03E,EACP33E,MAAO43E,GAGT,IAAMtB,EAAO,IAAIt+E,WAAW,CAC1B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,IACA,IACA,GACA,EACA,EACA,EACA,IAGIo/E,EAAO,IAAIp/E,WAAW,CAC1B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAGFi+E,EAAI6B,KAAO7B,EAAI8B,KAAO9B,EAAI+B,KAAOZ,EAEjCnB,EAAIgC,KAAO,IAAIjgF,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAEFi+E,EAAIiC,KAAO,IAAIlgF,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAEFi+E,EAAIkC,KAAO,IAAIngF,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAGFi+E,EAAImC,KAAO,IAAIpgF,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAGF,IAAMqgF,EAAa,IAAIrgF,WAAW,CAAC,IAAK,IAAK,IAAK,MAC5CsgF,EAAY,IAAItgF,WAAW,CAAC,GAAI,IAAK,GAAI,KACzCugF,EAAe,IAAIvgF,WAAW,CAAC,EAAG,EAAG,EAAG,IAE9Ci+E,EAAIuC,KAAOvC,E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rqE,KAAW,IAANhG,GAGTqwE,EAAMA,EAAI/8C,OAAO38B,MAAMqB,UAAUQ,MAAMkC,KAAK4D,IAI9C,IAAK5F,EAAI,EAAGA,EAAIiS,EAAM6lE,IAAIz7E,OAAQ2D,IAEhCsH,GADA1B,EAAOqM,EAAM6lE,IAAI93E,IACNiO,WACX6pE,EAAIxqE,KAAMhG,IAAQ,EAAK,KACvBwwE,EAAIxqE,KAAW,IAANhG,GAETwwE,EAAMA,EAAIl9C,OAAO38B,MAAMqB,UAAUQ,MAAMkC,KAAK4D,IAG9C,IAAMq7E,EAAOjD,EAAIwC,IACfxC,EAAIC,MAAMC,KACV,IAAIn+E,WACF,CACE,EACA43E,EAAI,GACJA,EAAI,GACJA,EAAI,GACJ,IACA,IAAO1lE,EAAM0lE,IAAIt7E,QAEhBu+B,OAAO+8C,GACP/8C,OAAO,CACN3oB,EAAM6lE,IAAIz7E,SAEXu+B,OAAOk9C,KAGRp3E,EAAQuR,EAAMvR,MACdC,EAASsR,EAAMtR,OACfugF,EAAWjvE,EAAM2uC,WAAW,GAC5BugC,EAAWlvE,EAAM2uC,WAAW,GAElC,OAAOo9B,EAAIwC,IACTxC,EAAIC,MAAM3gE,KACV,IAAIvd,WAAW,CACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACCW,GAAS,EAAK,IACP,IAARA,EACCC,GAAU,EAAK,IACP,IAATA,EACA,EACA,GACA,EACA,EACA,EACA,GACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,GACA,IACA,IACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,GACA,KAEFsgF,EACAjD,EAAIwC,IACFxC,EAAIC,MAAME,KACV,IAA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