1 |
- {"version":3,"file":"hls.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/utils/numeric-encoding-utils.ts","src/utils/keysystem-util.ts","src/utils/mediakeys-helper.ts","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/variable-substitution.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/controller/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/level-controller.ts","src/controller/base-playlist-controller.ts","src/controller/fragment-tracker.ts","src/loader/fragment-loader.ts","src/loader/key-loader.ts","src/task-loop.ts","src/utils/buffer-helper.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/base-audio-demuxer.ts","src/demux/adts.ts","src/demux/aacdemuxer.ts","src/demux/mp4demuxer.ts","src/demux/mpegaudio.ts","src/demux/exp-golomb.ts","src/demux/sample-aes.ts","src/demux/tsdemuxer.ts","src/demux/mp3demuxer.ts","src/remux/aac-helper.ts","src/remux/mp4-generator.ts","src/utils/timescale-conversion.ts","src/remux/mp4-remuxer.ts","src/demux/transmuxer.ts","src/remux/passthrough-remuxer.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/utils/ewma.ts","src/utils/ewma-bandwidth-estimator.ts","src/controller/abr-controller.ts","src/demux/chunk-cache.ts","src/controller/audio-stream-controller.ts","src/controller/audio-track-controller.ts","src/utils/media-option-attributes.ts","src/controller/subtitle-stream-controller.ts","src/controller/subtitle-track-controller.ts","src/controller/buffer-operation-queue.ts","src/controller/buffer-controller.ts","src/utils/cea-608-parser.ts","src/utils/output-filter.ts","src/utils/vttcue.ts","src/utils/vttparser.ts","src/utils/webvtt-parser.ts","src/utils/imsc1-ttml-parser.ts","src/controller/timeline-controller.ts","src/controller/cap-level-controller.ts","src/controller/fps-controller.ts","src/controller/eme-controller.ts","src/types/cmcd.ts","src/controller/cmcd-controller.ts","src/controller/content-steering-controller.ts","src/utils/xhr-loader.ts","src/utils/fetch-loader.ts","src/utils/cues.ts","src/config.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 FPSDropLevelCappingData,\n FPSDropData,\n BufferCreatedData,\n BufferAppendedData,\n LevelPTSUpdatedData,\n FragParsedData,\n AudioTracksUpdatedData,\n FragLoadEmergencyAbortedData,\n BackBufferData,\n LiveBackBufferData,\n TrackLoadingData,\n BufferFlushedData,\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 // 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}\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.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}\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 (self.console && 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\n for (const attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n if (attr.substring(0, 2) === 'X-') {\n this.clientAttrs = this.clientAttrs || [];\n this.clientAttrs.push(attr);\n }\n this[attr] = attrs[attr];\n }\n }\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[] | 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 const byteRange: number[] = [];\n if (params.length === 1) {\n byteRange[0] = previous ? previous.byteRangeEndOffset : 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n\n get byteRange(): number[] {\n if (!this._byteRange) {\n return [];\n }\n\n return this._byteRange;\n }\n\n get byteRangeStartOffset(): number {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset(): number {\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 public urlId: number = 0;\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\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) {\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","export function base64ToBase64Url(base64encodedStr: string): string {\n return base64encodedStr\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\nexport function strToBase64Encode(str: string): string {\n return btoa(str);\n}\n\nexport function base64DecodeToStr(str: string): string {\n return atob(str);\n}\n\nexport function base64Encode(input: Uint8Array): string {\n return btoa(String.fromCharCode(...input));\n}\n\nexport function base64UrlEncode(input: Uint8Array): string {\n return base64ToBase64Url(base64Encode(input));\n}\n\nexport function base64Decode(base64encodedStr: string): Uint8Array {\n return Uint8Array.from(atob(base64encodedStr), (c) => c.charCodeAt(0));\n}\n","import { base64Decode } from './numeric-encoding-utils';\n\nfunction getKeyIdBytes(str: string): Uint8Array {\n const keyIdbytes = strToUtf8array(str).subarray(0, 16);\n const paddedkeyIdbytes = new Uint8Array(16);\n paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);\n return paddedkeyIdbytes;\n}\n\nexport function changeEndianness(keyId: Uint8Array) {\n const swap = function (array: Uint8Array, from: number, to: number) {\n const cur = array[from];\n array[from] = array[to];\n array[to] = cur;\n };\n\n swap(keyId, 0, 3);\n swap(keyId, 1, 2);\n swap(keyId, 4, 5);\n swap(keyId, 6, 7);\n}\n\nexport function convertDataUriToArrayBytes(uri: string): Uint8Array | null {\n // data:[<media type][;attribute=value][;base64],<data>\n const colonsplit = uri.split(':');\n let keydata: Uint8Array | null = null;\n if (colonsplit[0] === 'data' && colonsplit.length === 2) {\n const semicolonsplit = colonsplit[1].split(';');\n const commasplit = semicolonsplit[semicolonsplit.length - 1].split(',');\n if (commasplit.length === 2) {\n const isbase64 = commasplit[0] === 'base64';\n const data = commasplit[1];\n if (isbase64) {\n semicolonsplit.splice(-1, 1); // remove from processing\n keydata = base64Decode(data);\n } else {\n keydata = getKeyIdBytes(data);\n }\n }\n }\n return keydata;\n}\n\nexport function strToUtf8array(str: string): Uint8Array {\n return Uint8Array.from(unescape(encodeURIComponent(str)), (c) =>\n c.charCodeAt(0)\n );\n}\n","import type { DRMSystemOptions, EMEControllerConfig } from '../config';\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nexport const enum KeySystems {\n CLEARKEY = 'org.w3.clearkey',\n FAIRPLAY = 'com.apple.fps',\n PLAYREADY = 'com.microsoft.playready',\n WIDEVINE = 'com.widevine.alpha',\n}\n\n// Playlist #EXT-X-KEY KEYFORMAT values\nexport const enum KeySystemFormats {\n CLEARKEY = 'org.w3.clearkey',\n FAIRPLAY = 'com.apple.streamingkeydelivery',\n PLAYREADY = 'com.microsoft.playready',\n WIDEVINE = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',\n}\n\nexport function keySystemFormatToKeySystemDomain(\n format: KeySystemFormats\n): KeySystems | undefined {\n switch (format) {\n case KeySystemFormats.FAIRPLAY:\n return KeySystems.FAIRPLAY;\n case KeySystemFormats.PLAYREADY:\n return KeySystems.PLAYREADY;\n case KeySystemFormats.WIDEVINE:\n return KeySystems.WIDEVINE;\n case KeySystemFormats.CLEARKEY:\n return KeySystems.CLEARKEY;\n }\n}\n\n// System IDs for which we can extract a key ID from \"encrypted\" event PSSH\nexport const enum KeySystemIds {\n // CENC = '1077efecc0b24d02ace33c1e52e2fb4b'\n // CLEARKEY = 'e2719d58a985b3c9781ab030af78d30e',\n // FAIRPLAY = '94ce86fb07ff4f43adb893d2fa968ca2',\n // PLAYREADY = '9a04f07998404286ab92e65be0885f95',\n WIDEVINE = 'edef8ba979d64acea3c827dcd51d21ed',\n}\n\nexport function keySystemIdToKeySystemDomain(\n systemId: KeySystemIds\n): KeySystems | undefined {\n if (systemId === KeySystemIds.WIDEVINE) {\n return KeySystems.WIDEVINE;\n // } else if (systemId === KeySystemIds.PLAYREADY) {\n // return KeySystems.PLAYREADY;\n // } else if (systemId === KeySystemIds.CENC || systemId === KeySystemIds.CLEARKEY) {\n // return KeySystems.CLEARKEY;\n }\n}\n\nexport function keySystemDomainToKeySystemFormat(\n keySystem: KeySystems\n): KeySystemFormats | undefined {\n switch (keySystem) {\n case KeySystems.FAIRPLAY:\n return KeySystemFormats.FAIRPLAY;\n case KeySystems.PLAYREADY:\n return KeySystemFormats.PLAYREADY;\n case KeySystems.WIDEVINE:\n return KeySystemFormats.WIDEVINE;\n case KeySystems.CLEARKEY:\n return KeySystemFormats.CLEARKEY;\n }\n}\n\nexport function getKeySystemsForConfig(\n config: EMEControllerConfig\n): KeySystems[] {\n const { drmSystems, widevineLicenseUrl } = config;\n const keySystemsToAttempt: KeySystems[] = drmSystems\n ? [\n KeySystems.FAIRPLAY,\n KeySystems.WIDEVINE,\n KeySystems.PLAYREADY,\n KeySystems.CLEARKEY,\n ].filter((keySystem) => !!drmSystems[keySystem])\n : [];\n if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {\n keySystemsToAttempt.push(KeySystems.WIDEVINE);\n }\n return keySystemsToAttempt;\n}\n\nexport type MediaKeyFunc = (\n keySystem: KeySystems,\n supportedConfigurations: MediaKeySystemConfiguration[]\n) => Promise<MediaKeySystemAccess>;\n\nexport const requestMediaKeySystemAccess = (function (): MediaKeyFunc | null {\n if (\n typeof self !== 'undefined' &&\n self.navigator &&\n self.navigator.requestMediaKeySystemAccess\n ) {\n return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);\n } else {\n return null;\n }\n})();\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n */\nexport function getSupportedMediaKeySystemConfigurations(\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n let initDataTypes: string[];\n switch (keySystem) {\n case KeySystems.FAIRPLAY:\n initDataTypes = ['cenc', 'sinf'];\n break;\n case KeySystems.WIDEVINE:\n case KeySystems.PLAYREADY:\n initDataTypes = ['cenc'];\n break;\n case KeySystems.CLEARKEY:\n initDataTypes = ['cenc', 'keyids'];\n break;\n default:\n throw new Error(`Unknown key-system: ${keySystem}`);\n }\n return createMediaKeySystemConfigurations(\n initDataTypes,\n audioCodecs,\n videoCodecs,\n drmSystemOptions\n );\n}\n\nfunction createMediaKeySystemConfigurations(\n initDataTypes: string[],\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n const baseConfig: MediaKeySystemConfiguration = {\n initDataTypes: initDataTypes,\n persistentState: drmSystemOptions.persistentState || 'not-allowed',\n distinctiveIdentifier:\n drmSystemOptions.distinctiveIdentifier || 'not-allowed',\n sessionTypes: drmSystemOptions.sessionTypes || [\n drmSystemOptions.sessionType || 'temporary',\n ],\n audioCapabilities: audioCodecs.map((codec) => ({\n contentType: `audio/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.audioRobustness || '',\n encryptionScheme: drmSystemOptions.audioEncryptionScheme || null,\n })),\n videoCapabilities: videoCodecs.map((codec) => ({\n contentType: `video/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.videoRobustness || '',\n encryptionScheme: drmSystemOptions.videoEncryptionScheme || null,\n })),\n };\n\n return [baseConfig];\n}\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 { 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 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 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\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 // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n const earliestPresentationTime = 0;\n const firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\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 let index = version === 0 ? 12 : 20;\n const trackId = readUint32(tkhd, index);\n const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd[0];\n index = version === 0 ? 12 : 20;\n const timescale = readUint32(mdhd, index);\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 let codec;\n if (stsd) {\n codec = bin2str(stsd.subarray(12, 16));\n // TODO: Parse codec details to be able to build MIME type.\n // stsd.start += 8;\n // const codecBox = findBox(stsd, [codec])[0];\n // if (codecBox) {\n // TODO: Codec parsing support for avc1, mp4a, hevc, av01...\n // }\n }\n result[trackId] = { timescale, type };\n result[type] = { timescale, id: trackId, codec };\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\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 logger.error(`[eme] missing 'schm' box`);\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 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 sidxDuration += sidx.references.reduce(\n (dur, ref) => dur + ref.info.duration || 0,\n 0\n );\n }\n }\n\n return sidxDuration;\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 let baseMediaDecodeTime = readUint32(tfdt, 4);\n\n if (version === 0) {\n baseMediaDecodeTime -= timeOffset * timescale;\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 -= timeOffset * timescale;\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// 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) {\n return segmentedRange;\n } else 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 endOfCaptions = false;\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\n if (!endOfCaptions && payloadType === 4 && seiPtr < data.length) {\n endOfCaptions = true;\n\n const countryCode = data[seiPtr++];\n if (countryCode === 181) {\n const providerCode = readUint16(data, seiPtr);\n seiPtr += 2;\n\n if (providerCode === 49) {\n const userStructure = readUint32(data, seiPtr);\n seiPtr += 4;\n\n if (userStructure === 0x47413934) {\n const userDataType = data[seiPtr++];\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n const firstByte = data[seiPtr++];\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[seiPtr++];\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 && payloadSize < leftOver) {\n endOfCaptions = true;\n\n if (payloadSize > 16) {\n const uuidStrArray: Array<string> = [];\n for (let i = 0; i < 16; i++) {\n const b = data[seiPtr++].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[seiPtr++];\n }\n\n samples.push({\n payloadType,\n pts,\n uuid: uuidStrArray.join(''),\n userData: utf8ArrayToStr(userDataBytes),\n userDataBytes,\n });\n }\n } else if (payloadSize < leftOver) {\n seiPtr += payloadSize;\n } else if (payloadSize > leftOver) {\n break;\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 function parsePssh(initData: ArrayBuffer) {\n if (!(initData instanceof ArrayBuffer) || initData.byteLength < 32) {\n return null;\n }\n const result = {\n version: 0,\n systemId: '',\n kids: null as null | Uint8Array[],\n data: null as null | Uint8Array,\n };\n const view = new DataView(initData);\n const boxSize = view.getUint32(0);\n if (initData.byteLength !== boxSize && boxSize > 44) {\n return null;\n }\n const type = view.getUint32(4);\n if (type !== 0x70737368) {\n return null;\n }\n result.version = view.getUint32(8) >>> 24;\n if (result.version > 1) {\n return null;\n }\n result.systemId = Hex.hexDump(new Uint8Array(initData, 12, 16));\n const dataSizeOrKidCount = view.getUint32(28);\n if (result.version === 0) {\n if (boxSize - 32 < dataSizeOrKidCount) {\n return null;\n }\n result.data = new Uint8Array(initData, 32, dataSizeOrKidCount);\n } else if (result.version === 1) {\n result.kids = [];\n for (let i = 0; i < dataSizeOrKidCount; i++) {\n result.kids.push(new Uint8Array(initData, 32 + i * 16, 16));\n }\n }\n return result;\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","import type { AttrList } from './attr-list';\nimport type { ParsedMultivariantPlaylist } from '../loader/m3u8-parser';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { VariableMap } from '../types/level';\n\nconst VARIABLE_REPLACEMENT_REGEX = /\\{\\$([a-zA-Z0-9-_]+)\\}/g;\n\nexport function hasVariableReferences(str: string): boolean {\n return VARIABLE_REPLACEMENT_REGEX.test(str);\n}\n\nexport function substituteVariablesInAttributes(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'hasVariableRefs' | 'playlistParsingError'\n >,\n attr: AttrList,\n attributeNames: string[]\n) {\n if (parsed.variableList !== null || parsed.hasVariableRefs) {\n for (let i = attributeNames.length; i--; ) {\n const name = attributeNames[i];\n const value = attr[name];\n if (value) {\n attr[name] = substituteVariables(parsed, value);\n }\n }\n }\n}\n\nexport function substituteVariables(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'hasVariableRefs' | 'playlistParsingError'\n >,\n value: string\n): string {\n if (parsed.variableList !== null || parsed.hasVariableRefs) {\n const variableList = parsed.variableList;\n return value.replace(\n VARIABLE_REPLACEMENT_REGEX,\n (variableReference: string) => {\n const variableName = variableReference.substring(\n 2,\n variableReference.length - 1\n );\n const variableValue = variableList?.[variableName];\n if (variableValue === undefined) {\n parsed.playlistParsingError ||= new Error(\n `Missing preceding EXT-X-DEFINE tag for Variable Reference: \"${variableName}\"`\n );\n return variableReference;\n }\n return variableValue;\n }\n );\n }\n return value;\n}\n\nexport function addVariableDefinition(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'playlistParsingError'\n >,\n attr: AttrList,\n parentUrl: string\n) {\n let variableList = parsed.variableList;\n if (!variableList) {\n parsed.variableList = variableList = {};\n }\n let NAME: string;\n let VALUE;\n if ('QUERYPARAM' in attr) {\n NAME = attr.QUERYPARAM;\n try {\n const searchParams = new self.URL(parentUrl).searchParams;\n if (searchParams.has(NAME)) {\n VALUE = searchParams.get(NAME);\n } else {\n throw new Error(\n `\"${NAME}\" does not match any query parameter in URI: \"${parentUrl}\"`\n );\n }\n } catch (error) {\n parsed.playlistParsingError ||= new Error(\n `EXT-X-DEFINE QUERYPARAM: ${error.message}`\n );\n }\n } else {\n NAME = attr.NAME;\n VALUE = attr.VALUE;\n }\n if (NAME in variableList) {\n parsed.playlistParsingError ||= new Error(\n `EXT-X-DEFINE duplicate Variable Name declarations: \"${NAME}\"`\n );\n } else {\n variableList[NAME] = VALUE || '';\n }\n}\n\nexport function importVariableDefinition(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'playlistParsingError'\n >,\n attr: AttrList,\n sourceVariableList: VariableMap | null\n) {\n const IMPORT = attr.IMPORT;\n if (sourceVariableList && IMPORT in sourceVariableList) {\n let variableList = parsed.variableList;\n if (!variableList) {\n parsed.variableList = variableList = {};\n }\n variableList[IMPORT] = sourceVariableList[IMPORT];\n } else {\n parsed.playlistParsingError ||= new Error(\n `EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: \"${IMPORT}\"`\n );\n }\n}\n","/**\n * MediaSource helper\n */\n\nexport function getMediaSource(): typeof MediaSource | undefined {\n if (typeof self === 'undefined') return undefined;\n return self.MediaSource || ((self as any).WebKitMediaSource as MediaSource);\n}\n","import { getMediaSource } from './mediasource-helper';\n\n// from http://mp4ra.org/codecs.html\nconst sampleEntryCodesISO = {\n audio: {\n a3ds: true,\n 'ac-3': true,\n 'ac-4': true,\n alac: true,\n alaw: true,\n dra1: true,\n 'dts+': true,\n 'dts-': true,\n dtsc: true,\n dtse: true,\n dtsh: true,\n 'ec-3': true,\n enca: true,\n g719: true,\n g726: true,\n m4ae: true,\n mha1: true,\n mha2: true,\n mhm1: true,\n mhm2: true,\n mlpa: true,\n mp4a: true,\n 'raw ': true,\n Opus: true,\n opus: true, // browsers expect this to be lowercase despite MP4RA says 'Opus'\n samr: true,\n sawb: true,\n sawp: true,\n sevc: true,\n sqcp: true,\n ssmv: true,\n twos: true,\n ulaw: true,\n },\n video: {\n avc1: true,\n avc2: true,\n avc3: true,\n avc4: true,\n avcp: true,\n av01: true,\n drac: true,\n dva1: true,\n dvav: true,\n dvh1: true,\n dvhe: true,\n encv: true,\n hev1: true,\n hvc1: true,\n mjp2: true,\n mp4v: true,\n mvc1: true,\n mvc2: true,\n mvc3: true,\n mvc4: true,\n resv: true,\n rv60: true,\n s263: true,\n svc1: true,\n svc2: true,\n 'vc-1': true,\n vp08: true,\n vp09: true,\n },\n text: {\n stpp: true,\n wvtt: true,\n },\n};\n\nconst MediaSource = getMediaSource();\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)] === true;\n}\n\nexport function isCodecSupportedInMp4(codec: string, type: CodecType): boolean {\n return (\n MediaSource?.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`) ??\n false\n );\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 {\n MediaPlaylist,\n AudioGroup,\n MediaPlaylistType,\n MediaAttributes,\n} 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[\\S ]*)/.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)/.source,\n /(#)([^:]*):(.*)/.source,\n /(#)(.*)(?:.*)\\r?\\n?/.source,\n ].join('|')\n);\n\nexport default class M3U8Parser {\n static findGroup(\n groups: Array<AudioGroup>,\n mediaGroupId: string\n ): AudioGroup | 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 convertAVC1ToAVCOTI(codec) {\n // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported\n const avcdata = codec.split('.');\n if (avcdata.length > 2) {\n let result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);\n return result;\n }\n return codec;\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('AVERAGE-BANDWIDTH') ||\n attrs.decimalInteger('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(\n ((attrs.CODECS as string) || '').split(/[ ,]+/).filter((c) => c),\n level\n );\n\n if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {\n level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\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: MediaPlaylistType | undefined = attrs.TYPE as\n | MediaPlaylistType\n | undefined;\n if (type) {\n const groups = 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 media: MediaPlaylist = {\n attrs,\n bitrate: 0,\n id: id++,\n groupId: attrs['GROUP-ID'] || '',\n instreamId: attrs['INSTREAM-ID'],\n name: attrs.NAME || attrs.LANGUAGE || '',\n type,\n default: attrs.bool('DEFAULT'),\n autoselect: attrs.bool('AUTOSELECT'),\n forced: attrs.bool('FORCED'),\n lang: attrs.LANGUAGE,\n url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : '',\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\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 }\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 frag.urlId = levelUrlId;\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 '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 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(codecs: Array<string>, level: LevelParsed) {\n ['video', 'audio', 'text'].forEach((type: CodecType) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n const preferred = filtered.filter((codec) => {\n return (\n codec.lastIndexOf('avc1', 0) === 0 ||\n codec.lastIndexOf('mp4a', 0) === 0\n );\n });\n level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];\n\n // remove from list\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n\n level.unknownCodecs = codecs;\n}\n\nfunction assignCodec(media, groupItem, codecProperty) {\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: LoaderContext,\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;\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 // track group id\n groupId?: 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, url, deliveryDirectives } = data;\n this.load({\n id,\n level,\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;\n if (loaderContext && loaderContext.url === context.url) {\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 (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 = Number.isFinite(id as number) ? (id as number) : 0;\n const levelId = Number.isFinite(level as number)\n ? (level as number)\n : levelUrlId;\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","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: DemuxedVideoTrack;\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 | AvcSample[]\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[];\n samplerate?: number;\n segmentCodec?: string;\n channelCount?: number;\n manifestCodec?: string;\n samples: AudioSample[];\n}\n\nexport interface DemuxedVideoTrack 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 samples: AvcSample[] | Uint8Array;\n}\n\nexport interface DemuxedAvcTrack extends DemuxedVideoTrack {\n samples: AvcSample[];\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 AvcSample {\n dts: number;\n pts: number;\n key: boolean;\n frame: boolean;\n units: AvcSampleUnit[];\n debug: string;\n length: number;\n}\n\nexport interface AvcSampleUnit {\n data: Uint8Array;\n type: 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 appendedDateRangeCues = dateRangeCuesAppended[id];\n const cues = appendedDateRangeCues?.cues || {};\n let durationKnown = appendedDateRangeCues?.durationKnown || false;\n const startTime = dateRangeDateToTimelineSeconds(\n dateRange.startDate,\n dateTimeOffset\n );\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\n .reduce((filterMapArray, id) => {\n const candidate = dateRanges[id];\n if (\n candidate.class === dateRange.class &&\n candidate.id !== id &&\n candidate.startDate > dateRange.startDate\n ) {\n filterMapArray.push(candidate);\n }\n return filterMapArray;\n }, [] as DateRange[])\n .sort((a, b) => a.startDate.getTime() - b.startDate.getTime())[0];\n if (nextDateRangeWithSameClass) {\n endTime = dateRangeDateToTimelineSeconds(\n nextDateRangeWithSameClass.startDate,\n dateTimeOffset\n );\n durationKnown = true;\n }\n }\n\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 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 (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {\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 if (\n levelDetails.live &&\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 { LevelDetails } from '../loader/level-details';\nimport { AttrList } from '../utils/attr-list';\n\nexport interface LevelParsed {\n attrs: LevelAttributes;\n audioCodec?: string;\n bitrate: number;\n details?: LevelDetails;\n height?: number;\n id?: number;\n level?: 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'?: 'SDR' | 'HLG' | 'PQ';\n}\n\nexport const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null] as const;\nexport type HdcpLevel = (typeof HdcpLevels)[number];\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, msn?: number): HlsSkip {\n const { canSkipUntil, canSkipDateRanges, endSN } = details;\n const snChangeGoal = msn !== undefined ? msn - endSN : 0;\n if (canSkipUntil && snChangeGoal < canSkipUntil) {\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 height: number;\n public readonly id: number;\n public readonly name: string | undefined;\n public readonly videoCodec: string | undefined;\n public readonly width: number;\n public readonly unknownCodecs: string[] | undefined;\n public audioGroupIds?: (string | undefined)[];\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 textGroupIds?: (string | undefined)[];\n public url: string[];\n private _urlId: number = 0;\n\n constructor(data: LevelParsed) {\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.audioCodec = data.audioCodec;\n this.videoCodec = data.videoCodec;\n this.unknownCodecs = data.unknownCodecs;\n this.codecSet = [data.videoCodec, data.audioCodec]\n .filter((c) => c)\n .join(',')\n .replace(/\\.[^.,]+/g, '');\n }\n\n get maxBitrate(): number {\n return Math.max(this.realBitrate, this.bitrate);\n }\n\n get attrs(): LevelAttributes {\n return this._attrs[this._urlId];\n }\n\n get pathwayId(): string {\n return this.attrs['PATHWAY-ID'] || '.';\n }\n\n get uri(): string {\n return this.url[this._urlId] || '';\n }\n\n get urlId(): number {\n return this._urlId;\n }\n\n set urlId(value: number) {\n const newValue = value % this.url.length;\n if (this._urlId !== newValue) {\n this.fragmentError = 0;\n this.loadError = 0;\n this.details = undefined;\n this._urlId = newValue;\n }\n }\n\n get audioGroupId(): string | undefined {\n return this.audioGroupIds?.[this.urlId];\n }\n\n get textGroupId(): string | undefined {\n return this.textGroupIds?.[this.urlId];\n }\n\n addFallback(data: LevelParsed) {\n this.url.push(data.url);\n this._attrs.push(data.attrs);\n }\n}\n","/**\n * Provides methods dealing with playlist sliding and drift\n */\n\nimport { logger } from '../utils/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 newFrag.urlId = oldFrag.urlId;\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.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","import { LoadPolicy, LoaderConfig, RetryConfig } from '../config';\nimport { ErrorDetails } from '../errors';\nimport { ErrorData } from '../types/events';\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 httpStatus?: number | undefined\n): retryConfig is RetryConfig & boolean {\n return (\n !!retryConfig &&\n retryCount < retryConfig.maxNumRetry &&\n (retryForHttpStatus(httpStatus) || !!isTimeout)\n );\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): 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 } 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 fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) ===\n 0\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\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, type Level } 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 '../hls';\n\nconst RENDITION_PENALTY_DURATION_MS = 300000;\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 this.playlistError = 0;\n }\n\n stopLoad(): void {}\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 context.groupId === level.audioGroupId) ||\n (context.type === PlaylistContextType.SUBTITLE_TRACK &&\n context.groupId === level.textGroupId))\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 }\n }\n return;\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.REMUX_ALLOC_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_APPEND_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 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 return;\n }\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 httpStatus = data.response?.code;\n const retry = shouldRetry(\n retryConfig,\n retryCount,\n isTimeoutError(data),\n httpStatus\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 httpStatus = data.response?.code;\n const retry = shouldRetry(\n retryConfig,\n fragmentErrors,\n isTimeoutError(data),\n httpStatus\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 level.loadError++;\n if (hls.autoLevelEnabled) {\n // Search for next level to retry\n let nextLevel = -1;\n const { levels, loadLevel, minAutoLevel, maxAutoLevel } = hls;\n const fragErrorType = data.frag?.type;\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 (data.details === ErrorDetails.FRAG_GAP && data.frag) {\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 playlistErrorGroupId === levelCandidate.audioGroupId) ||\n (playlistErrorType === PlaylistContextType.SUBTITLE_TRACK &&\n playlistErrorGroupId === levelCandidate.textGroupId)\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.audioGroupId === levelCandidate.audioGroupId) ||\n (fragErrorType === PlaylistLevelType.SUBTITLE &&\n level.textGroupId === levelCandidate.textGroupId)\n ) {\n // For 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 }\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 }\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.MoveAllAlternatesMatchingHost:\n {\n // Handle Redundant Levels here. Pathway switching is handled by content-steering-controller\n if (!errorAction.resolved) {\n errorAction.resolved = this.redundantFailover(data);\n }\n }\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 private redundantFailover(data: ErrorData): boolean {\n const { hls, penalizedRenditions } = this;\n const levelIndex: number =\n data.parent === PlaylistLevelType.MAIN\n ? (data.level as number)\n : hls.loadLevel;\n const level = hls.levels[levelIndex];\n const redundantLevels = level.url.length;\n const errorUrlId = data.frag ? data.frag.urlId : level.urlId;\n if (level.urlId === errorUrlId && (!data.frag || level.details)) {\n this.penalizeRendition(level, data);\n }\n for (let i = 1; i < redundantLevels; i++) {\n const newUrlId = (errorUrlId + i) % redundantLevels;\n const penalizedRendition = penalizedRenditions[newUrlId];\n // Check if rendition is penalized and skip if it is a bad fit for failover\n if (\n !penalizedRendition ||\n checkExpired(penalizedRendition, data, penalizedRenditions[errorUrlId])\n ) {\n // delete penalizedRenditions[newUrlId];\n // Update the url id of all levels so that we stay on the same set of variants when level switching\n this.warn(\n `Switching to Redundant Stream ${newUrlId + 1}/${redundantLevels}: \"${\n level.url[newUrlId]\n }\" after ${data.details}`\n );\n this.playlistError = 0;\n hls.levels.forEach((lv) => {\n lv.urlId = newUrlId;\n });\n hls.nextLoadLevel = levelIndex;\n return true;\n }\n }\n return false;\n }\n\n private penalizeRendition(level: Level, data: ErrorData) {\n const { penalizedRenditions } = this;\n const penalizedRendition = penalizedRenditions[level.urlId] || {\n lastErrorPerfMs: 0,\n errors: [],\n details: undefined,\n };\n penalizedRendition.lastErrorPerfMs = performance.now();\n penalizedRendition.errors.push(data);\n penalizedRendition.details = level.details;\n penalizedRenditions[level.urlId] = penalizedRendition;\n }\n}\n\nfunction checkExpired(\n penalizedRendition: PenalizedRendition,\n data: ErrorData,\n currentPenaltyState: PenalizedRendition | undefined\n): boolean {\n // Expire penalty for switching back to rendition after RENDITION_PENALTY_DURATION_MS\n if (\n performance.now() - penalizedRendition.lastErrorPerfMs >\n RENDITION_PENALTY_DURATION_MS\n ) {\n return true;\n }\n // Expire penalty on GAP tag error if rendition has no GAP at position (does not cover media tracks)\n const lastErrorDetails = penalizedRendition.details;\n if (data.details === ErrorDetails.FRAG_GAP && lastErrorDetails && data.frag) {\n const position = data.frag.start;\n const candidateFrag = findFragmentByPTS(\n null,\n lastErrorDetails.fragments,\n position\n );\n if (candidateFrag && !candidateFrag.gap) {\n return true;\n }\n }\n // Expire penalty if there are more errors in currentLevel than in penalizedRendition\n if (\n currentPenaltyState &&\n penalizedRendition.errors.length < currentPenaltyState.errors.length\n ) {\n const lastCandidateError =\n penalizedRendition.errors[penalizedRendition.errors.length - 1];\n if (\n lastErrorDetails &&\n lastCandidateError.frag &&\n data.frag &&\n Math.abs(lastCandidateError.frag.start - data.frag.start) >\n lastErrorDetails.targetduration * 3\n ) {\n return true;\n }\n }\n return false;\n}\n","/*\n * Level Controller\n */\n\nimport {\n ManifestLoadedData,\n ManifestParsedData,\n LevelLoadedData,\n TrackSwitchedData,\n FragLoadedData,\n ErrorData,\n LevelSwitchingData,\n LevelsUpdatedData,\n ManifestLoadingData,\n} from '../types/events';\nimport { Level } from '../types/level';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { isCodecSupportedInMp4 } from '../utils/codecs';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters, LevelParsed } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport ContentSteeringController from './content-steering-controller';\n\nlet chromeOrFirefox: boolean;\n\nexport default class LevelController extends BasePlaylistController {\n private _levels: Level[] = [];\n private _firstLevel: 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.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, 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.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, 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 startLoad(): 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.startLoad();\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 }\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 levels: Level[] = [];\n const levelSet: { [key: string]: Level } = {};\n let levelFromSet: Level;\n\n // regroup redundant levels together\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 if (levelParsed.audioCodec?.indexOf('mp4a.40.34') !== -1) {\n chromeOrFirefox ||= /chrome|firefox/i.test(navigator.userAgent);\n if (chromeOrFirefox) {\n levelParsed.audioCodec = undefined;\n }\n }\n\n const {\n AUDIO,\n CODECS,\n 'FRAME-RATE': FRAMERATE,\n 'PATHWAY-ID': PATHWAY,\n RESOLUTION,\n SUBTITLES,\n } = attributes;\n const contentSteeringPrefix = __USE_CONTENT_STEERING__\n ? `${PATHWAY || '.'}-`\n : '';\n const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}`;\n levelFromSet = levelSet[levelKey];\n\n if (!levelFromSet) {\n levelFromSet = new Level(levelParsed);\n levelSet[levelKey] = levelFromSet;\n levels.push(levelFromSet);\n } else {\n levelFromSet.addFallback(levelParsed);\n }\n\n addGroupId(levelFromSet, 'audio', AUDIO);\n addGroupId(levelFromSet, 'text', SUBTITLES);\n });\n\n this.filterAndSortMediaOptions(levels, data);\n }\n\n private filterAndSortMediaOptions(\n unfilteredLevels: Level[],\n data: ManifestLoadedData\n ) {\n let audioTracks: MediaPlaylist[] = [];\n let subtitleTracks: MediaPlaylist[] = [];\n\n let resolutionFound = false;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n // only keep levels with supported audio/video codecs\n let levels = unfilteredLevels.filter(\n ({ audioCodec, videoCodec, width, height, unknownCodecs }) => {\n resolutionFound ||= !!(width && height);\n videoCodecFound ||= !!videoCodec;\n audioCodecFound ||= !!audioCodec;\n return (\n !unknownCodecs?.length &&\n (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) &&\n (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'))\n );\n }\n );\n\n // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled\n if ((resolutionFound || videoCodecFound) && audioCodecFound) {\n levels = levels.filter(\n ({ videoCodec, width, height }) => !!videoCodec || !!(width && height)\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 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 audioTracks = data.audioTracks.filter(\n (track) =>\n !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio')\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 if (a.bitrate !== b.bitrate) {\n return a.bitrate - b.bitrate;\n }\n if (a.attrs['FRAME-RATE'] !== b.attrs['FRAME-RATE']) {\n return (\n a.attrs.decimalFloatingPoint('FRAME-RATE') -\n b.attrs.decimalFloatingPoint('FRAME-RATE')\n );\n }\n if (a.attrs.SCORE !== b.attrs.SCORE) {\n return (\n a.attrs.decimalFloatingPoint('SCORE') -\n b.attrs.decimalFloatingPoint('SCORE')\n );\n }\n if (resolutionFound && a.height !== b.height) {\n return a.height - b.height;\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 this.log(\n `manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelInPlaylist.bitrate}`\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 pathwayId ? ' with Pathway ' + pathwayId : ''\n } from level ${lastLevelIndex}${\n lastPathwayId ? ' with Pathway ' + lastPathwayId : ''\n }`\n );\n\n const levelSwitchingData: LevelSwitchingData = Object.assign({}, level, {\n level: newLevel,\n maxBitrate: level.maxBitrate,\n attrs: level.attrs,\n uri: level.uri,\n urlId: level.urlId,\n });\n // @ts-ignore\n delete levelSwitchingData._attrs;\n // @ts-ignore\n delete levelSwitchingData._urlId;\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(level.uri, lastLevel?.details);\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() {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n const configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel(newLevel) {\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 onFragLoaded(event: Events.FRAG_LOADED, { frag }: FragLoadedData) {\n if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {\n const level = this._levels[frag.level];\n if (level !== undefined) {\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 onAudioTrackSwitched(\n event: Events.AUDIO_TRACK_SWITCHED,\n data: TrackSwitchedData\n ) {\n const currentLevel = this.currentLevel;\n if (!currentLevel) {\n return;\n }\n\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n if (\n currentLevel.audioGroupIds &&\n currentLevel.audioGroupId !== audioGroupId\n ) {\n let urlId = -1;\n for (let i = 0; i < currentLevel.audioGroupIds.length; i++) {\n if (currentLevel.audioGroupIds[i] === audioGroupId) {\n urlId = i;\n break;\n }\n }\n\n if (urlId !== -1 && urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n if (this.canLoad) {\n this.startLoad();\n }\n }\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 const id = currentLevel.urlId;\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 : ''} URI ${id + 1}/${\n currentLevel.url.length\n } ${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 id,\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, urlId) {\n const filterLevelAndGroupByIdIndex = (url, id) => id !== urlId;\n const levels = this._levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n\n if (level.url.length > 1 && urlId !== undefined) {\n level.url = level.url.filter(filterLevelAndGroupByIdIndex);\n if (level.audioGroupIds) {\n level.audioGroupIds = level.audioGroupIds.filter(\n filterLevelAndGroupByIdIndex\n );\n }\n if (level.textGroupIds) {\n level.textGroupIds = level.textGroupIds.filter(\n filterLevelAndGroupByIdIndex\n );\n }\n level.urlId = 0;\n return true;\n }\n if (this.steering) {\n this.steering.removeLevel(level);\n }\n return false;\n });\n\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n { levels }: LevelsUpdatedData\n ) {\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 this._levels = levels;\n }\n}\n\nexport function addGroupId(\n level: Level,\n type: string,\n id: string | undefined\n): void {\n if (!id) {\n return;\n }\n if (type === 'audio') {\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds[level.url.length - 1] = id;\n } else if (type === 'text') {\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds[level.url.length - 1] = id;\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 type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport { getSkipValue, HlsSkip, HlsUrlParameters, Level } from '../types/level';\nimport { computeReloadInterval, mergeDetails } from './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 clearTimeout(this.timer);\n this.timer = -1;\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 ): 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 return new HlsUrlParameters(\n msn,\n part >= 0 ? part : undefined,\n HlsSkip.No\n );\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, msn);\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","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 buffered.partial = true;\n // Check for intersection with buffer\n // Get playable sections of the fragment\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i)),\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.urlId}_${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;\n const end = segment.byteRangeEndOffset;\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","/**\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 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 '../controller/level-helper';\n\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { Level } from '../types/level';\nimport type { RequiredProperties } from '../types/general';\n\nexport function findFirstFragWithCC(fragments: Fragment[], cc: number) {\n let firstFrag: Fragment | null = null;\n\n for (let i = 0, len = fragments.length; i < len; i++) {\n const currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nexport function shouldAlignOnDiscontinuities(\n lastFrag: Fragment | null,\n lastLevel: Level,\n details: LevelDetails\n): lastLevel is RequiredProperties<Level, 'details'> {\n if (lastLevel.details) {\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 referenceIndex: number = 0\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 lastLevel: Level | null,\n details: LevelDetails\n) {\n if (!lastLevel) {\n return;\n }\n alignDiscontinuities(lastFrag, details, lastLevel);\n if (!details.alignedSliding && lastLevel.details) {\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 alignPDT(details, lastLevel.details);\n }\n if (\n !details.alignedSliding &&\n lastLevel.details &&\n !details.skippedSegments\n ) {\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(lastLevel.details, 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 lastLevel: Level\n) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(\n lastLevel.details,\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 * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.\n * @param details - The details of the new level\n * @param lastDetails - The details of the last loaded level\n */\nexport function alignPDT(details: LevelDetails, lastDetails: LevelDetails) {\n // This check protects the unsafe \"!\" usage below for null program date time access.\n if (\n !lastDetails.fragments.length ||\n !details.hasProgramDateTime ||\n !lastDetails.hasProgramDateTime\n ) {\n return;\n }\n // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n // then we can deduce that playlist B sliding is 1000+8 = 1008s\n const lastPDT = lastDetails.fragments[0].programDateTime!; // hasProgramDateTime check above makes this safe.\n const newPDT = details.fragments[0].programDateTime!;\n // date diff is in ms. frag.start is in seconds\n const sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;\n if (sliding && Number.isFinite(sliding)) {\n logger.log(\n `Adjusting PTS using programDateTime delta ${\n newPDT - lastPDT\n }ms, sliding:${sliding.toFixed(3)} ${details.url} `\n );\n adjustSlidingStart(sliding, details);\n }\n}\n\n/**\n * Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts\n * the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,\n * this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,\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 const middleFrag = Math.round(refFragments.length / 2) - 1;\n const refFrag = refFragments[middleFrag];\n const frag =\n findFirstFragWithCC(fragments, refFrag.cc) ||\n fragments[Math.round(fragments.length / 2) - 1];\n\n const refPDT = refFrag.programDateTime;\n const targetPDT = frag.programDateTime;\n if (refPDT === null || targetPDT === null) {\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: any;\n private key: ArrayBuffer;\n\n constructor(subtle, key) {\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 if (this.subtle === null) {\n this.useSoftware = true;\n }\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 const subtle = this.subtle;\n if (this.key !== key || !this.fastAesKey) {\n this.key = key;\n this.fastAesKey = new FastAESKey(subtle, key);\n }\n return this.fastAesKey\n .expandKey()\n .then((aesKey) => {\n // decrypt using web crypto\n if (!subtle) {\n return Promise.reject(new Error('web crypto not initialized'));\n }\n this.logOnce('WebCrypto AES decrypt');\n const crypto = new AESCrypto(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(data, key, iv): 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 './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: number | 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.levels[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.stopLoad();\n super.onHandlerDestroying();\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(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 buffer size 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 (this.reduceMaxBufferLength(minForwardBufferLength)) {\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 &&\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\n return data;\n });\n }\n\n return data;\n })\n .then((data: FragLoadedData) => {\n const { fragCurrent, hls, levels } = this;\n if (!levels) {\n throw new Error('init load aborted, missing levels');\n }\n\n const stats = frag.stats;\n this.state = State.IDLE;\n level.fragmentError = 0;\n 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\n // Silence FRAG_BUFFERED event if fragCurrent is null\n if (data.frag === fragCurrent) {\n hls.trigger(Events.FRAG_BUFFERED, {\n stats,\n frag: fragCurrent,\n part: null,\n id: frag.type,\n });\n }\n this.tick();\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 protected fragContextChanged(frag: Fragment | null) {\n const { fragCurrent } = this;\n return (\n !frag ||\n !fragCurrent ||\n frag.level !== fragCurrent.level ||\n frag.sn !== fragCurrent.sn ||\n frag.urlId !== fragCurrent.urlId\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 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) {\n const config = this.config;\n const minLength = threshold || config.maxBufferLength;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n this.warn(`Reduce max buffer length to ${config.maxMaxBufferLength}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 ) {\n frag = this.getInitialLiveFragment(levelDetails, fragments);\n this.startPosition = 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 tolerance = config.maxFragLookUpTolerance;\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 = bufferEnd > end - tolerance ? 0 : tolerance;\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\n ): number {\n const { levels, levelLastLoaded, fragPrevious } = this;\n const lastLevel: Level | null =\n levelLastLoaded !== null ? levels![levelLastLoaded] : null;\n\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 alignStream(fragPrevious, lastLevel, 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 ?? frag.level);\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 (!gapTagEncountered) {\n errorAction.resolved = true;\n }\n } else {\n logger.warn(\n `${data.details} reached or exceeded max retry (${retryCount})`\n );\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 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);\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 (data.frag) {\n this.fragmentTracker.removeFragment(data.frag);\n this.nextLoadPosition = data.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: number): 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 = this.levels ? this.levels[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 ?? chunkMeta.level);\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) {\n level.fragmentError = 0;\n } else if (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(\n this.levelLastLoaded ?? this.fragCurrent?.level ?? 0\n );\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 type { ExtendedSourceBuffer } from './types/buffer';\n\nfunction getSourceBuffer(): typeof self.SourceBuffer {\n return self.SourceBuffer || (self as any).WebKitSourceBuffer;\n}\n\n/**\n * @ignore\n */\nexport function isSupported(): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n const sourceBuffer = getSourceBuffer();\n const isTypeSupported =\n mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\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 sourceBufferValidAPI =\n !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n\n/**\n * @ignore\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 '../demux/id3';\nimport {\n DemuxerResult,\n Demuxer,\n DemuxedAudioTrack,\n AudioFrame,\n DemuxedMetadataTrack,\n DemuxedVideoTrack,\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 DemuxedVideoTrack,\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(`[${this}] This demuxer does not support Sample-AES decryption`)\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 DemuxedVideoTrack,\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,\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 observer.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: true,\n reason: `invalid ADTS sampling index:${adtsSamplingIndex}`,\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 * AAC demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport * as ID3 from '../demux/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): 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;\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} 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 // ensure we find a moof box in the first 16 kB\n data = data.length > 16384 ? data.subarray(0, 16384) : data;\n return findBox(data, ['moof']).length > 0;\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","/**\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 * 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","/**\n * SAMPLE-AES decrypter\n */\n\nimport { HlsConfig } from '../config';\nimport Decrypter from '../crypt/decrypter';\nimport { HlsEventEmitter } from '../events';\nimport type {\n AudioSample,\n AvcSample,\n AvcSampleUnit,\n DemuxedVideoTrack,\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: AvcSample[],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void,\n curUnit: AvcSampleUnit\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: DemuxedVideoTrack['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 './adts';\nimport * as MpegAudio from './mpegaudio';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\nimport { Events } from '../events';\nimport {\n appendUint8Array,\n parseSEIMessageFromNALu,\n RemuxerTrackIdConfig,\n} 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 DemuxedAvcTrack,\n DemuxedAudioTrack,\n DemuxedTrack,\n Demuxer,\n DemuxerResult,\n AvcSample,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n ElementaryStreamData,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport { AudioFrame } from '../types/demuxer';\n\ntype ParsedTimestamp = {\n pts?: number;\n dts?: number;\n};\n\ntype PES = ParsedTimestamp & {\n data: Uint8Array;\n len: number;\n};\n\ntype ParsedAvcSample = ParsedTimestamp & Omit<AvcSample, 'pts' | 'dts'>;\n\nexport interface TypeSupported {\n mpeg: boolean;\n mp3: boolean;\n mp4: 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 _avcTrack?: DemuxedAvcTrack;\n private _audioTrack?: DemuxedAudioTrack;\n private _id3Track?: DemuxedMetadataTrack;\n private _txtTrack?: DemuxedUserdataTrack;\n private aacOverFlow: AudioFrame | null = null;\n private avcSample: ParsedAvcSample | null = null;\n private remainderData: Uint8Array | null = null;\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 }\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 =\n Math.min(PACKET_LENGTH * 5, data.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 (data[j] === 0x47) {\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 (#5501)\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._avcTrack = TSDemuxer.createTrack('video') as DemuxedAvcTrack;\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.avcSample = 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, _avcTrack, _id3Track } = this;\n if (_audioTrack) {\n _audioTrack.pesData = null;\n }\n if (_avcTrack) {\n _avcTrack.pesData = null;\n }\n if (_id3Track) {\n _id3Track.pesData = null;\n }\n this.aacOverFlow = null;\n this.avcSample = 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._avcTrack as DemuxedAvcTrack;\n const audioTrack = this._audioTrack as DemuxedAudioTrack;\n const id3Track = this._id3Track as DemuxedMetadataTrack;\n const textTrack = this._txtTrack as DemuxedUserdataTrack;\n\n let avcId = videoTrack.pid;\n let avcData = videoTrack.pesData;\n let audioId = audioTrack.pid;\n let id3Id = 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 avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\n this.parseAVCPES(videoTrack, textTrack, pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n avcData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case audioId:\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 }\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 id3Id:\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 );\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 avcId = parsedPIDs.avc;\n if (avcId > 0) {\n videoTrack.pid = avcId;\n }\n\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.pid = audioId;\n audioTrack.segmentCodec = parsedPIDs.segmentCodec;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.pid = id3Id;\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 const error = new Error(\n `Found ${tsPacketErrors} TS packet/s that do not start with 0x47`\n );\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 }\n\n videoTrack.pesData = avcData;\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._avcTrack as DemuxedAvcTrack,\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 avcData = 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 (avcData && (pes = parsePES(avcData))) {\n this.parseAVCPES(\n videoTrack as DemuxedAvcTrack,\n textTrack as DemuxedUserdataTrack,\n pes,\n true\n );\n videoTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n videoTrack.pesData = avcData;\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 }\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 parseAVCPES(\n track: DemuxedAvcTrack,\n textTrack: DemuxedUserdataTrack,\n pes: PES,\n last: boolean\n ) {\n const units = this.parseAVCNALu(track, pes.data);\n const debug = false;\n let avcSample = this.avcSample;\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 (avcSample && units.length && !track.audFound) {\n pushAccessUnit(avcSample, track);\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');\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 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 (avcSample?.frame && !avcSample.key) {\n pushAccessUnit(avcSample, track);\n avcSample = this.avcSample = null;\n }\n }\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(\n true,\n pes.pts,\n pes.dts,\n ''\n );\n }\n\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n avcSample.key = iskey;\n break;\n // IDR\n }\n case 5:\n push = true;\n // handle PES not starting with AUD\n // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push\n if (avcSample?.frame && !avcSample.key) {\n pushAccessUnit(avcSample, track);\n avcSample = this.avcSample = null;\n }\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(\n true,\n pes.pts,\n pes.dts,\n ''\n );\n }\n\n if (debug) {\n avcSample.debug += 'IDR ';\n }\n\n avcSample.key = true;\n avcSample.frame = true;\n break;\n // SEI\n case 6: {\n push = true;\n if (debug && avcSample) {\n avcSample.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 && avcSample) {\n avcSample.debug += 'SPS ';\n }\n\n if (!track.sps) {\n const sps = unit.data;\n const expGolombDecoder = new ExpGolomb(sps);\n const config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [sps];\n track.duration = this._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 break;\n // PPS\n case 8:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccessUnit(avcSample, track);\n }\n\n avcSample = this.avcSample = createAVCSample(\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 (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (avcSample && push) {\n const units = avcSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccessUnit(avcSample, track);\n this.avcSample = null;\n }\n }\n\n private getLastNalUnit(samples: AvcSample[]) {\n let avcSample = this.avcSample;\n let lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n avcSample = samples[samples.length - 1];\n }\n if (avcSample?.units) {\n const units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n private parseAVCNALu(\n track: DemuxedAvcTrack,\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 = [] as Array<{\n data: Uint8Array;\n type: number;\n state?: number;\n }>;\n let i = 0;\n let value;\n let overflow;\n let unitType;\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 if (lastUnitStart >= 0) {\n const unit = {\n data: array.subarray(lastUnitStart, i - state - 1),\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 overflow = i - state - 1;\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n const tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\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 = {\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 const tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\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 const tmp = new Uint8Array(sampleLength + data.byteLength);\n tmp.set(aacOverFlow.sample.unit, 0);\n tmp.set(data, sampleLength);\n data = tmp;\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 const error = new Error(reason);\n logger.warn(`parsing error: ${reason}`);\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n levelRetry: recoverable,\n error,\n reason,\n });\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 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._avcTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n id3Track.samples.push(id3Sample);\n }\n}\n\nfunction createAVCSample(\n key: boolean,\n pts: number | undefined,\n dts: number | undefined,\n debug: string\n): ParsedAvcSample {\n return {\n key,\n frame: false,\n pts,\n dts,\n units: [],\n debug,\n length: 0,\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) {\n const result = { audio: -1, avc: -1, id3: -1, segmentCodec: 'aac' };\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 switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logger.log(\n 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream'\n );\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.audio === -1) {\n result.audio = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logger.log(\n 'H.264 with AES-128-CBC slice encryption found in unencrypted stream'\n );\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.avc === -1) {\n result.avc = pid;\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 !== true && typeSupported.mp3 !== true) {\n logger.log('MPEG audio found, not supported in this browser');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.segmentCodec = 'mp3';\n }\n break;\n\n case 0x24:\n logger.warn('Unsupported HEVC stream type found');\n break;\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 += (((data[offset + 3] & 0x0f) << 8) | data[offset + 4]) + 5;\n }\n return result;\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 const newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\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\nfunction pushAccessUnit(avcSample: ParsedAvcSample, avcTrack: DemuxedAvcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (avcSample.pts === undefined) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n avcSample.pts = lastSample.pts;\n avcSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n avcTrack.dropped++;\n return;\n }\n }\n avcTrack.samples.push(avcSample as AvcSample);\n }\n if (avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n}\n\nexport default TSDemuxer;\n","/**\n * MP3 demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ID3 from '../demux/id3';\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): 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 = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\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","/**\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\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 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 mp4a(track) {\n const samplerate = track.samplerate;\n return MP4.box(\n MP4.types.mp4a,\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,\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 MP4.box(MP4.types.esds, MP4.esds(track))\n );\n }\n\n static mp3(track) {\n const samplerate = track.samplerate;\n return MP4.box(\n MP4.types['.mp3'],\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,\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\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\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 = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\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 AvcSample,\n DemuxedAudioTrack,\n DemuxedAvcTrack,\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;\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\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\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 }\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: DemuxedAvcTrack,\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 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: DemuxedAvcTrack,\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 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 }\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: DemuxedAvcTrack,\n timeOffset: number,\n contiguous: boolean,\n audioTrackLength: number\n ): RemuxedTrack | undefined {\n const timeScale: number = track.inputTimeScale;\n const inputSamples: Array<AvcSample> = 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 not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\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, filling it`\n );\n } else {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n -delta,\n true\n )} ms (${delta}dts) overlapping between fragments detected`\n );\n }\n if (!foundOverlap || nextAvcDts >= inputSamples[0].pts) {\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n logger.log(\n `Video: First 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 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 sample.dts = Math.max(sample.dts, firstDTS);\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 avcSample = inputSamples[i];\n const avcSampleUnits = avcSample.units;\n let mp4SampleLength = 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n const unit = avcSampleUnits[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 - avcSample.dts;\n ptsDelta = inputSamples[i + 1].pts - avcSample.pts;\n } else {\n const config = this.config;\n const lastFrameDuration =\n i > 0\n ? avcSample.dts - inputSamples[i - 1].dts\n : averageSampleDuration;\n ptsDelta =\n i > 0\n ? avcSample.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) - avcSample.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(avcSample.pts - avcSample.dts);\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 avcSample.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 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 =\n track.segmentCodec === 'aac'\n ? AAC_SAMPLES_PER_FRAME\n : MPEG_AUDIO_SAMPLE_PER_FRAME;\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<AvcSample>): 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\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 = new Mp4SampleFlags(isKeyframe);\n }\n}\n\nclass Mp4SampleFlags {\n public isLeading: 0 = 0;\n public isDependedOn: 0 = 0;\n public hasRedundancy: 0 = 0;\n public degradPrio: 0 = 0;\n public dependsOn: 1 | 2 = 1;\n public isNonSync: 0 | 1 = 1;\n\n constructor(isKeyframe) {\n this.dependsOn = isKeyframe ? 2 : 1;\n this.isNonSync = isKeyframe ? 0 : 1;\n }\n}\n","import type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer, { TypeSupported } from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\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';\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 = typeof self !== 'undefined' && self.Date.now;\n}\n\ntype MuxConfig =\n | { demux: typeof MP4Demuxer; remux: typeof PassThroughRemuxer }\n | { demux: typeof TSDemuxer; 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\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 != null &&\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","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 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 (!audioCodec) {\n audioCodec = getParsedTrackCodec(\n initData.audio,\n ElementaryStreamTypes.AUDIO\n );\n }\n\n if (!videoCodec) {\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 | undefined,\n type: ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO\n): string {\n const parsedCodec = track?.codec;\n if (parsedCodec && parsedCodec.length > 4) {\n return parsedCodec;\n }\n // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)\n // Provide defaults based on codec type\n // This allows for some playback of some fmp4 playlists without CODECS defined in manifest\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 if (parsedCodec === 'avc1' || type === ElementaryStreamTypes.VIDEO) {\n return 'avc1.42e01e';\n }\n return 'mp4a.40.5';\n}\nexport default PassThroughRemuxer;\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 data.vendor,\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 } from '../events';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { TypeSupported } from './tsdemuxer';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nconst MediaSource = getMediaSource() || { isTypeSupported: () => false };\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?: Function;\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 typeSupported: TypeSupported = {\n mp4: MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\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 = (ev: any) => this.onWorkerMessage(ev);\n const { worker } = this.workerContext;\n worker.addEventListener('message', this.onwmsg as any);\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: typeSupported,\n vendor: 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 typeSupported,\n config,\n vendor,\n id\n );\n }\n return;\n }\n }\n\n this.transmuxer = new Transmuxer(\n this.observer,\n typeSupported,\n config,\n vendor,\n id\n );\n }\n\n resetWorker(): void {\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(): void {\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 ): void {\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 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(ev: any): void {\n const data = ev.data;\n const hls = this.hls;\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, 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 (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 this.nudgeRetry = 0;\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 return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const isBuffered = bufferInfo.len > 0;\n const nextStart = bufferInfo.nextStart || 0;\n\n // There is no playable buffer (seeked, waiting for buffer)\n if (!isBuffered && !nextStart) {\n return;\n }\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 // 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 this._trySkipBufferHole(partialOrGap);\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 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 this.onMediaDetaching();\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.nextAutoLevel;\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 this.level = hls.nextLoadLevel = startLevel;\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 details = levels?.[level]?.details;\n if (details && (!details.live || this.levelLastLoaded === this.level)) {\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 this.resetStartWhenNotLoaded(this.level);\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 const { config, nextLoadLevel: level } = hls;\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 || !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 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 !== level)\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 * 0.5\n ),\n fragDuration * 0.75\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 = 0;\n this.levels = this.fragPlaying = this.backtrackFragment = null;\n this.altAudio = this.audioOnly = false;\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) {\n let aac = false;\n let heaac = false;\n let codec;\n data.levels.forEach((level) => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\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 !== data.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 (\n (fragCurrent.level !== data.level ||\n fragCurrent.urlId !== curLevel.urlId) &&\n fragCurrent.loader\n ) {\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(newDetails, curLevel.details);\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = newLevelId;\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_FULL_ERROR:\n if (!data.parent || data.parent !== 'main') {\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 }\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData\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 }\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 if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {\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 (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {\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:${\n audiovideo.container\n }, codecs[level/parsed]=[${currentLevel.attrs.CODECS || ''}/${\n audiovideo.codec\n }]`\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.tick();\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 fragPlayingCurrent.urlId !== fragPlaying.urlId\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","/*\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 EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\nimport { Events } from '../events';\nimport { PlaylistLevelType } from '../types/loader';\nimport { logger } from '../utils/logger';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { LoaderStats } from '../types/loader';\nimport type Hls from '../hls';\nimport type {\n FragLoadingData,\n FragLoadedData,\n FragBufferedData,\n LevelLoadedData,\n LevelSwitchingData,\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 = 0;\n private _nextAutoLevel: number = -1;\n private timer: number = -1;\n private onCheck: Function = this._abandonRulesCheck.bind(this);\n private fragCurrent: Fragment | null = null;\n private partCurrent: Part | null = null;\n private bitrateTestDelay: number = 0;\n\n public readonly bwEstimator: EwmaBandWidthEstimator;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n const config = hls.config;\n this.bwEstimator = new EwmaBandWidthEstimator(\n config.abrEwmaSlowVoD,\n config.abrEwmaFastVoD,\n config.abrEwmaDefaultEstimate\n );\n\n this.registerListeners();\n }\n\n protected registerListeners() {\n const { hls } = 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 }\n\n protected unregisterListeners() {\n const { hls } = 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 }\n\n public destroy() {\n this.unregisterListeners();\n this.clearTimer();\n // @ts-ignore\n this.hls = this.onCheck = null;\n this.fragCurrent = this.partCurrent = null;\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 this.fragCurrent = frag;\n this.partCurrent = data.part ?? null;\n this.clearTimer();\n this.timer = self.setInterval(this.onCheck, 100);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.clearTimer();\n }\n\n private getTimeToLoadFrag(\n timeToFirstByteSec: number,\n bandwidth: number,\n fragSizeBits: number,\n isSwitch: boolean\n ) {\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 { total, bwEstimate } = data.stats;\n // Total is the bytelength and bwEstimate in bits/sec\n if (Number.isFinite(total) && Number.isFinite(bwEstimate)) {\n this.lastLevelLoadSec = (8 * total) / bwEstimate;\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 // 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 === 0\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 // Only downswitch if less than 2 fragment lengths are buffered\n if (bufferStarvationDelay >= (2 * duration) / playbackRate) {\n return;\n }\n\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.bwEstimator.getEstimate();\n const { levels, minAutoLevel } = hls;\n const level = levels[frag.level];\n const expectedLen =\n stats.total ||\n Math.max(stats.loaded, Math.round((duration * level.maxBitrate) / 8));\n let timeStreaming = timeLoading - ttfb;\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 = 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\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}\n Current BW estimate: ${\n Number.isFinite(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown'\n } Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate() / 1024).toFixed(\n 3\n )} Kb/s\n Aborting and switching to level ${nextLoadLevel}`);\n if (frag.loader) {\n this.fragCurrent = this.partCurrent = null;\n frag.abortRequests();\n }\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 // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -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 }\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.bwEstimator.getEstimate();\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 self.clearInterval(this.timer);\n }\n\n // return next auto level\n get nextAutoLevel() {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this.bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && !bwEstimator.canEstimate()) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n let nextABRAutoLevel = this.getNextABRAutoLevel();\n // use forced auto level when ABR selected level has errored\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 // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);\n }\n\n return nextABRAutoLevel;\n }\n\n private getNextABRAutoLevel(): number {\n const { fragCurrent, partCurrent, hls } = this;\n const { maxAutoLevel, config, minAutoLevel, media } = hls;\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\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 avgbw = this.bwEstimator\n ? this.bwEstimator.getEstimate()\n : config.abrEwmaDefaultEstimate;\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferInfo = hls.mainForwardBufferInfo;\n const bufferStarvationDelay =\n (bufferInfo ? bufferInfo.len : 0) / playbackRate;\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 let bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay,\n config.abrBandWidthFactor,\n config.abrBandWidthUpFactor\n );\n if (bestLevel >= 0) {\n return bestLevel;\n }\n logger.trace(\n `[abr] ${\n bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'\n }, finding optimal quality level`\n );\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxStarvationDelay)\n : config.maxStarvationDelay;\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\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.trace(\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 bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay + maxStarvationDelay,\n bwFactor,\n bwUpFactor\n );\n return Math.max(bestLevel, 0);\n }\n\n private findBestLevel(\n currentBw: number,\n minAutoLevel: number,\n maxAutoLevel: number,\n maxFetchDuration: number,\n bwFactor: number,\n bwUpFactor: number\n ): number {\n const {\n fragCurrent,\n partCurrent,\n lastLoadedFragLevel: currentLevel,\n } = this;\n const { levels } = this.hls;\n const level = levels[currentLevel];\n const live = !!level?.details?.live;\n const currentCodecSet = level?.codecSet;\n\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n\n const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;\n let levelSkippedMin = minAutoLevel;\n let levelSkippedMax = -1;\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n const levelInfo = levels[i];\n\n if (\n !levelInfo ||\n (currentCodecSet && levelInfo.codecSet !== currentCodecSet)\n ) {\n if (levelInfo) {\n levelSkippedMin = Math.min(i, levelSkippedMin);\n levelSkippedMax = Math.max(i, levelSkippedMax);\n }\n continue;\n }\n if (levelSkippedMax !== -1) {\n logger.trace(\n `[abr] Skipped level(s) ${levelSkippedMin}-${levelSkippedMax} with CODECS:\"${levels[levelSkippedMax].attrs.CODECS}\"; not compatible with \"${level.attrs.CODECS}\"`\n );\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 (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n const bitrate: number = levels[i].maxBitrate;\n const fetchDuration: number = this.getTimeToLoadFrag(\n ttfbEstimateSec,\n adjustedbw,\n bitrate * avgDuration,\n levelDetails === undefined\n );\n\n logger.trace(\n `[abr] level:${i} adjustedbw-bitrate:${Math.round(\n adjustedbw - bitrate\n )} avgDuration:${avgDuration.toFixed(\n 1\n )} maxFetchDuration:${maxFetchDuration.toFixed(\n 1\n )} fetchDuration:${fetchDuration.toFixed(1)}`\n );\n // if adjusted bw is greater than level bitrate AND\n if (\n adjustedbw > bitrate &&\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 === 0 ||\n !Number.isFinite(fetchDuration) ||\n (live && !this.bitrateTestDelay) ||\n fetchDuration < maxFetchDuration)\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 set nextAutoLevel(nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\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 BaseStreamController, { State } from './base-stream-controller';\nimport { Events } from '../events';\nimport { Bufferable, BufferHelper } from '../utils/buffer-helper';\nimport { FragmentState } from './fragment-tracker';\nimport { Level } from '../types/level';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { Fragment, ElementaryStreamTypes, Part } from '../loader/fragment';\nimport ChunkCache from '../demux/chunk-cache';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport { fragmentWithinToleranceTest } from './fragment-finders';\nimport { alignMediaPlaylistByPDT } from '../utils/discontinuities';\nimport { ErrorDetails } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type KeyLoader from '../loader/key-loader';\nimport type { TransmuxerResult } from '../types/transmuxer';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { TrackSet } from '../types/track';\nimport type {\n BufferCreatedData,\n AudioTracksUpdatedData,\n AudioTrackSwitchingData,\n LevelLoadedData,\n TrackLoadedData,\n BufferAppendingData,\n BufferFlushedData,\n InitPTSFoundData,\n FragLoadedData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n FragBufferedData,\n ErrorData,\n} from '../types/events';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\ntype WaitingForPTSData = {\n frag: Fragment;\n part: Part | null;\n cache: ChunkCache;\n complete: boolean;\n};\n\nclass AudioStreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n private videoBuffer: Bufferable | null = null;\n private videoTrackCC: number = -1;\n private waitingVideoCC: number = -1;\n private bufferedTrack: MediaPlaylist | null = null;\n private switchingTrack: MediaPlaylist | null = null;\n private trackId: number = -1;\n private waitingData: WaitingForPTSData | null = null;\n private mainDetails: LevelDetails | null = null;\n private bufferFlushed: boolean = false;\n private cachedTrackLoadedData: TrackLoadedData | null = null;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader\n ) {\n super(\n hls,\n fragmentTracker,\n keyLoader,\n '[audio-stream-controller]',\n PlaylistLevelType.AUDIO\n );\n this._registerListeners();\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.mainDetails = null;\n this.bufferedTrack = null;\n this.switchingTrack = 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.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, 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.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value\n onInitPtsFound(\n event: Events.INIT_PTS_FOUND,\n { frag, id, initPTS, timescale }: InitPTSFoundData\n ) {\n // Always update the new INIT PTS\n // Can change due level switch\n if (id === 'main') {\n const cc = frag.cc;\n this.initPTS[frag.cc] = { baseTime: initPTS, timescale };\n this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}`);\n this.videoTrackCC = cc;\n // If we are waiting, tick immediately to unblock audio fragment transmuxing\n if (this.state === State.WAITING_INIT_PTS) {\n this.tick();\n }\n }\n }\n\n startLoad(startPosition: number) {\n if (!this.levels) {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n return;\n }\n const lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(\n `Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(\n 3\n )}`\n );\n startPosition = lastCurrentTime;\n this.state = State.IDLE;\n } else {\n this.loadedmetadata = false;\n this.state = State.WAITING_TRACK;\n }\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n\n this.tick();\n }\n\n doTick() {\n switch (this.state) {\n case State.IDLE:\n this.doTickIdle();\n break;\n case State.WAITING_TRACK: {\n const { levels, trackId } = this;\n const details = levels?.[trackId]?.details;\n if (details) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.WAITING_INIT_PTS;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY: {\n const now = 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 this.log('RetryDate reached, switch back to IDLE state');\n this.resetStartWhenNotLoaded(this.trackId);\n this.state = State.IDLE;\n }\n break;\n }\n case State.WAITING_INIT_PTS: {\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingData = this.waitingData;\n if (waitingData) {\n const { frag, part, cache, complete } = waitingData;\n if (this.initPTS[frag.cc] !== undefined) {\n this.waitingData = null;\n this.waitingVideoCC = -1;\n this.state = State.FRAG_LOADING;\n const payload = cache.flush();\n const data: FragLoadedData = {\n frag,\n part,\n payload,\n networkDetails: null,\n };\n this._handleFragmentLoadProgress(data);\n if (complete) {\n super._handleFragmentLoadComplete(data);\n }\n } else if (this.videoTrackCC !== this.waitingVideoCC) {\n // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found\n this.log(\n `Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${this.videoTrackCC}`\n );\n this.clearWaitingFragment();\n } else {\n // Drop waiting fragment if an earlier fragment is needed\n const pos = this.getLoadPosition();\n const bufferInfo = BufferHelper.bufferInfo(\n this.mediaBuffer,\n pos,\n this.config.maxBufferHole\n );\n const waitingFragmentAtPosition = fragmentWithinToleranceTest(\n bufferInfo.end,\n this.config.maxFragLookUpTolerance,\n frag\n );\n if (waitingFragmentAtPosition < 0) {\n this.log(\n `Waiting fragment cc (${frag.cc}) @ ${frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`\n );\n this.clearWaitingFragment();\n }\n }\n } else {\n this.state = State.IDLE;\n }\n }\n }\n\n this.onTickEnd();\n }\n\n clearWaitingFragment() {\n const waitingData = this.waitingData;\n if (waitingData) {\n this.fragmentTracker.removeFragment(waitingData.frag);\n this.waitingData = null;\n this.waitingVideoCC = -1;\n this.state = State.IDLE;\n }\n }\n\n protected resetLoadingState() {\n this.clearWaitingFragment();\n super.resetLoadingState();\n }\n\n protected onTickEnd() {\n const { media } = this;\n if (!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 this.lastCurrentTime = media.currentTime;\n }\n\n private doTickIdle() {\n const { hls, levels, media, trackId } = this;\n const config = hls.config;\n\n if (!levels?.[trackId]) {\n return;\n }\n\n // if video not attached AND\n // start fragment already requested OR start frag prefetch not enabled\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!media && (this.startFragRequested || !config.startFragPrefetch)) {\n return;\n }\n\n const levelInfo = levels[trackId];\n\n const trackDetails = levelInfo.details;\n if (\n !trackDetails ||\n (trackDetails.live && this.levelLastLoaded !== trackId) ||\n this.waitForCdnTuneIn(trackDetails)\n ) {\n this.state = State.WAITING_TRACK;\n return;\n }\n\n const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (this.bufferFlushed && bufferable) {\n this.bufferFlushed = false;\n this.afterBufferFlushed(\n bufferable,\n ElementaryStreamTypes.AUDIO,\n PlaylistLevelType.AUDIO\n );\n }\n\n const bufferInfo = this.getFwdBufferInfo(\n bufferable,\n PlaylistLevelType.AUDIO\n );\n if (bufferInfo === null) {\n return;\n }\n const { bufferedTrack, switchingTrack } = this;\n\n if (!switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {\n hls.trigger(Events.BUFFER_EOS, { type: 'audio' });\n this.state = State.ENDED;\n return;\n }\n\n const mainBufferInfo = this.getFwdBufferInfo(\n this.videoBuffer ? this.videoBuffer : this.media,\n PlaylistLevelType.MAIN\n );\n const bufferLen = bufferInfo.len;\n const maxBufLen = this.getMaxBufferLength(mainBufferInfo?.len);\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if (bufferLen >= maxBufLen && !switchingTrack) {\n return;\n }\n const fragments = trackDetails.fragments;\n const start = fragments[0].start;\n let targetBufferTime = bufferInfo.end;\n\n if (switchingTrack && media) {\n const pos = this.getLoadPosition();\n if (bufferedTrack && switchingTrack.attrs !== bufferedTrack.attrs) {\n targetBufferTime = pos;\n }\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\n this.log(\n 'Alt audio track ahead of main track, seek to start of alt audio track'\n );\n media.currentTime = start + 0.05;\n }\n }\n }\n\n let frag = this.getNextFragment(targetBufferTime, trackDetails);\n let atGap = false;\n // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags\n if (frag && this.isLoopLoading(frag, targetBufferTime)) {\n atGap = !!frag.gap;\n frag = this.getNextFragmentLoopLoading(\n frag,\n trackDetails,\n bufferInfo,\n PlaylistLevelType.MAIN,\n maxBufLen\n );\n }\n if (!frag) {\n this.bufferFlushed = true;\n return;\n }\n\n // Buffer audio up to one target duration ahead of main buffer\n const atBufferSyncLimit =\n mainBufferInfo &&\n frag.start > mainBufferInfo.end + trackDetails.targetduration;\n if (\n atBufferSyncLimit ||\n // Or wait for main buffer after buffing some audio\n (!mainBufferInfo?.len && bufferInfo.len)\n ) {\n // Check fragment-tracker for main fragments since GAP segments do not show up in bufferInfo\n const mainFrag = this.getAppendedFrag(frag.start, PlaylistLevelType.MAIN);\n if (mainFrag === null) {\n return;\n }\n // Bridge gaps in main buffer\n atGap ||=\n !!mainFrag.gap || (!!atBufferSyncLimit && mainBufferInfo.len === 0);\n if (\n (atBufferSyncLimit && !atGap) ||\n (atGap && bufferInfo.nextStart && bufferInfo.nextStart < mainFrag.end)\n ) {\n return;\n }\n }\n\n this.loadFragment(frag, levelInfo, targetBufferTime);\n }\n\n protected getMaxBufferLength(mainBufferLength?: number): number {\n const maxConfigBuffer = super.getMaxBufferLength();\n if (!mainBufferLength) {\n return maxConfigBuffer;\n }\n return Math.min(\n Math.max(maxConfigBuffer, mainBufferLength),\n this.config.maxMaxBufferLength\n );\n }\n\n onMediaDetaching() {\n this.videoBuffer = null;\n super.onMediaDetaching();\n }\n\n onAudioTracksUpdated(\n event: Events.AUDIO_TRACKS_UPDATED,\n { audioTracks }: AudioTracksUpdatedData\n ) {\n this.resetTransmuxer();\n this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));\n }\n\n 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 altAudio = !!data.url;\n this.trackId = data.id;\n const { fragCurrent } = this;\n\n if (fragCurrent) {\n fragCurrent.abortRequests();\n this.removeUnbufferedFrags(fragCurrent.start);\n }\n this.resetLoadingState();\n // destroy useless transmuxer when switching audio to main\n if (!altAudio) {\n this.resetTransmuxer();\n } else {\n // switching to audio track, start timer if not already started\n this.setInterval(TICK_INTERVAL);\n }\n\n // should we switch tracks ?\n if (altAudio) {\n this.switchingTrack = data;\n // main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state = State.IDLE;\n } else {\n this.switchingTrack = null;\n this.bufferedTrack = data;\n this.state = State.STOPPED;\n }\n this.tick();\n }\n\n onManifestLoading() {\n this.fragmentTracker.removeAllFragments();\n this.startPosition = this.lastCurrentTime = 0;\n this.bufferFlushed = false;\n this.levels =\n this.mainDetails =\n this.waitingData =\n this.bufferedTrack =\n this.cachedTrackLoadedData =\n this.switchingTrack =\n null;\n this.startFragRequested = false;\n this.trackId = this.videoTrackCC = this.waitingVideoCC = -1;\n }\n\n onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n this.mainDetails = data.details;\n if (this.cachedTrackLoadedData !== null) {\n this.hls.trigger(Events.AUDIO_TRACK_LOADED, this.cachedTrackLoadedData);\n this.cachedTrackLoadedData = null;\n }\n }\n\n onAudioTrackLoaded(event: Events.AUDIO_TRACK_LOADED, data: TrackLoadedData) {\n if (this.mainDetails == null) {\n this.cachedTrackLoadedData = data;\n return;\n }\n const { levels } = this;\n const { details: newDetails, id: trackId } = data;\n if (!levels) {\n this.warn(`Audio tracks were reset while loading level ${trackId}`);\n return;\n }\n this.log(\n `Track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${\n newDetails.lastPartSn\n ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]`\n : ''\n },duration:${newDetails.totalduration}`\n );\n\n const track = levels[trackId];\n let sliding = 0;\n if (newDetails.live || track.details?.live) {\n this.checkLiveUpdate(newDetails);\n const mainDetails = this.mainDetails;\n if (newDetails.deltaUpdateFailed || !mainDetails) {\n return;\n }\n if (\n !track.details &&\n newDetails.hasProgramDateTime &&\n mainDetails.hasProgramDateTime\n ) {\n // Make sure our audio rendition is aligned with the \"main\" rendition, using\n // pdt as our reference times.\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n sliding = newDetails.fragments[0].start;\n } else {\n sliding = this.alignPlaylists(newDetails, track.details);\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = trackId;\n\n // compute start position if we are aligned with the main playlist\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(track.details, sliding);\n }\n // only switch back to IDLE state if we were waiting for track to start downloading a new fragment\n if (\n this.state === State.WAITING_TRACK &&\n !this.waitForCdnTuneIn(newDetails)\n ) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n _handleFragmentLoadProgress(data: FragLoadedData) {\n const { frag, part, payload } = data;\n const { config, trackId, levels } = this;\n if (!levels) {\n this.warn(\n `Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`\n );\n return;\n }\n\n const track = levels[trackId] as Level;\n if (!track) {\n this.warn('Audio track is undefined on fragment load progress');\n return;\n }\n const details = track.details as LevelDetails;\n if (!details) {\n this.warn('Audio track details undefined on fragment load progress');\n this.removeUnbufferedFrags(frag.start);\n return;\n }\n const audioCodec =\n config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';\n\n let transmuxer = this.transmuxer;\n if (!transmuxer) {\n transmuxer = this.transmuxer = new TransmuxerInterface(\n this.hls,\n PlaylistLevelType.AUDIO,\n this._handleTransmuxComplete.bind(this),\n this._handleTransmuxerFlush.bind(this)\n );\n }\n\n // Check if we have video initPTS\n // If not we need to wait for it\n const initPTS = this.initPTS[frag.cc];\n const initSegmentData = frag.initSegment?.data;\n if (initPTS !== undefined) {\n // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n const accurateTimeOffset = false; // details.PTSKnown || !details.live;\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 transmuxer.push(\n payload,\n initSegmentData,\n audioCodec,\n '',\n frag,\n part,\n details.totalduration,\n accurateTimeOffset,\n chunkMeta,\n initPTS\n );\n } else {\n this.log(\n `Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`\n );\n const { cache } = (this.waitingData = this.waitingData || {\n frag,\n part,\n cache: new ChunkCache(),\n complete: false,\n });\n cache.push(new Uint8Array(payload));\n this.waitingVideoCC = this.videoTrackCC;\n this.state = State.WAITING_INIT_PTS;\n }\n }\n\n protected _handleFragmentLoadComplete(fragLoadedData: FragLoadedData) {\n if (this.waitingData) {\n this.waitingData.complete = true;\n return;\n }\n super._handleFragmentLoadComplete(fragLoadedData);\n }\n\n onBufferReset(/* event: Events.BUFFER_RESET */) {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n }\n\n onBufferCreated(event: Events.BUFFER_CREATED, data: BufferCreatedData) {\n const audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer || null;\n }\n if (data.tracks.video) {\n this.videoBuffer = data.tracks.video.buffer || null;\n }\n }\n\n onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n const { frag, part } = data;\n if (frag.type !== PlaylistLevelType.AUDIO) {\n if (!this.loadedmetadata && frag.type === PlaylistLevelType.MAIN) {\n const bufferable = this.videoBuffer || this.media;\n if (bufferable) {\n const bufferedTimeRanges = BufferHelper.getBuffered(bufferable);\n if (bufferedTimeRanges.length) {\n this.loadedmetadata = true;\n }\n }\n }\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 or concluding the audio switch; otherwise, the switched-to track will not buffer\n this.warn(\n `Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${\n frag.level\n } finished buffering, but was aborted. state: ${\n this.state\n }, audioSwitch: ${\n this.switchingTrack ? this.switchingTrack.name : 'false'\n }`\n );\n return;\n }\n if (frag.sn !== 'initSegment') {\n this.fragPrevious = frag;\n const track = this.switchingTrack;\n if (track) {\n this.bufferedTrack = track;\n this.switchingTrack = null;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, { ...track });\n }\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.AUDIO, data);\n break;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n // in case of non fatal error while loading track, if not retrying to load track, switch back to IDLE\n if (\n !data.levelRetry &&\n this.state === State.WAITING_TRACK &&\n data.context?.type === PlaylistContextType.AUDIO_TRACK\n ) {\n this.state = State.IDLE;\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (!data.parent || data.parent !== 'audio') {\n return;\n }\n if (this.reduceLengthAndFlushBuffer(data)) {\n this.bufferedTrack = null;\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n }\n break;\n case ErrorDetails.INTERNAL_EXCEPTION:\n this.recoverWorkerError(data);\n break;\n default:\n break;\n }\n }\n\n private onBufferFlushed(\n event: Events.BUFFER_FLUSHED,\n { type }: BufferFlushedData\n ) {\n if (type === ElementaryStreamTypes.AUDIO) {\n this.bufferFlushed = true;\n if (this.state === State.ENDED) {\n this.state = State.IDLE;\n }\n }\n }\n\n private _handleTransmuxComplete(transmuxResult: TransmuxerResult) {\n const id = 'audio';\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 { details } = level;\n const { audio, text, id3, initSegment } = remuxResult;\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) || !details) {\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n\n this.state = State.PARSING;\n if (this.switchingTrack && audio) {\n this.completeAudioSwitch(this.switchingTrack);\n }\n\n if (initSegment?.tracks) {\n const mapFragment = frag.initSegment || frag;\n this._bufferInitSegment(initSegment.tracks, mapFragment, chunkMeta);\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag: mapFragment,\n id,\n tracks: initSegment.tracks,\n });\n // Only flush audio from old audio tracks when PTS is known on new audio track\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 (id3?.samples?.length) {\n const emittedID3: FragParsingMetadataData = Object.assign(\n {\n id,\n frag,\n details,\n },\n id3\n );\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (text) {\n const emittedText: FragParsingUserdataData = Object.assign(\n {\n id,\n frag,\n details,\n },\n text\n );\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n\n private _bufferInitSegment(\n tracks: TrackSet,\n frag: Fragment,\n chunkMeta: ChunkMetadata\n ) {\n if (this.state !== State.PARSING) {\n return;\n }\n // delete any video track found on audio transmuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n const track = tracks.audio;\n if (!track) {\n return;\n }\n\n track.levelCodec = track.codec;\n track.id = 'audio';\n this.log(\n `Init audio buffer, container:${track.container}, codecs[parsed]=[${track.codec}]`\n );\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n const initSegment = track.initSegment;\n if (initSegment?.byteLength) {\n const segment: BufferAppendingData = {\n type: 'audio',\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n data: initSegment,\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n }\n // trigger handler right now\n this.tick();\n }\n\n protected loadFragment(\n frag: Fragment,\n track: Level,\n targetBufferTime: number\n ) {\n // only load if fragment is not loaded or if in audio switch\n const fragState = this.fragmentTracker.getState(frag);\n this.fragCurrent = frag;\n\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n if (\n this.switchingTrack ||\n fragState === FragmentState.NOT_LOADED ||\n fragState === FragmentState.PARTIAL\n ) {\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, track);\n } else if (track.details?.live && !this.initPTS[frag.cc]) {\n this.log(\n `Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`\n );\n this.state = State.WAITING_INIT_PTS;\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, track, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n\n private completeAudioSwitch(switchingTrack: MediaPlaylist) {\n const { hls, media, bufferedTrack } = this;\n const bufferedAttributes = bufferedTrack?.attrs;\n const switchAttributes = switchingTrack.attrs;\n if (\n media &&\n bufferedAttributes &&\n (bufferedAttributes.CHANNELS !== switchAttributes.CHANNELS ||\n bufferedAttributes.NAME !== switchAttributes.NAME ||\n bufferedAttributes.LANGUAGE !== switchAttributes.LANGUAGE)\n ) {\n this.log('Switching audio track : flushing all audio');\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n }\n this.bufferedTrack = switchingTrack;\n this.switchingTrack = null;\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, { ...switchingTrack });\n }\n}\nexport default AudioStreamController;\n","import { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport {\n ManifestParsedData,\n AudioTracksUpdatedData,\n ErrorData,\n LevelLoadingData,\n AudioTrackLoadedData,\n LevelSwitchingData,\n} from '../types/events';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType } from '../types/loader';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nclass AudioTrackController extends BasePlaylistController {\n private tracks: MediaPlaylist[] = [];\n private groupId: string | null = null;\n private tracksInGroup: MediaPlaylist[] = [];\n private trackId: number = -1;\n private currentTrack: MediaPlaylist | null = null;\n private selectDefaultTrack: boolean = true;\n\n constructor(hls: Hls) {\n super(hls, '[audio-track-controller]');\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_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, 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_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this.unregisterListeners();\n this.tracks.length = 0;\n this.tracksInGroup.length = 0;\n this.currentTrack = null;\n super.destroy();\n }\n\n protected onManifestLoading(): void {\n this.tracks = [];\n this.groupId = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.currentTrack = null;\n this.selectDefaultTrack = true;\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ): void {\n this.tracks = data.audioTracks || [];\n }\n\n protected onAudioTrackLoaded(\n event: Events.AUDIO_TRACK_LOADED,\n data: AudioTrackLoadedData\n ): void {\n const { id, groupId, details } = data;\n const trackInActiveGroup = this.tracksInGroup[id];\n\n if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {\n this.warn(\n `Track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup.groupId}`\n );\n return;\n }\n\n const curDetails = trackInActiveGroup.details;\n trackInActiveGroup.details = data.details;\n this.log(\n `audio-track ${id} \"${trackInActiveGroup.name}\" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`\n );\n\n if (id === this.trackId) {\n this.playlistLoaded(id, data, curDetails);\n }\n }\n\n protected onLevelLoading(\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ): void {\n this.switchLevel(data.level);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.switchLevel(data.level);\n }\n\n private switchLevel(levelIndex: number) {\n const levelInfo = this.hls.levels[levelIndex];\n\n if (!levelInfo?.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.groupId !== audioGroupId) {\n this.groupId = audioGroupId || null;\n\n const audioTracks = this.tracks.filter(\n (track): boolean => !audioGroupId || track.groupId === audioGroupId\n );\n\n // Disable selectDefaultTrack if there are no default tracks\n if (\n this.selectDefaultTrack &&\n !audioTracks.some((track) => track.default)\n ) {\n this.selectDefaultTrack = false;\n }\n\n this.tracksInGroup = audioTracks;\n const audioTracksUpdated: AudioTracksUpdatedData = { audioTracks };\n this.log(\n `Updating audio tracks, ${audioTracks.length} track(s) found in group:${audioGroupId}`\n );\n this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);\n\n this.selectInitialTrack();\n } else if (this.shouldReloadPlaylist(this.currentTrack)) {\n // Retry playlist loading if no playlist is or has been loaded yet\n this.setAudioTrack(this.trackId);\n }\n }\n\n protected onError(event: Events.ERROR, data: ErrorData): void {\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.AUDIO_TRACK &&\n data.context.id === this.trackId &&\n data.context.groupId === this.groupId\n ) {\n this.requestScheduled = -1;\n this.checkRetry(data);\n }\n }\n\n get audioTracks(): MediaPlaylist[] {\n return this.tracksInGroup;\n }\n\n get audioTrack(): number {\n return this.trackId;\n }\n\n set audioTrack(newId: number) {\n // If audio track is selected from API then don't choose from the manifest default track\n this.selectDefaultTrack = false;\n this.setAudioTrack(newId);\n }\n\n private setAudioTrack(newId: number): void {\n const tracks = this.tracksInGroup;\n\n // check if level idx is valid\n if (newId < 0 || newId >= tracks.length) {\n this.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n const lastTrack = this.currentTrack;\n tracks[this.trackId];\n const track = tracks[newId];\n const { groupId, name } = track;\n this.log(\n `Switching to audio-track ${newId} \"${name}\" lang:${track.lang} group:${groupId}`\n );\n this.trackId = newId;\n this.currentTrack = track;\n this.selectDefaultTrack = false;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, { ...track });\n // Do not reload track unless live\n if (track.details && !track.details.live) {\n return;\n }\n const hlsUrlParameters = this.switchParams(track.url, lastTrack?.details);\n this.loadPlaylist(hlsUrlParameters);\n }\n\n private selectInitialTrack(): void {\n const audioTracks = this.tracksInGroup;\n const trackId =\n this.findTrackId(this.currentTrack) | this.findTrackId(null);\n\n if (trackId !== -1) {\n this.setAudioTrack(trackId);\n } else {\n const error = new Error(\n `No track found for running audio group-ID: ${this.groupId} track count: ${audioTracks.length}`\n );\n this.warn(error.message);\n\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true,\n error,\n });\n }\n }\n\n private findTrackId(currentTrack: MediaPlaylist | null): number {\n const audioTracks = this.tracksInGroup;\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (!this.selectDefaultTrack || track.default) {\n if (\n !currentTrack ||\n (currentTrack.attrs['STABLE-RENDITION-ID'] !== undefined &&\n currentTrack.attrs['STABLE-RENDITION-ID'] ===\n track.attrs['STABLE-RENDITION-ID'])\n ) {\n return track.id;\n }\n if (\n currentTrack.name === track.name &&\n currentTrack.lang === track.lang\n ) {\n return track.id;\n }\n }\n }\n return -1;\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n super.loadPlaylist();\n const audioTrack = this.tracksInGroup[this.trackId];\n if (this.shouldLoadPlaylist(audioTrack)) {\n const id = audioTrack.id;\n const groupId = audioTrack.groupId as string;\n let url = audioTrack.url;\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 // track not retrieved yet, or live playlist we need to (re)load it\n this.log(\n `loading audio-track playlist ${id} \"${audioTrack.name}\" lang:${audioTrack.lang} group:${groupId}`\n );\n this.clearTimer();\n this.hls.trigger(Events.AUDIO_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n}\n\nexport default AudioTrackController;\n","import type { Level } from '../types/level';\nimport type { MediaAttributes, MediaPlaylist } from '../types/media-playlist';\n\nexport function subtitleOptionsIdentical(\n trackList1: MediaPlaylist[] | Level[],\n trackList2: MediaPlaylist[]\n): boolean {\n if (trackList1.length !== trackList2.length) {\n return false;\n }\n for (let i = 0; i < trackList1.length; i++) {\n if (\n !subtitleAttributesIdentical(\n trackList1[i].attrs as MediaAttributes,\n trackList2[i].attrs\n )\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function subtitleAttributesIdentical(\n attrs1: MediaAttributes,\n attrs2: MediaAttributes\n): boolean {\n // Media options with the same rendition ID must be bit identical\n const stableRenditionId = attrs1['STABLE-RENDITION-ID'];\n if (stableRenditionId) {\n return stableRenditionId === attrs2['STABLE-RENDITION-ID'];\n }\n // When rendition ID is not present, compare attributes\n return ![\n 'LANGUAGE',\n 'NAME',\n 'CHARACTERISTICS',\n 'AUTOSELECT',\n 'DEFAULT',\n 'FORCED',\n ].some(\n (subtitleAttribute) =>\n attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]\n );\n}\n","import { Events } from '../events';\nimport { Bufferable, BufferHelper } from '../utils/buffer-helper';\nimport { findFragmentByPTS } from './fragment-finders';\nimport { alignMediaPlaylistByPDT } from '../utils/discontinuities';\nimport { addSliding } from './level-helper';\nimport { FragmentState } from './fragment-tracker';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Level } from '../types/level';\nimport { subtitleOptionsIdentical } from '../utils/media-option-attributes';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type KeyLoader from '../loader/key-loader';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { Fragment } from '../loader/fragment';\nimport type {\n ErrorData,\n FragLoadedData,\n SubtitleFragProcessed,\n SubtitleTracksUpdatedData,\n TrackLoadedData,\n TrackSwitchedData,\n BufferFlushingData,\n LevelLoadedData,\n FragBufferedData,\n} from '../types/events';\n\nconst TICK_INTERVAL = 500; // how often to tick in ms\n\ninterface TimeRange {\n start: number;\n end: number;\n}\n\nexport class SubtitleStreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n protected levels: Array<Level> = [];\n\n private currentTrackId: number = -1;\n private tracksBuffered: Array<TimeRange[]> = [];\n private mainDetails: LevelDetails | null = null;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader\n ) {\n super(\n hls,\n fragmentTracker,\n keyLoader,\n '[subtitle-stream-controller]',\n PlaylistLevelType.SUBTITLE\n );\n this._registerListeners();\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.mainDetails = 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.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, 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.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n startLoad(startPosition: number) {\n this.stopLoad();\n this.state = State.IDLE;\n\n this.setInterval(TICK_INTERVAL);\n\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n\n this.tick();\n }\n\n onManifestLoading() {\n this.mainDetails = null;\n this.fragmentTracker.removeAllFragments();\n }\n\n onMediaDetaching(): void {\n this.tracksBuffered = [];\n super.onMediaDetaching();\n }\n\n onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n this.mainDetails = data.details;\n }\n\n onSubtitleFragProcessed(\n event: Events.SUBTITLE_FRAG_PROCESSED,\n data: SubtitleFragProcessed\n ) {\n const { frag, success } = data;\n this.fragPrevious = frag;\n this.state = State.IDLE;\n if (!success) {\n return;\n }\n\n const buffered = this.tracksBuffered[this.currentTrackId];\n if (!buffered) {\n return;\n }\n\n // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n // so we can re-use the logic used to detect how much has been buffered\n let timeRange: TimeRange | undefined;\n const fragStart = frag.start;\n for (let i = 0; i < buffered.length; i++) {\n if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n timeRange = buffered[i];\n break;\n }\n }\n\n const fragEnd = frag.start + frag.duration;\n if (timeRange) {\n timeRange.end = fragEnd;\n } else {\n timeRange = {\n start: fragStart,\n end: fragEnd,\n };\n buffered.push(timeRange);\n }\n this.fragmentTracker.fragBuffered(frag);\n }\n\n onBufferFlushing(event: Events.BUFFER_FLUSHING, data: BufferFlushingData) {\n const { startOffset, endOffset } = data;\n if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {\n const endOffsetSubtitles = endOffset - 1;\n if (endOffsetSubtitles <= 0) {\n return;\n }\n data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);\n this.tracksBuffered.forEach((buffered) => {\n for (let i = 0; i < buffered.length; ) {\n if (buffered[i].end <= endOffsetSubtitles) {\n buffered.shift();\n continue;\n } else if (buffered[i].start < endOffsetSubtitles) {\n buffered[i].start = endOffsetSubtitles;\n } else {\n break;\n }\n i++;\n }\n });\n this.fragmentTracker.removeFragmentsInRange(\n startOffset,\n endOffsetSubtitles,\n PlaylistLevelType.SUBTITLE\n );\n }\n }\n\n onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n if (!this.loadedmetadata && data.frag.type === PlaylistLevelType.MAIN) {\n if (this.media?.buffered.length) {\n this.loadedmetadata = true;\n }\n }\n }\n\n // If something goes wrong, proceed to next frag, if we were processing one.\n onError(event: Events.ERROR, data: ErrorData) {\n const frag = data.frag;\n\n if (frag?.type === PlaylistLevelType.SUBTITLE) {\n if (this.fragCurrent) {\n this.fragCurrent.abortRequests();\n }\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n }\n\n // Got all new subtitle levels.\n onSubtitleTracksUpdated(\n event: Events.SUBTITLE_TRACKS_UPDATED,\n { subtitleTracks }: SubtitleTracksUpdatedData\n ) {\n if (subtitleOptionsIdentical(this.levels, subtitleTracks)) {\n this.levels = subtitleTracks.map(\n (mediaPlaylist) => new Level(mediaPlaylist)\n );\n return;\n }\n this.tracksBuffered = [];\n this.levels = subtitleTracks.map((mediaPlaylist) => {\n const level = new Level(mediaPlaylist);\n this.tracksBuffered[level.id] = [];\n return level;\n });\n this.fragmentTracker.removeFragmentsInRange(\n 0,\n Number.POSITIVE_INFINITY,\n PlaylistLevelType.SUBTITLE\n );\n this.fragPrevious = null;\n this.mediaBuffer = null;\n }\n\n onSubtitleTrackSwitch(\n event: Events.SUBTITLE_TRACK_SWITCH,\n data: TrackSwitchedData\n ) {\n this.currentTrackId = data.id;\n\n if (!this.levels.length || this.currentTrackId === -1) {\n this.clearInterval();\n return;\n }\n\n // Check if track has the necessary details to load fragments\n const currentTrack = this.levels[this.currentTrackId];\n if (currentTrack?.details) {\n this.mediaBuffer = this.mediaBufferTimeRanges;\n } else {\n this.mediaBuffer = null;\n }\n if (currentTrack) {\n this.setInterval(TICK_INTERVAL);\n }\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded(\n event: Events.SUBTITLE_TRACK_LOADED,\n data: TrackLoadedData\n ) {\n const { details: newDetails, id: trackId } = data;\n const { currentTrackId, levels } = this;\n if (!levels.length) {\n return;\n }\n const track: Level = levels[currentTrackId];\n if (trackId >= levels.length || trackId !== currentTrackId || !track) {\n return;\n }\n this.mediaBuffer = this.mediaBufferTimeRanges;\n let sliding = 0;\n if (newDetails.live || track.details?.live) {\n const mainDetails = this.mainDetails;\n if (newDetails.deltaUpdateFailed || !mainDetails) {\n return;\n }\n const mainSlidingStartFragment = mainDetails.fragments[0];\n if (!track.details) {\n if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n sliding = newDetails.fragments[0].start;\n } else if (mainSlidingStartFragment) {\n // line up live playlist with main so that fragments in range are loaded\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n } else {\n sliding = this.alignPlaylists(newDetails, track.details);\n if (sliding === 0 && mainSlidingStartFragment) {\n // realign with main when there is no overlap with last refresh\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = trackId;\n\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(track.details, sliding);\n }\n\n // trigger handler right now\n this.tick();\n\n // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload\n if (\n newDetails.live &&\n !this.fragCurrent &&\n this.media &&\n this.state === State.IDLE\n ) {\n const foundFrag = findFragmentByPTS(\n null,\n newDetails.fragments,\n this.media.currentTime,\n 0\n );\n if (!foundFrag) {\n this.warn('Subtitle playlist not aligned with playback');\n track.details = undefined;\n }\n }\n }\n\n _handleFragmentLoadComplete(fragLoadedData: FragLoadedData) {\n const { frag, payload } = fragLoadedData;\n const decryptData = frag.decryptdata;\n const hls = this.hls;\n\n if (this.fragContextChanged(frag)) {\n return;\n }\n // check to see if the payload needs to be decrypted\n if (\n payload &&\n payload.byteLength > 0 &&\n decryptData &&\n decryptData.key &&\n decryptData.iv &&\n decryptData.method === 'AES-128'\n ) {\n const startTime = performance.now();\n // decrypt the subtitles\n 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 = performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime,\n },\n });\n })\n .catch((err) => {\n this.warn(`${err.name}: ${err.message}`);\n this.state = State.IDLE;\n });\n }\n }\n\n doTick() {\n if (!this.media) {\n this.state = State.IDLE;\n return;\n }\n\n if (this.state === State.IDLE) {\n const { currentTrackId, levels } = this;\n const track = levels[currentTrackId];\n if (!levels.length || !track || !track.details) {\n return;\n }\n const { config } = this;\n const currentTime = this.getLoadPosition();\n const bufferedInfo = BufferHelper.bufferedInfo(\n this.tracksBuffered[this.currentTrackId] || [],\n currentTime,\n config.maxBufferHole\n );\n const { end: targetBufferTime, len: bufferLen } = bufferedInfo;\n\n const mainBufferInfo = this.getFwdBufferInfo(\n this.media,\n PlaylistLevelType.MAIN\n );\n const trackDetails = track.details as LevelDetails;\n const maxBufLen =\n this.getMaxBufferLength(mainBufferInfo?.len) +\n trackDetails.levelTargetDuration;\n\n if (bufferLen > maxBufLen) {\n return;\n }\n const fragments = trackDetails.fragments;\n const fragLen = fragments.length;\n const end = trackDetails.edge;\n\n let foundFrag: Fragment | null = null;\n const fragPrevious = this.fragPrevious;\n if (targetBufferTime < end) {\n const tolerance = config.maxFragLookUpTolerance;\n const lookupTolerance =\n targetBufferTime > end - tolerance ? 0 : tolerance;\n foundFrag = findFragmentByPTS(\n fragPrevious,\n fragments,\n Math.max(fragments[0].start, targetBufferTime),\n lookupTolerance\n );\n if (\n !foundFrag &&\n fragPrevious &&\n fragPrevious.start < fragments[0].start\n ) {\n foundFrag = fragments[0];\n }\n } else {\n foundFrag = fragments[fragLen - 1];\n }\n if (!foundFrag) {\n return;\n }\n foundFrag = this.mapToInitFragWhenRequired(foundFrag) as Fragment;\n if (foundFrag.sn !== 'initSegment') {\n // Load earlier fragment in same discontinuity to make up for misaligned playlists and cues that extend beyond end of segment\n const curSNIdx = foundFrag.sn - trackDetails.startSN;\n const prevFrag = fragments[curSNIdx - 1];\n if (\n prevFrag &&\n prevFrag.cc === foundFrag.cc &&\n this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED\n ) {\n foundFrag = prevFrag;\n }\n }\n if (\n this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED\n ) {\n // only load if fragment is not loaded\n this.loadFragment(foundFrag, track, targetBufferTime);\n }\n }\n }\n\n protected getMaxBufferLength(mainBufferLength?: number): number {\n const maxConfigBuffer = super.getMaxBufferLength();\n if (!mainBufferLength) {\n return maxConfigBuffer;\n }\n return Math.max(maxConfigBuffer, mainBufferLength);\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number\n ) {\n this.fragCurrent = frag;\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, level);\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, level, targetBufferTime);\n }\n }\n\n get mediaBufferTimeRanges(): Bufferable {\n return new BufferableInstance(\n this.tracksBuffered[this.currentTrackId] || []\n );\n }\n}\n\nclass BufferableInstance implements Bufferable {\n public readonly buffered: TimeRanges;\n\n constructor(timeranges: TimeRange[]) {\n const getRange = (\n name: 'start' | 'end',\n index: number,\n length: number\n ): number => {\n index = index >>> 0;\n if (index > length - 1) {\n throw new DOMException(\n `Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`\n );\n }\n return timeranges[index][name];\n };\n this.buffered = {\n get length() {\n return timeranges.length;\n },\n end(index: number): number {\n return getRange('end', index, timeranges.length);\n },\n start(index: number): number {\n return getRange('start', index, timeranges.length);\n },\n };\n }\n}\n","import { Events } from '../events';\nimport { clearCurrentCues } from '../utils/texttrack-utils';\nimport BasePlaylistController from './base-playlist-controller';\nimport type { HlsUrlParameters } from '../types/level';\nimport type Hls from '../hls';\nimport type {\n TrackLoadedData,\n MediaAttachedData,\n SubtitleTracksUpdatedData,\n ManifestParsedData,\n LevelSwitchingData,\n} from '../types/events';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport { ErrorData, LevelLoadingData } from '../types/events';\nimport { PlaylistContextType } from '../types/loader';\n\nclass SubtitleTrackController extends BasePlaylistController {\n private media: HTMLMediaElement | null = null;\n private tracks: MediaPlaylist[] = [];\n private groupId: string | null = null;\n private tracksInGroup: MediaPlaylist[] = [];\n private trackId: number = -1;\n private selectDefaultTrack: boolean = true;\n private queuedDefaultTrack: number = -1;\n private trackChangeListener: () => void = () => this.onTextTracksChanged();\n private asyncPollTrackChange: () => void = () => this.pollTrackChange(0);\n private useTextTrackPolling: boolean = false;\n private subtitlePollingInterval: number = -1;\n private _subtitleDisplay: boolean = true;\n\n constructor(hls: Hls) {\n super(hls, '[subtitle-track-controller]');\n this.registerListeners();\n }\n\n public destroy() {\n this.unregisterListeners();\n this.tracks.length = 0;\n this.tracksInGroup.length = 0;\n this.trackChangeListener = this.asyncPollTrackChange = null as any;\n super.destroy();\n }\n\n public get subtitleDisplay(): boolean {\n return this._subtitleDisplay;\n }\n\n public set subtitleDisplay(value: boolean) {\n this._subtitleDisplay = value;\n if (this.trackId > -1) {\n this.toggleTrackModes(this.trackId);\n }\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_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, 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.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ): void {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (this.queuedDefaultTrack > -1) {\n this.subtitleTrack = this.queuedDefaultTrack;\n this.queuedDefaultTrack = -1;\n }\n\n this.useTextTrackPolling = !(\n this.media.textTracks && 'onchange' in this.media.textTracks\n );\n if (this.useTextTrackPolling) {\n this.pollTrackChange(500);\n } else {\n this.media.textTracks.addEventListener(\n 'change',\n this.asyncPollTrackChange\n );\n }\n }\n\n private pollTrackChange(timeout: number) {\n self.clearInterval(this.subtitlePollingInterval);\n this.subtitlePollingInterval = self.setInterval(\n this.trackChangeListener,\n timeout\n );\n }\n\n protected onMediaDetaching(): void {\n if (!this.media) {\n return;\n }\n\n self.clearInterval(this.subtitlePollingInterval);\n if (!this.useTextTrackPolling) {\n this.media.textTracks.removeEventListener(\n 'change',\n this.asyncPollTrackChange\n );\n }\n\n if (this.trackId > -1) {\n this.queuedDefaultTrack = this.trackId;\n }\n\n const textTracks = filterSubtitleTracks(this.media.textTracks);\n // Clear loaded cues on media detachment from tracks\n textTracks.forEach((track) => {\n clearCurrentCues(track);\n });\n // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.\n this.subtitleTrack = -1;\n this.media = null;\n }\n\n protected onManifestLoading(): void {\n this.tracks = [];\n this.groupId = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.selectDefaultTrack = true;\n }\n\n // Fired whenever a new manifest is loaded.\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ): void {\n this.tracks = data.subtitleTracks;\n }\n\n protected onSubtitleTrackLoaded(\n event: Events.SUBTITLE_TRACK_LOADED,\n data: TrackLoadedData\n ): void {\n const { id, details } = data;\n const { trackId } = this;\n const currentTrack = this.tracksInGroup[trackId];\n\n if (!currentTrack) {\n this.warn(`Invalid subtitle track id ${id}`);\n return;\n }\n\n const curDetails = currentTrack.details;\n currentTrack.details = data.details;\n this.log(\n `subtitle track ${id} loaded [${details.startSN}-${details.endSN}]`\n );\n\n if (id === this.trackId) {\n this.playlistLoaded(id, data, curDetails);\n }\n }\n\n protected onLevelLoading(\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ): void {\n this.switchLevel(data.level);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.switchLevel(data.level);\n }\n\n private switchLevel(levelIndex: number) {\n const levelInfo = this.hls.levels[levelIndex];\n if (!levelInfo?.textGroupIds) {\n return;\n }\n const textGroupId = levelInfo.textGroupIds[levelInfo.urlId];\n const lastTrack = this.tracksInGroup\n ? this.tracksInGroup[this.trackId]\n : undefined;\n if (this.groupId !== textGroupId) {\n const subtitleTracks = this.tracks.filter(\n (track): boolean => !textGroupId || track.groupId === textGroupId\n );\n this.tracksInGroup = subtitleTracks;\n const initialTrackId =\n this.findTrackId(lastTrack?.name) || this.findTrackId();\n this.groupId = textGroupId || null;\n\n const subtitleTracksUpdated: SubtitleTracksUpdatedData = {\n subtitleTracks,\n };\n this.log(\n `Updating subtitle tracks, ${subtitleTracks.length} track(s) found in \"${textGroupId}\" group-id`\n );\n this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);\n\n if (initialTrackId !== -1) {\n this.setSubtitleTrack(initialTrackId, lastTrack);\n }\n } else if (this.shouldReloadPlaylist(lastTrack)) {\n // Retry playlist loading if no playlist is or has been loaded yet\n this.setSubtitleTrack(this.trackId, lastTrack);\n }\n }\n\n private findTrackId(name?: string): number {\n const textTracks = this.tracksInGroup;\n for (let i = 0; i < textTracks.length; i++) {\n const track = textTracks[i];\n if (!this.selectDefaultTrack || track.default) {\n if (!name || name === track.name) {\n return track.id;\n }\n }\n }\n return -1;\n }\n\n protected onError(event: Events.ERROR, data: ErrorData): void {\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.SUBTITLE_TRACK &&\n data.context.id === this.trackId &&\n data.context.groupId === this.groupId\n ) {\n this.checkRetry(data);\n }\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks(): MediaPlaylist[] {\n return this.tracksInGroup;\n }\n\n /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/\n get subtitleTrack(): number {\n return this.trackId;\n }\n\n set subtitleTrack(newId: number) {\n this.selectDefaultTrack = false;\n const lastTrack = this.tracksInGroup\n ? this.tracksInGroup[this.trackId]\n : undefined;\n this.setSubtitleTrack(newId, lastTrack);\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n super.loadPlaylist();\n const currentTrack = this.tracksInGroup[this.trackId];\n if (this.shouldLoadPlaylist(currentTrack)) {\n const id = currentTrack.id;\n const groupId = currentTrack.groupId as string;\n let url = currentTrack.url;\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 this.log(`Loading subtitle playlist for id ${id}`);\n this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n */\n private toggleTrackModes(newId: number): void {\n const { media, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n const groupTracks = textTracks.filter(\n (track) => (track as any).groupId === this.groupId\n );\n if (newId === -1) {\n [].slice.call(textTracks).forEach((track) => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = groupTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = groupTracks[newId];\n if (nextTrack) {\n nextTrack.mode = this.subtitleDisplay ? 'showing' : 'hidden';\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n */\n private setSubtitleTrack(\n newId: number,\n lastTrack: MediaPlaylist | undefined\n ): void {\n const tracks = this.tracksInGroup;\n\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (!this.media) {\n this.queuedDefaultTrack = newId;\n return;\n }\n\n if (this.trackId !== newId) {\n this.toggleTrackModes(newId);\n }\n\n // exit if track id as already set or invalid\n if (\n (this.trackId === newId && (newId === -1 || tracks[newId]?.details)) ||\n newId < -1 ||\n newId >= tracks.length\n ) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n const track = tracks[newId];\n\n this.log(\n `Switching to subtitle-track ${newId}` +\n (track\n ? ` \"${track.name}\" lang:${track.lang} group:${track.groupId}`\n : '')\n );\n this.trackId = newId;\n if (track) {\n const { id, groupId = '', name, type, url } = track;\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {\n id,\n groupId,\n name,\n type,\n url,\n });\n const hlsUrlParameters = this.switchParams(track.url, lastTrack?.details);\n this.loadPlaylist(hlsUrlParameters);\n } else {\n // switch to -1\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, { id: newId });\n }\n }\n\n private onTextTracksChanged(): void {\n if (!this.useTextTrackPolling) {\n self.clearInterval(this.subtitlePollingInterval);\n }\n // Media is undefined when switching streams via loadSource()\n if (!this.media || !this.hls.config.renderTextTracksNatively) {\n return;\n }\n\n let trackId: number = -1;\n const tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n if (this.subtitleTrack !== trackId) {\n this.subtitleTrack = trackId;\n }\n }\n}\n\nfunction filterSubtitleTracks(textTrackList: TextTrackList): 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\nexport default SubtitleTrackController;\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(operation: BufferOperation, type: SourceBufferName) {\n const queue = this.queues[type];\n queue.push(operation);\n if (queue.length === 1 && this.buffers[type]) {\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 { buffers, queues } = this;\n const sb = buffers[type];\n const queue = 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 (e) {\n logger.warn(\n '[buffer-operation-queue]: Unhandled exception executing the current operation'\n );\n operation.onError(e);\n\n // Only shift the current operation off, otherwise the updateend handler will do this for us\n if (!sb?.updating) {\n queue.shift();\n this.executeNext(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 { getMediaSource } 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} 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';\n\nconst MediaSource = getMediaSource();\nconst VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\\.[^.,]+)+/;\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 // counters\n public appendError: number = 0;\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer!: SourceBuffers;\n\n constructor(hls: Hls) {\n this.hls = hls;\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 }\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.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 logger.log(\n `${this.bufferCodecEventsExpected} bufferCodec event(s) expected`\n );\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n const media = (this.media = data.media);\n if (media && MediaSource) {\n const ms = (this.mediaSource = new MediaSource());\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 // link video and media Source\n media.src = self.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n media.addEventListener('emptied', this._onMediaEmptied);\n }\n }\n\n protected onMediaDetaching() {\n const { media, mediaSource, _objectUrl } = this;\n if (mediaSource) {\n logger.log('[buffer-controller]: 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 logger.warn(\n `[buffer-controller]: 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\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 (media.src === _objectUrl) {\n media.removeAttribute('src');\n media.load();\n } else {\n logger.warn(\n '[buffer-controller]: media.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 const sb = this.sourceBuffer[type];\n try {\n if (sb) {\n this.removeBufferListeners(type);\n if (this.mediaSource) {\n this.mediaSource.removeSourceBuffer(sb);\n }\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 }\n } catch (err) {\n logger.warn(\n `[buffer-controller]: Failed to reset the ${type} buffer`,\n err\n );\n }\n });\n this._initSourceBuffer();\n }\n\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData\n ) {\n const sourceBufferCount = this.getSourceBufferTypes().length;\n\n Object.keys(data).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 currentCodec = (track.levelCodec || track.codec).replace(\n VIDEO_CODEC_PROFILE_REPACE,\n '$1'\n );\n const nextCodec = (levelCodec || codec).replace(\n VIDEO_CODEC_PROFILE_REPACE,\n '$1'\n );\n if (currentCodec !== nextCodec) {\n const mimeType = `${container};codecs=${levelCodec || codec}`;\n this.appendChangeType(trackName, mimeType);\n logger.log(\n `[buffer-controller]: switching codec ${currentCodec} to ${nextCodec}`\n );\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 this.bufferCodecEventsExpected = Math.max(\n this.bufferCodecEventsExpected - 1,\n 0\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 logger.log(\n `[buffer-controller]: changing ${type} sourceBuffer type to ${mimeType}`\n );\n sb.changeType(mimeType);\n }\n operationQueue.shiftAndExecuteNext(type);\n },\n onStart: () => {},\n onComplete: () => {},\n onError: (e) => {\n logger.warn(\n `[buffer-controller]: Failed to change ${type} SourceBuffer type`,\n e\n );\n },\n };\n\n operationQueue.append(operation, 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 logger.log(\n `[buffer-controller]: 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.appendError = 0;\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: (err) => {\n // in case any error occured while appending, put back segment in segments table\n logger.error(\n `[buffer-controller]: Error encountered while trying to append to the ${type} SourceBuffer`,\n err\n );\n const event = {\n type: ErrorTypes.MEDIA_ERROR,\n parent: frag.type,\n details: ErrorDetails.BUFFER_APPEND_ERROR,\n frag,\n part,\n chunkMeta,\n error: err,\n err,\n fatal: false,\n };\n\n if (err.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 this.appendError++;\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 if (this.appendError > hls.config.appendErrorMaxRetry) {\n logger.error(\n `[buffer-controller]: Failed ${hls.config.appendErrorMaxRetry} times to append segment in sourceBuffer`\n );\n event.fatal = true;\n }\n }\n hls.trigger(Events.ERROR, event);\n },\n };\n operationQueue.append(operation, 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: (e) => {\n logger.warn(\n `[buffer-controller]: Failed to remove from ${type} SourceBuffer`,\n e\n );\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 logger.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.flushBackBuffer();\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 logger.log(`[buffer-controller]: ${type} sourceBuffer now EOS`);\n }\n }\n return acc && !!(!sb || sb.ended);\n }, true);\n\n if (ended) {\n logger.log(`[buffer-controller]: 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 logger.info(\n `[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`\n );\n }\n return;\n }\n logger.log(`[buffer-controller]: 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 flushBackBuffer() {\n const { hls, details, media, sourceBuffer } = this;\n if (!media || details === null) {\n return;\n }\n\n const sourceBufferTypes = this.getSourceBufferTypes();\n if (!sourceBufferTypes.length) {\n return;\n }\n\n // Support for deprecated liveBackBufferLength\n const backBufferLength =\n details.live && hls.config.liveBackBufferLength !== null\n ? hls.config.liveBackBufferLength\n : hls.config.backBufferLength;\n\n if (!Number.isFinite(backBufferLength) || backBufferLength < 0) {\n return;\n }\n\n const currentTime = media.currentTime;\n const targetDuration = details.levelTargetDuration;\n const maxBackBufferLength = Math.max(backBufferLength, targetDuration);\n const targetBackBufferPosition =\n Math.floor(currentTime / targetDuration) * targetDuration -\n maxBackBufferLength;\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 hls.trigger(Events.BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n\n // Support for deprecated event:\n if (details.live) {\n 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 logger.info(\n `[buffer-controller]: Cannot flush ${type} back buffer while SourceBuffer is in ended state`\n );\n return;\n }\n\n hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: targetBackBufferPosition,\n type,\n });\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 logger.log(\n '[buffer-controller]: Media Source duration is set to Infinity'\n );\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 logger.log(\n `[buffer-controller]: Updating Media Source duration to ${levelDuration.toFixed(\n 3\n )}`\n );\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 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 && !bufferCodecEventsExpected) ||\n pendingTracksCount === 2\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\n const codec = track.levelCodec || track.codec;\n const mimeType = `${track.container};codecs=${codec}`;\n logger.log(`[buffer-controller]: 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 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 logger.error(\n `[buffer-controller]: error while trying to add sourceBuffer: ${err.message}`\n );\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 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 logger.log('[buffer-controller]: Media source opened');\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n this.updateMediaElementDuration();\n this.hls.trigger(Events.MEDIA_ATTACHED, { media });\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 logger.log('[buffer-controller]: Media source closed');\n };\n\n private _onMediaSourceEnded = () => {\n logger.log('[buffer-controller]: Media source ended');\n };\n\n private _onMediaEmptied = () => {\n const { media, _objectUrl } = this;\n if (media && media.src !== _objectUrl) {\n logger.error(\n `Media element src was set while attaching MediaSource (${_objectUrl} > ${media.src})`\n );\n }\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 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(`${type} SourceBuffer error`);\n logger.error(`[buffer-controller]: ${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 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(event);\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 logger.warn(\n `[buffer-controller]: 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) {\n sb.ended = false;\n logger.log(\n `[buffer-controller]: 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 { operationQueue, sourceBuffer } = this;\n const sb = sourceBuffer[type];\n if (!sb) {\n logger.warn(\n `[buffer-controller]: Attempting to append to the ${type} SourceBuffer, but it does not exist`\n );\n operationQueue.shiftAndExecuteNext(type);\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 logger.log(\n '[buffer-controller]: Blocking operation requested, but no SourceBuffers exist'\n );\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","import OutputFilter from './output-filter';\nimport { logger } from '../utils/logger';\n\n/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nconst specialCea608CharsCodes = {\n 0x2a: 0xe1, // lowercase a, acute accent\n 0x5c: 0xe9, // lowercase e, acute accent\n 0x5e: 0xed, // lowercase i, acute accent\n 0x5f: 0xf3, // lowercase o, acute accent\n 0x60: 0xfa, // lowercase u, acute accent\n 0x7b: 0xe7, // lowercase c with cedilla\n 0x7c: 0xf7, // division symbol\n 0x7d: 0xd1, // uppercase N tilde\n 0x7e: 0xf1, // lowercase n tilde\n 0x7f: 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80: 0xae, // Registered symbol (R)\n 0x81: 0xb0, // degree sign\n 0x82: 0xbd, // 1/2 symbol\n 0x83: 0xbf, // Inverted (open) question mark\n 0x84: 0x2122, // Trademark symbol (TM)\n 0x85: 0xa2, // Cents symbol\n 0x86: 0xa3, // Pounds sterling\n 0x87: 0x266a, // Music 8'th note\n 0x88: 0xe0, // lowercase a, grave accent\n 0x89: 0x20, // transparent space (regular)\n 0x8a: 0xe8, // lowercase e, grave accent\n 0x8b: 0xe2, // lowercase a, circumflex accent\n 0x8c: 0xea, // lowercase e, circumflex accent\n 0x8d: 0xee, // lowercase i, circumflex accent\n 0x8e: 0xf4, // lowercase o, circumflex accent\n 0x8f: 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90: 0xc1, // capital letter A with acute\n 0x91: 0xc9, // capital letter E with acute\n 0x92: 0xd3, // capital letter O with acute\n 0x93: 0xda, // capital letter U with acute\n 0x94: 0xdc, // capital letter U with diaresis\n 0x95: 0xfc, // lowercase letter U with diaeresis\n 0x96: 0x2018, // opening single quote\n 0x97: 0xa1, // inverted exclamation mark\n 0x98: 0x2a, // asterisk\n 0x99: 0x2019, // closing single quote\n 0x9a: 0x2501, // box drawings heavy horizontal\n 0x9b: 0xa9, // copyright sign\n 0x9c: 0x2120, // Service mark\n 0x9d: 0x2022, // (round) bullet\n 0x9e: 0x201c, // Left double quotation mark\n 0x9f: 0x201d, // Right double quotation mark\n 0xa0: 0xc0, // uppercase A, grave accent\n 0xa1: 0xc2, // uppercase A, circumflex\n 0xa2: 0xc7, // uppercase C with cedilla\n 0xa3: 0xc8, // uppercase E, grave accent\n 0xa4: 0xca, // uppercase E, circumflex\n 0xa5: 0xcb, // capital letter E with diaresis\n 0xa6: 0xeb, // lowercase letter e with diaresis\n 0xa7: 0xce, // uppercase I, circumflex\n 0xa8: 0xcf, // uppercase I, with diaresis\n 0xa9: 0xef, // lowercase i, with diaresis\n 0xaa: 0xd4, // uppercase O, circumflex\n 0xab: 0xd9, // uppercase U, grave accent\n 0xac: 0xf9, // lowercase u, grave accent\n 0xad: 0xdb, // uppercase U, circumflex\n 0xae: 0xab, // left-pointing double angle quotation mark\n 0xaf: 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0: 0xc3, // Uppercase A, tilde\n 0xb1: 0xe3, // Lowercase a, tilde\n 0xb2: 0xcd, // Uppercase I, acute accent\n 0xb3: 0xcc, // Uppercase I, grave accent\n 0xb4: 0xec, // Lowercase i, grave accent\n 0xb5: 0xd2, // Uppercase O, grave accent\n 0xb6: 0xf2, // Lowercase o, grave accent\n 0xb7: 0xd5, // Uppercase O, tilde\n 0xb8: 0xf5, // Lowercase o, tilde\n 0xb9: 0x7b, // Open curly brace\n 0xba: 0x7d, // Closing curly brace\n 0xbb: 0x5c, // Backslash\n 0xbc: 0x5e, // Caret\n 0xbd: 0x5f, // Underscore\n 0xbe: 0x7c, // Pipe (vertical line)\n 0xbf: 0x223c, // Tilde operator\n 0xc0: 0xc4, // Uppercase A, umlaut\n 0xc1: 0xe4, // Lowercase A, umlaut\n 0xc2: 0xd6, // Uppercase O, umlaut\n 0xc3: 0xf6, // Lowercase o, umlaut\n 0xc4: 0xdf, // Esszett (sharp S)\n 0xc5: 0xa5, // Yen symbol\n 0xc6: 0xa4, // Generic currency sign\n 0xc7: 0x2503, // Box drawings heavy vertical\n 0xc8: 0xc5, // Uppercase A, ring\n 0xc9: 0xe5, // Lowercase A, ring\n 0xca: 0xd8, // Uppercase O, stroke\n 0xcb: 0xf8, // Lowercase o, strok\n 0xcc: 0x250f, // Box drawings heavy down and right\n 0xcd: 0x2513, // Box drawings heavy down and left\n 0xce: 0x2517, // Box drawings heavy up and right\n 0xcf: 0x251b, // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nconst getCharForByte = function (byte: number) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nconst NR_ROWS = 15;\nconst NR_COLS = 100;\n// Tables to look up row from PAC data\nconst rowsLowCh1 = {\n 0x11: 1,\n 0x12: 3,\n 0x15: 5,\n 0x16: 7,\n 0x17: 9,\n 0x10: 11,\n 0x13: 12,\n 0x14: 14,\n};\nconst rowsHighCh1 = {\n 0x11: 2,\n 0x12: 4,\n 0x15: 6,\n 0x16: 8,\n 0x17: 10,\n 0x13: 13,\n 0x14: 15,\n};\nconst rowsLowCh2 = {\n 0x19: 1,\n 0x1a: 3,\n 0x1d: 5,\n 0x1e: 7,\n 0x1f: 9,\n 0x18: 11,\n 0x1b: 12,\n 0x1c: 14,\n};\nconst rowsHighCh2 = {\n 0x19: 2,\n 0x1a: 4,\n 0x1d: 6,\n 0x1e: 8,\n 0x1f: 10,\n 0x1b: 13,\n 0x1c: 15,\n};\n\nconst backgroundColors = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n 'black',\n 'transparent',\n];\n\nconst enum VerboseLevel {\n ERROR = 0,\n TEXT = 1,\n WARNING = 2,\n INFO = 2,\n DEBUG = 3,\n DATA = 3,\n}\n\nclass CaptionsLogger {\n public time: number | null = null;\n public verboseLevel: VerboseLevel = VerboseLevel.ERROR;\n\n log(severity: VerboseLevel, msg: string | (() => string)): void {\n if (this.verboseLevel >= severity) {\n const m: string = typeof msg === 'function' ? msg() : msg;\n logger.log(`${this.time} [${severity}] ${m}`);\n }\n }\n}\n\nconst numArrayToHexArray = function (numArray: number[]): string[] {\n const hexArray: string[] = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\ntype PenStyles = {\n foreground: string | null;\n underline: boolean;\n italics: boolean;\n background: string;\n flash: boolean;\n};\n\nclass PenState {\n public foreground: string;\n public underline: boolean;\n public italics: boolean;\n public background: string;\n public flash: boolean;\n\n constructor(\n foreground?: string,\n underline?: boolean,\n italics?: boolean,\n background?: string,\n flash?: boolean\n ) {\n this.foreground = foreground || 'white';\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || 'black';\n this.flash = flash || false;\n }\n\n reset() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles(styles: Partial<PenStyles>) {\n const attribs = [\n 'foreground',\n 'underline',\n 'italics',\n 'background',\n 'flash',\n ];\n for (let i = 0; i < attribs.length; i++) {\n const style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault() {\n return (\n this.foreground === 'white' &&\n !this.underline &&\n !this.italics &&\n this.background === 'black' &&\n !this.flash\n );\n }\n\n equals(other: PenState) {\n return (\n this.foreground === other.foreground &&\n this.underline === other.underline &&\n this.italics === other.italics &&\n this.background === other.background &&\n this.flash === other.flash\n );\n }\n\n copy(newPenState: PenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n\n toString(): string {\n return (\n 'color=' +\n this.foreground +\n ', underline=' +\n this.underline +\n ', italics=' +\n this.italics +\n ', background=' +\n this.background +\n ', flash=' +\n this.flash\n );\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar {\n uchar: string;\n penState: PenState;\n\n constructor(\n uchar?: string,\n foreground?: string,\n underline?: boolean,\n italics?: boolean,\n background?: string,\n flash?: boolean\n ) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(\n foreground,\n underline,\n italics,\n background,\n flash\n );\n }\n\n reset() {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar(uchar: string, newPenState: PenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState(newPenState: PenState) {\n this.penState.copy(newPenState);\n }\n\n equals(other: StyledUnicodeChar) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy(newChar: StyledUnicodeChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty(): boolean {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nexport class Row {\n public chars: StyledUnicodeChar[];\n public pos: number;\n public currPenState: PenState;\n public cueStartTime?: number;\n logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n this.chars = [];\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.logger = logger;\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals(other: Row) {\n let equal = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other: Row) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty(): boolean {\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor(absPos: number) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n\n if (this.pos < 0) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Negative cursor position ' + this.pos\n );\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Too large cursor position ' + this.pos\n );\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor(relPos: number) {\n const newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let i = this.pos + 1; i < newPos + 1; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace() {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar(byte: number) {\n if (byte >= 0x90) {\n // Extended char\n this.backSpace();\n }\n const char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n this.logger.log(\n VerboseLevel.ERROR,\n () =>\n 'Cannot insert ' +\n byte.toString(16) +\n ' (' +\n char +\n ') at position ' +\n this.pos +\n '. Skipping it!'\n );\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n\n clearFromPos(startPos: number) {\n let i: number;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n }\n\n clear() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow() {\n this.clearFromPos(this.pos);\n }\n\n getTextString() {\n const chars: string[] = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n const char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles(styles: Partial<PenStyles>) {\n this.currPenState.setStyles(styles);\n const currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n */\nexport class CaptionScreen {\n rows: Row[];\n currRow: number;\n nrRollUpRows: number | null;\n lastOutputScreen: CaptionScreen | null;\n logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row(logger));\n } // Note that we use zero-based numbering (0-14)\n\n this.logger = logger;\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.lastOutputScreen = null;\n this.reset();\n }\n\n reset() {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals(other: CaptionScreen): boolean {\n let equal = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other: CaptionScreen) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty(): boolean {\n let empty = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n backSpace() {\n const row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow() {\n const row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar(char: number) {\n const row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen(styles: Partial<PenStyles>) {\n const row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor(relPos: number) {\n const row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor(absPos: number) {\n this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);\n const row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC(pacData: PACData) {\n this.logger.log(\n VerboseLevel.INFO,\n () => 'pacData = ' + JSON.stringify(pacData)\n );\n let newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows - 1;\n }\n\n // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n // clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n const time = this.logger.time;\n if (prevLineTime && time !== null && prevLineTime < time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow - this.nrRollUpRows + i + 1].copy(\n lastOutputScreen.rows[topRowIndex + i]\n );\n }\n }\n }\n }\n\n this.currRow = newRow;\n const row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n const indent = pacData.indent;\n const prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n const styles: PenStyles = {\n foreground: pacData.color,\n underline: pacData.underline,\n italics: pacData.italics,\n background: 'black',\n flash: false,\n };\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData(bkgData: Partial<PenStyles>) {\n this.logger.log(\n VerboseLevel.INFO,\n () => 'bkgData = ' + JSON.stringify(bkgData)\n );\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n }\n\n setRollUpRows(nrRows: number | null) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp() {\n if (this.nrRollUpRows === null) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'roll_up but nrRollUpRows not set yet'\n );\n return; // Not properly setup\n }\n this.logger.log(VerboseLevel.TEXT, () => this.getDisplayText());\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n const topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n this.logger.log(VerboseLevel.INFO, 'Rolling up');\n // this.logger.log(VerboseLevel.TEXT, this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText(asOneRow?: boolean) {\n asOneRow = asOneRow || false;\n const displayText: string[] = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n const rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i + 1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + \": '\" + rowText + \"'\");\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n\n getTextAndFormat() {\n return this.rows;\n }\n}\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\ntype CaptionModes =\n | 'MODE_ROLL-UP'\n | 'MODE_POP-ON'\n | 'MODE_PAINT-ON'\n | 'MODE_TEXT'\n | null;\n\nclass Cea608Channel {\n chNr: number;\n outputFilter: OutputFilter;\n mode: CaptionModes;\n verbose: number;\n displayedMemory: CaptionScreen;\n nonDisplayedMemory: CaptionScreen;\n lastOutputScreen: CaptionScreen;\n currRollUpRow: Row;\n writeScreen: CaptionScreen;\n cueStartTime: number | null;\n logger: CaptionsLogger;\n\n constructor(\n channelNumber: number,\n outputFilter: OutputFilter,\n logger: CaptionsLogger\n ) {\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen(logger);\n this.nonDisplayedMemory = new CaptionScreen(logger);\n this.lastOutputScreen = new CaptionScreen(logger);\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n this.logger = logger;\n }\n\n reset() {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.outputFilter.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n }\n\n getHandler(): OutputFilter {\n return this.outputFilter;\n }\n\n setHandler(newHandler: OutputFilter) {\n this.outputFilter = newHandler;\n }\n\n setPAC(pacData: PACData) {\n this.writeScreen.setPAC(pacData);\n }\n\n setBkgData(bkgData: Partial<PenStyles>) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode(newMode: CaptionModes) {\n if (newMode === this.mode) {\n return;\n }\n\n this.mode = newMode;\n this.logger.log(VerboseLevel.INFO, () => 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n\n insertChars(chars: number[]) {\n for (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n const screen =\n this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n this.logger.log(\n VerboseLevel.INFO,\n () => screen + ': ' + this.writeScreen.getDisplayText(true)\n );\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n this.logger.log(\n VerboseLevel.TEXT,\n () => 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)\n );\n this.outputDataUpdate();\n }\n }\n\n ccRCL() {\n // Resume Caption Loading (switch mode to Pop On)\n this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS() {\n // BackSpace\n this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF() {\n // Reserved (formerly Alarm Off)\n }\n\n ccAON() {\n // Reserved (formerly Alarm On)\n }\n\n ccDER() {\n // Delete to End of Row\n this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU(nrRows: number | null) {\n // Roll-Up Captions-2,3,or 4 Rows\n this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n\n ccFON() {\n // Flash On\n this.logger.log(VerboseLevel.INFO, 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n }\n\n ccRDC() {\n // Resume Direct Captioning (switch mode to PaintOn)\n this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR() {\n // Text Restart in text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD() {\n // Resume Text Display in Text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM() {\n // Erase Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR() {\n // Carriage Return\n this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM() {\n // Erase Non-Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC() {\n // End of Caption (Flip Memories)\n this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n const tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n this.logger.log(\n VerboseLevel.TEXT,\n () => 'DISP: ' + this.displayedMemory.getDisplayText()\n );\n }\n this.outputDataUpdate(true);\n }\n\n ccTO(nrCols: number) {\n // Tab Offset 1,2, or 3 columns\n this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW(secondByte: number) {\n // Parse MIDROW command\n const styles: Partial<PenStyles> = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n const colorIndex = Math.floor(secondByte / 2) - 0x10;\n const colors = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n ];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate(dispatch: boolean = false) {\n const time = this.logger.time;\n if (time === null) {\n return;\n }\n\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {\n // Start of a new cue\n this.cueStartTime = time;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n this.outputFilter.newCue(\n this.cueStartTime!,\n time,\n this.lastOutputScreen\n );\n if (dispatch && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime(t: number) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime!, t, this.displayedMemory);\n }\n\n this.cueStartTime = t;\n }\n }\n }\n}\n\ninterface PACData {\n row: number;\n indent: number | null;\n color: string | null;\n underline: boolean;\n italics: boolean;\n}\n\ntype SupportedField = 1 | 3;\n\ntype Channels = 0 | 1 | 2; // Will be 1 or 2 when parsing captions\n\ntype CmdHistory = {\n a: number | null;\n b: number | null;\n};\n\nclass Cea608Parser {\n channels: Array<Cea608Channel | null>;\n currentChannel: Channels = 0;\n cmdHistory: CmdHistory;\n logger: CaptionsLogger;\n\n constructor(field: SupportedField, out1: OutputFilter, out2: OutputFilter) {\n const logger = new CaptionsLogger();\n this.channels = [\n null,\n new Cea608Channel(field, out1, logger),\n new Cea608Channel(field + 1, out2, logger),\n ];\n this.cmdHistory = createCmdHistory();\n this.logger = logger;\n }\n\n getHandler(channel: number) {\n return (this.channels[channel] as Cea608Channel).getHandler();\n }\n\n setHandler(channel: number, newHandler: OutputFilter) {\n (this.channels[channel] as Cea608Channel).setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData(time: number | null, byteList: number[]) {\n let cmdFound: boolean;\n let a: number;\n let b: number;\n let charsFound: number[] | boolean | null = false;\n\n this.logger.time = time;\n\n for (let i = 0; i < byteList.length; i += 2) {\n a = byteList[i] & 0x7f;\n b = byteList[i + 1] & 0x7f;\n if (a === 0 && b === 0) {\n continue;\n } else {\n this.logger.log(\n VerboseLevel.DATA,\n '[' +\n numArrayToHexArray([byteList[i], byteList[i + 1]]) +\n '] -> (' +\n numArrayToHexArray([a, b]) +\n ')'\n );\n }\n\n cmdFound = this.parseCmd(a, b);\n\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n const currChNr = this.currentChannel;\n if (currChNr && currChNr > 0) {\n const channel = this.channels[currChNr] as Cea608Channel;\n channel.insertChars(charsFound);\n } else {\n this.logger.log(\n VerboseLevel.WARNING,\n 'No channel found yet. TEXT-MODE?'\n );\n }\n }\n }\n if (!cmdFound && !charsFound) {\n this.logger.log(\n VerboseLevel.WARNING,\n \"Couldn't parse cleaned data \" +\n numArrayToHexArray([a, b]) +\n ' orig: ' +\n numArrayToHexArray([byteList[i], byteList[i + 1]])\n );\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns True if a command was found\n */\n parseCmd(a: number, b: number): boolean {\n const { cmdHistory } = this;\n const cond1 =\n (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) &&\n b >= 0x20 &&\n b <= 0x2f;\n const cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped'\n );\n return true;\n }\n\n const chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;\n const channel = this.channels[chNr] as Cea608Channel;\n\n if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2a) {\n channel.ccTR();\n } else if (b === 0x2b) {\n channel.ccRTD();\n } else if (b === 0x2c) {\n channel.ccEDM();\n } else if (b === 0x2d) {\n channel.ccCR();\n } else if (b === 0x2e) {\n channel.ccENM();\n } else if (b === 0x2f) {\n channel.ccEOC();\n }\n } else {\n // a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n */\n parseMidrow(a: number, b: number): boolean {\n let chNr: number = 0;\n\n if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currentChannel) {\n this.logger.log(\n VerboseLevel.ERROR,\n 'Mismatch channel in midrow parsing'\n );\n return false;\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.ccMIDROW(b);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'MIDROW (' + numArrayToHexArray([a, b]) + ')'\n );\n return true;\n }\n return false;\n }\n\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC(a: number, b: number): boolean {\n let row: number;\n const cmdHistory = this.cmdHistory;\n\n const case1 =\n ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1f)) &&\n b >= 0x40 &&\n b <= 0x7f;\n const case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;\n if (!(case1 || case2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n return true; // Repeated commands are dropped (once)\n }\n\n const chNr: Channels = a <= 0x17 ? 1 : 2;\n\n if (b >= 0x40 && b <= 0x5f) {\n row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];\n } else {\n // 0x60 <= b <= 0x7F\n row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.setPAC(this.interpretPAC(row, b));\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns pacData with style parameters\n */\n interpretPAC(row: number, byte: number): PACData {\n let pacIndex;\n const pacData: PACData = {\n color: null,\n italics: false,\n indent: null,\n underline: false,\n row: row,\n };\n\n if (byte > 0x5f) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n 'white',\n ][Math.floor(pacIndex / 2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars(a: number, b: number): number[] | null {\n let channelNr: Channels;\n let charCodes: number[] | null = null;\n let charCode1: number | null = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let oneCode;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n\n this.logger.log(\n VerboseLevel.INFO,\n \"Special char '\" + getCharForByte(oneCode) + \"' in channel \" + channelNr\n );\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = b === 0 ? [a] : [a, b];\n }\n if (charCodes) {\n const hexCodes = numArrayToHexArray(charCodes);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Char codes = ' + hexCodes.join(',')\n );\n setLastCmd(a, b, this.cmdHistory);\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns True if background attributes are found\n */\n parseBackgroundAttributes(a: number, b: number): boolean {\n const case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;\n const case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;\n if (!(case1 || case2)) {\n return false;\n }\n let index: number;\n const bkgData: Partial<PenStyles> = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b - 0x20) / 2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n const chNr: Channels = a <= 0x17 ? 1 : 2;\n const channel: Cea608Channel = this.channels[chNr] as Cea608Channel;\n channel.setBkgData(bkgData);\n setLastCmd(a, b, this.cmdHistory);\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset() {\n for (let i = 0; i < Object.keys(this.channels).length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.reset();\n }\n }\n this.cmdHistory = createCmdHistory();\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime(t: number) {\n for (let i = 0; i < this.channels.length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.cueSplitAtTime(t);\n }\n }\n }\n}\n\nfunction setLastCmd(\n a: number | null,\n b: number | null,\n cmdHistory: CmdHistory\n) {\n cmdHistory.a = a;\n cmdHistory.b = b;\n}\n\nfunction hasCmdRepeated(a: number, b: number, cmdHistory: CmdHistory) {\n return cmdHistory.a === a && cmdHistory.b === b;\n}\n\nfunction createCmdHistory(): CmdHistory {\n return {\n a: null,\n b: null,\n };\n}\n\nexport default Cea608Parser;\n","import type { TimelineController } from '../controller/timeline-controller';\nimport type { CaptionScreen } from './cea-608-parser';\n\nexport default class OutputFilter {\n private timelineController: TimelineController;\n private cueRanges: Array<[number, number]> = [];\n private trackName: string;\n private startTime: number | null = null;\n private endTime: number | null = null;\n private screen: CaptionScreen | null = null;\n\n constructor(timelineController: TimelineController, trackName: string) {\n this.timelineController = timelineController;\n this.trackName = trackName;\n }\n\n dispatchCue() {\n if (this.startTime === null) {\n return;\n }\n\n this.timelineController.addCues(\n this.trackName,\n this.startTime,\n this.endTime as number,\n this.screen as CaptionScreen,\n this.cueRanges\n );\n this.startTime = null;\n }\n\n newCue(startTime: number, endTime: number, screen: CaptionScreen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\n }\n\n reset() {\n this.cueRanges = [];\n this.startTime = null;\n }\n}\n","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ndeclare interface VTTCuePolyfill extends VTTCue {\n new (...args): VTTCuePolyfill;\n hasBeenReset: boolean;\n displayState: void;\n}\n\nexport default (function () {\n if (typeof self !== 'undefined' && self.VTTCue) {\n return self.VTTCue;\n }\n\n const AllowedDirections = ['', 'lr', 'rl'] as const;\n type Direction = (typeof AllowedDirections)[number];\n\n const AllowedAlignments = [\n 'start',\n 'middle',\n 'end',\n 'left',\n 'right',\n ] as const;\n type Alignment = (typeof AllowedAlignments)[number];\n\n function isAllowedValue<T, A>(allowed: T, value: string): A | false {\n if (typeof value !== 'string') {\n return false;\n }\n // necessary for assuring the generic conforms to the Array interface\n if (!Array.isArray(allowed)) {\n return false;\n }\n // reset the type so that the next narrowing works well\n const lcValue = value.toLowerCase() as any;\n // use the allow list to narrow the type to a specific subset of strings\n if (~allowed.indexOf(lcValue)) {\n return lcValue;\n }\n\n return false;\n }\n\n function findDirectionSetting(value: string) {\n return isAllowedValue<typeof AllowedDirections, Direction>(\n AllowedDirections,\n value\n );\n }\n\n function findAlignSetting(value: string) {\n return isAllowedValue<typeof AllowedAlignments, Alignment>(\n AllowedAlignments,\n value\n );\n }\n\n function extend(obj: Record<string, any>, ...rest: Record<string, any>[]) {\n let i = 1;\n for (; i < arguments.length; i++) {\n const cobj = arguments[i];\n for (const p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue(startTime: number, endTime: number, text: string) {\n const cue = this as VTTCuePolyfill;\n const baseObj = { enumerable: true };\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical: Direction = '';\n let _snapToLines = true;\n let _line: number | 'auto' = 'auto';\n let _lineAlign: Alignment = 'start';\n let _position = 50;\n let _positionAlign: Alignment = 'middle';\n let _size = 50;\n let _align: Alignment = 'middle';\n\n Object.defineProperty(\n cue,\n 'id',\n extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value: string) {\n _id = '' + value;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'pauseOnExit',\n extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value: boolean) {\n _pauseOnExit = !!value;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'startTime',\n extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value: number) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n\n _startTime = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'endTime',\n extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value: number) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n\n _endTime = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'text',\n extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value: string) {\n _text = '' + value;\n this.hasBeenReset = true;\n },\n })\n );\n\n // todo: implement VTTRegion polyfill?\n Object.defineProperty(\n cue,\n 'region',\n extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value: any) {\n _region = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'vertical',\n extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value: string) {\n const setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _vertical = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'snapToLines',\n extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value: boolean) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'line',\n extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value: number | 'auto') {\n if (typeof value !== 'number' && value !== 'auto') {\n throw new SyntaxError(\n 'An invalid number or illegal string was specified.'\n );\n }\n\n _line = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'lineAlign',\n extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _lineAlign = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'position',\n extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value: number) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n\n _position = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'positionAlign',\n extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _positionAlign = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'size',\n extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value: number) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n\n _size = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'align',\n extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _align = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = undefined;\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n const WebVTT = (self as any).WebVTT;\n return WebVTT.convertCueToDOMTree(self, this.text);\n };\n // this is a polyfill hack\n return VTTCue as any as VTTCuePolyfill;\n})();\n","/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js\n */\n\nimport VTTCue from './vttcue';\n\nclass StringDecoder {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n decode(data: string | any, options?: Object): string | never {\n if (!data) {\n return '';\n }\n\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n\n return decodeURIComponent(encodeURIComponent(data));\n }\n}\n\n// Try to parse input as a time stamp.\nexport function parseTimeStamp(input: string) {\n function computeSeconds(h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);\n }\n\n const m = input.match(/^(?:(\\d+):)?(\\d{2}):(\\d{2})(\\.\\d+)?/);\n if (!m) {\n return null;\n }\n\n if (parseFloat(m[2]) > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[2], m[3], 0, m[4]);\n }\n // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3], m[4]);\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nclass Settings {\n private readonly values: { [key: string]: any } = Object.create(null);\n\n // Only accept the first assignment to any key.\n set(k: string, v: any) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n }\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get(k: string, dflt?: any, defaultKey?: string): any {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n\n return this.has(k) ? this.values[k] : dflt;\n }\n // Check whether we have a value for a key.\n has(k: string): boolean {\n return k in this.values;\n }\n // Accept a setting if its one of the given alternatives.\n alt(k: string, v: any, a: any[]) {\n for (let n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n }\n // Accept a setting if its a valid (signed) integer.\n integer(k: string, v: any) {\n if (/^-?\\d+$/.test(v)) {\n // integer\n this.set(k, parseInt(v, 10));\n }\n }\n // Accept a setting if its a valid percentage.\n percent(k: string, v: any): boolean {\n if (/^([\\d]{1,3})(\\.[\\d]*)?%$/.test(v)) {\n const percent = parseFloat(v);\n if (percent >= 0 && percent <= 100) {\n this.set(k, percent);\n return true;\n }\n }\n return false;\n }\n}\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interpret each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions(\n input: string,\n callback: (k: string, v: any) => void,\n keyValueDelim: RegExp,\n groupDelim?: RegExp\n) {\n const groups = groupDelim ? input.split(groupDelim) : [input];\n for (const i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n const kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n const k = kv[0];\n const v = kv[1];\n callback(k, v);\n }\n}\n\nconst defaults = new VTTCue(0, 0, '');\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nconst center = (defaults.align as string) === 'middle' ? 'middle' : 'center';\n\nfunction parseCue(input: string, cue: VTTCue, regionList: Region[]) {\n // Remember the original input if we need to throw an error.\n const oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp(): number | never {\n const ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings(input: string, cue: VTTCue) {\n const settings = new Settings();\n\n parseOptions(\n input,\n function (k, v) {\n let vals;\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (let i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n vals = v.split(',');\n settings.integer(k, vals[0]);\n if (settings.percent(k, vals[0])) {\n settings.set('snapToLines', false);\n }\n\n settings.alt(k, vals[0], ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], [\n 'start',\n center,\n 'end',\n 'line-left',\n 'line-right',\n 'auto',\n ]);\n }\n\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n },\n /:/,\n /\\s/\n );\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n let line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n let position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position =\n cue.align === 'start' || cue.align === 'left'\n ? 0\n : cue.align === 'end' || cue.align === 'right'\n ? 100\n : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace() {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.slice(0, 3) !== '-->') {\n // (3) next characters must match '-->'\n throw new Error(\n \"Malformed time stamp (time stamps must be separated by '-->'): \" + oInput\n );\n }\n input = input.slice(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nexport function fixLineBreaks(input: string): string {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\ntype Region = {\n id: string;\n region: any;\n};\n\nexport class VTTParser {\n private state:\n | 'INITIAL'\n | 'HEADER'\n | 'ID'\n | 'CUE'\n | 'CUETEXT'\n | 'NOTE'\n | 'BADWEBVTT'\n | 'BADCUE' = 'INITIAL';\n private buffer: string = '';\n private decoder: StringDecoder = new StringDecoder();\n private regionList: Region[] = [];\n private cue: VTTCue | null = null;\n public oncue?: (cue: VTTCue) => void;\n public onparsingerror?: (error: Error) => void;\n public onflush?: () => void;\n\n parse(data?: string): VTTParser {\n const _this = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n _this.buffer += _this.decoder.decode(data, { stream: true });\n }\n\n function collectNextLine(): string {\n let buffer: string = _this.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (\n pos < buffer.length &&\n buffer[pos] !== '\\r' &&\n buffer[pos] !== '\\n'\n ) {\n ++pos;\n }\n\n const line: string = buffer.slice(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n\n _this.buffer = buffer.slice(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader(input) {\n parseOptions(\n input,\n function (k, v) {\n // switch (k) {\n // case 'region':\n // 3.3 WebVTT region metadata header syntax\n // console.log('parse region', v);\n // parseRegion(v);\n // break;\n // }\n },\n /:/\n );\n }\n\n // 5.1 WebVTT file parsing.\n try {\n let line: string = '';\n if (_this.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(_this.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n const m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!m?.[0]) {\n throw new Error('Malformed WebVTT signature.');\n }\n\n _this.state = 'HEADER';\n }\n\n let alreadyCollectedLine = false;\n while (_this.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(_this.buffer)) {\n return this;\n }\n\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n\n switch (_this.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n _this.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n _this.state = 'ID';\n }\n\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n _this.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n\n _this.cue = new VTTCue(0, 0, '');\n _this.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n _this.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /* falls through */\n case 'CUE':\n // 40 - Collect cue timings and settings.\n if (!_this.cue) {\n _this.state = 'BADCUE';\n continue;\n }\n try {\n parseCue(line, _this.cue, _this.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n _this.cue = null;\n _this.state = 'BADCUE';\n continue;\n }\n _this.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n {\n const hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || (hasSubstring && (alreadyCollectedLine = true))) {\n // We are done parsing self cue.\n if (_this.oncue && _this.cue) {\n _this.oncue(_this.cue);\n }\n\n _this.cue = null;\n _this.state = 'ID';\n continue;\n }\n if (_this.cue === null) {\n continue;\n }\n\n if (_this.cue.text) {\n _this.cue.text += '\\n';\n }\n _this.cue.text += line;\n }\n continue;\n case 'BADCUE':\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n _this.state = 'ID';\n }\n }\n }\n } catch (e) {\n // If we are currently parsing a cue, report what we have.\n if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {\n _this.oncue(_this.cue);\n }\n\n _this.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n }\n\n flush(): VTTParser {\n const _this = this;\n try {\n // Finish decoding the stream.\n // _this.buffer += _this.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (_this.cue || _this.state === 'HEADER') {\n _this.buffer += '\\n\\n';\n _this.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n if (_this.onparsingerror) {\n _this.onparsingerror(e);\n }\n }\n if (_this.onflush) {\n _this.onflush();\n }\n\n return this;\n }\n}\n","import { VTTParser } from './vttparser';\nimport { utf8ArrayToStr } from '../demux/id3';\nimport {\n RationalTimestamp,\n toMpegTsClockFromTimescale,\n} from './timescale-conversion';\nimport { normalizePts } from '../remux/mp4-remuxer';\nimport type { VTTCCs } from '../types/vtt';\n\nconst LINEBREAKS = /\\r\\n|\\n\\r|\\n|\\r/g;\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function (\n inputString: string,\n searchString: string,\n position: number = 0\n) {\n return (\n inputString.slice(position, position + searchString.length) === searchString\n );\n};\n\nconst cueString2millis = function (timeString: string) {\n let ts = parseInt(timeString.slice(-3));\n const secs = parseInt(timeString.slice(-6, -4));\n const mins = parseInt(timeString.slice(-9, -7));\n const hours =\n timeString.length > 9\n ? parseInt(timeString.substring(0, timeString.indexOf(':')))\n : 0;\n\n if (\n !Number.isFinite(ts) ||\n !Number.isFinite(secs) ||\n !Number.isFinite(mins) ||\n !Number.isFinite(hours)\n ) {\n throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);\n }\n\n ts += 1000 * secs;\n ts += 60 * 1000 * mins;\n ts += 60 * 60 * 1000 * hours;\n\n return ts;\n};\n\n// From https://github.com/darkskyapp/string-hash\nconst hash = function (text: string) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = (hash * 33) ^ text.charCodeAt(--i);\n }\n\n return (hash >>> 0).toString();\n};\n\n// Create a unique hash id for a cue based on start/end times and text.\n// This helps timeline-controller to avoid showing repeated captions.\nexport function generateCueId(\n startTime: number,\n endTime: number,\n text: string\n) {\n return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);\n}\n\nconst calculateOffset = function (vttCCs: VTTCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || (!prevCC.new && currCC.new)) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while (prevCC?.new) {\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n\n vttCCs.presentationOffset = presentationTime;\n};\n\nexport function parseWebVTT(\n vttByteArray: ArrayBuffer,\n initPTS: RationalTimestamp | undefined,\n vttCCs: VTTCCs,\n cc: number,\n timeOffset: number,\n callBack: (cues: VTTCue[]) => void,\n errorCallBack: (error: Error) => void\n) {\n const parser = new VTTParser();\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n // Uint8Array.prototype.reduce is not implemented in IE11\n const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray))\n .trim()\n .replace(LINEBREAKS, '\\n')\n .split('\\n');\n const cues: VTTCue[] = [];\n const init90kHz = initPTS\n ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale)\n : 0;\n let cueTime = '00:00.000';\n let timestampMapMPEGTS = 0;\n let timestampMapLOCAL = 0;\n let parsingError: Error;\n let inHeader = true;\n\n parser.oncue = function (cue: VTTCue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n const currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Calculate subtitle PTS offset\n const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;\n\n // Update offsets for new discontinuities\n if (currCC?.new) {\n if (timestampMapLOCAL !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);\n }\n }\n if (webVttMpegTsMapOffset) {\n if (!initPTS) {\n parsingError = new Error('Missing initPTS for VTT MPEGTS');\n return;\n }\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;\n }\n\n const duration = cue.endTime - cue.startTime;\n const startTime =\n normalizePts(\n (cue.startTime + cueOffset - timestampMapLOCAL) * 90000,\n timeOffset * 90000\n ) / 90000;\n cue.startTime = Math.max(startTime, 0);\n cue.endTime = Math.max(startTime + duration, 0);\n\n //trim trailing webvtt block whitespaces\n const text = cue.text.trim();\n\n // Fix encoding of special characters\n cue.text = decodeURIComponent(encodeURIComponent(text));\n\n // If the cue was not assigned an id from the VTT file (line above the content), create one.\n if (!cue.id) {\n cue.id = generateCueId(cue.startTime, cue.endTime, text);\n }\n\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n\n parser.onparsingerror = function (error: Error) {\n parsingError = error;\n };\n\n parser.onflush = function () {\n if (parsingError) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach((line) => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n // Extract LOCAL and MPEGTS.\n line\n .slice(16)\n .split(',')\n .forEach((timestamp) => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.slice(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n timestampMapMPEGTS = parseInt(timestamp.slice(7));\n }\n });\n try {\n // Convert cue time to seconds\n timestampMapLOCAL = cueString2millis(cueTime) / 1000;\n } catch (error) {\n parsingError = error;\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line + '\\n');\n });\n\n parser.flush();\n}\n","import { findBox } from './mp4-tools';\nimport { parseTimeStamp } from './vttparser';\nimport VTTCue from './vttcue';\nimport { utf8ArrayToStr } from '../demux/id3';\nimport {\n RationalTimestamp,\n toTimescaleFromScale,\n} from './timescale-conversion';\nimport { generateCueId } from './webvtt-parser';\n\nexport const IMSC1_CODEC = 'stpp.ttml.im1t';\n\n// Time format: h:m:s:frames(.subframes)\nconst HMSF_REGEX = /^(\\d{2,}):(\\d{2}):(\\d{2}):(\\d{2})\\.?(\\d+)?$/;\n\n// Time format: hours, minutes, seconds, milliseconds, frames, ticks\nconst TIME_UNIT_REGEX = /^(\\d*(?:\\.\\d*)?)(h|m|s|ms|f|t)$/;\n\nconst textAlignToLineAlign: Partial<Record<string, LineAlignSetting>> = {\n left: 'start',\n center: 'center',\n right: 'end',\n start: 'start',\n end: 'end',\n};\n\nexport function parseIMSC1(\n payload: ArrayBuffer,\n initPTS: RationalTimestamp,\n callBack: (cues: Array<VTTCue>) => any,\n errorCallBack: (error: Error) => any\n) {\n const results = findBox(new Uint8Array(payload), ['mdat']);\n if (results.length === 0) {\n errorCallBack(new Error('Could not parse IMSC1 mdat'));\n return;\n }\n\n const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));\n\n const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);\n\n try {\n ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));\n } catch (error) {\n errorCallBack(error);\n }\n}\n\nfunction parseTTML(ttml: string, syncTime: number): Array<VTTCue> {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(ttml, 'text/xml');\n const tt = xmlDoc.getElementsByTagName('tt')[0];\n if (!tt) {\n throw new Error('Invalid ttml');\n }\n const defaultRateInfo = {\n frameRate: 30,\n subFrameRate: 1,\n frameRateMultiplier: 0,\n tickRate: 0,\n };\n const rateInfo: Object = Object.keys(defaultRateInfo).reduce(\n (result, key) => {\n result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];\n return result;\n },\n {}\n );\n\n const trim = tt.getAttribute('xml:space') !== 'preserve';\n\n const styleElements = collectionToDictionary(\n getElementCollection(tt, 'styling', 'style')\n );\n const regionElements = collectionToDictionary(\n getElementCollection(tt, 'layout', 'region')\n );\n const cueElements = getElementCollection(tt, 'body', '[begin]');\n\n return [].map\n .call(cueElements, (cueElement) => {\n const cueText = getTextContent(cueElement, trim);\n\n if (!cueText || !cueElement.hasAttribute('begin')) {\n return null;\n }\n const startTime = parseTtmlTime(\n cueElement.getAttribute('begin'),\n rateInfo\n );\n const duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);\n let endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);\n if (startTime === null) {\n throw timestampParsingError(cueElement);\n }\n if (endTime === null) {\n if (duration === null) {\n throw timestampParsingError(cueElement);\n }\n endTime = startTime + duration;\n }\n const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);\n cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);\n\n const region = regionElements[cueElement.getAttribute('region')];\n const style = styleElements[cueElement.getAttribute('style')];\n\n // Apply styles to cue\n const styles = getTtmlStyles(region, style, styleElements);\n const { textAlign } = styles;\n if (textAlign) {\n // cue.positionAlign not settable in FF~2016\n const lineAlign = textAlignToLineAlign[textAlign];\n if (lineAlign) {\n cue.lineAlign = lineAlign;\n }\n cue.align = textAlign as AlignSetting;\n }\n Object.assign(cue, styles);\n\n return cue;\n })\n .filter((cue) => cue !== null);\n}\n\nfunction getElementCollection(\n fromElement,\n parentName,\n childName\n): Array<HTMLElement> {\n const parent = fromElement.getElementsByTagName(parentName)[0];\n if (parent) {\n return [].slice.call(parent.querySelectorAll(childName));\n }\n return [];\n}\n\nfunction collectionToDictionary(elementsWithId: Array<HTMLElement>): {\n [id: string]: HTMLElement;\n} {\n return elementsWithId.reduce((dict, element: HTMLElement) => {\n const id = element.getAttribute('xml:id');\n if (id) {\n dict[id] = element;\n }\n return dict;\n }, {});\n}\n\nfunction getTextContent(element, trim): string {\n return [].slice.call(element.childNodes).reduce((str, node, i) => {\n if (node.nodeName === 'br' && i) {\n return str + '\\n';\n }\n if (node.childNodes?.length) {\n return getTextContent(node, trim);\n } else if (trim) {\n return str + node.textContent.trim().replace(/\\s+/g, ' ');\n }\n return str + node.textContent;\n }, '');\n}\n\nfunction getTtmlStyles(\n region,\n style,\n styleElements\n): { [style: string]: string } {\n const ttsNs = 'http://www.w3.org/ns/ttml#styling';\n let regionStyle = null;\n const styleAttributes = [\n 'displayAlign',\n 'textAlign',\n 'color',\n 'backgroundColor',\n 'fontSize',\n 'fontFamily',\n // 'fontWeight',\n // 'lineHeight',\n // 'wrapOption',\n // 'fontStyle',\n // 'direction',\n // 'writingMode'\n ];\n\n const regionStyleName = region?.hasAttribute('style')\n ? region.getAttribute('style')\n : null;\n\n if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {\n regionStyle = styleElements[regionStyleName];\n }\n\n return styleAttributes.reduce((styles, name) => {\n const value =\n getAttributeNS(style, ttsNs, name) ||\n getAttributeNS(region, ttsNs, name) ||\n getAttributeNS(regionStyle, ttsNs, name);\n if (value) {\n styles[name] = value;\n }\n return styles;\n }, {});\n}\n\nfunction getAttributeNS(element, ns, name): string | null {\n if (!element) {\n return null;\n }\n return element.hasAttributeNS(ns, name)\n ? element.getAttributeNS(ns, name)\n : null;\n}\n\nfunction timestampParsingError(node) {\n return new Error(`Could not parse ttml timestamp ${node}`);\n}\n\nfunction parseTtmlTime(timeAttributeValue, rateInfo): number | null {\n if (!timeAttributeValue) {\n return null;\n }\n let seconds: number | null = parseTimeStamp(timeAttributeValue);\n if (seconds === null) {\n if (HMSF_REGEX.test(timeAttributeValue)) {\n seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);\n } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {\n seconds = parseTimeUnits(timeAttributeValue, rateInfo);\n }\n }\n return seconds;\n}\n\nfunction parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo): number {\n const m = HMSF_REGEX.exec(timeAttributeValue) as Array<any>;\n const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;\n return (\n (m[1] | 0) * 3600 +\n (m[2] | 0) * 60 +\n (m[3] | 0) +\n frames / rateInfo.frameRate\n );\n}\n\nfunction parseTimeUnits(timeAttributeValue, rateInfo): number {\n const m = TIME_UNIT_REGEX.exec(timeAttributeValue) as Array<any>;\n const value = Number(m[1]);\n const unit = m[2];\n switch (unit) {\n case 'h':\n return value * 3600;\n case 'm':\n return value * 60;\n case 'ms':\n return value * 1000;\n case 'f':\n return value / rateInfo.frameRate;\n case 't':\n return value / rateInfo.tickRate;\n }\n return value;\n}\n","import { Events } from '../events';\nimport Cea608Parser, { CaptionScreen } from '../utils/cea-608-parser';\nimport OutputFilter from '../utils/output-filter';\nimport { parseWebVTT } from '../utils/webvtt-parser';\nimport {\n sendAddTrackEvent,\n clearCurrentCues,\n addCueToTrack,\n removeCuesInRange,\n} from '../utils/texttrack-utils';\nimport { subtitleOptionsIdentical } from '../utils/media-option-attributes';\nimport { parseIMSC1, IMSC1_CODEC } from '../utils/imsc1-ttml-parser';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Fragment } from '../loader/fragment';\nimport {\n FragParsingUserdataData,\n FragLoadedData,\n FragDecryptedData,\n MediaAttachingData,\n ManifestLoadedData,\n InitPTSFoundData,\n SubtitleTracksUpdatedData,\n BufferFlushingData,\n FragLoadingData,\n} from '../types/events';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { HlsConfig } from '../config';\nimport type { CuesInterface } from '../utils/cues';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport type { VTTCCs } from '../types/vtt';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\ntype TrackProperties = {\n label: string;\n languageCode: string;\n media?: MediaPlaylist;\n};\n\ntype NonNativeCaptionsTrack = {\n _id?: string;\n label: string;\n kind: string;\n default: boolean;\n closedCaptions?: MediaPlaylist;\n subtitleTrack?: MediaPlaylist;\n};\n\nexport class TimelineController implements ComponentAPI {\n private hls: Hls;\n private media: HTMLMediaElement | null = null;\n private config: HlsConfig;\n private enabled: boolean = true;\n private Cues: CuesInterface;\n private textTracks: Array<TextTrack> = [];\n private tracks: Array<MediaPlaylist> = [];\n private initPTS: RationalTimestamp[] = [];\n private unparsedVttFrags: Array<FragLoadedData | FragDecryptedData> = [];\n private captionsTracks: Record<string, TextTrack> = {};\n private nonNativeCaptionsTracks: Record<string, NonNativeCaptionsTrack> = {};\n private cea608Parser1!: Cea608Parser;\n private cea608Parser2!: Cea608Parser;\n private lastSn: number = -1;\n private lastPartIndex: number = -1;\n private prevCC: number = -1;\n private vttCCs: VTTCCs = newVTTCCs();\n private captionsProperties: {\n textTrack1: TrackProperties;\n textTrack2: TrackProperties;\n textTrack3: TrackProperties;\n textTrack4: TrackProperties;\n };\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.Cues = hls.config.cueHandler;\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode,\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode,\n },\n textTrack3: {\n label: this.config.captionsTextTrack3Label,\n languageCode: this.config.captionsTextTrack3LanguageCode,\n },\n textTrack4: {\n label: this.config.captionsTextTrack4Label,\n languageCode: this.config.captionsTextTrack4LanguageCode,\n },\n };\n\n if (this.config.enableCEA708Captions) {\n const channel1 = new OutputFilter(this, 'textTrack1');\n const channel2 = new OutputFilter(this, 'textTrack2');\n const channel3 = new OutputFilter(this, 'textTrack3');\n const channel4 = new OutputFilter(this, 'textTrack4');\n this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);\n this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);\n }\n\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_LOADED, this.onManifestLoaded, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n }\n\n public destroy(): void {\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_LOADED, this.onManifestLoaded, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n // @ts-ignore\n this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;\n }\n\n public addCues(\n trackName: string,\n startTime: number,\n endTime: number,\n screen: CaptionScreen,\n cueRanges: Array<[number, number]>\n ) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n let merged = false;\n for (let i = cueRanges.length; i--; ) {\n const cueRange = cueRanges[i];\n const overlap = intersection(\n cueRange[0],\n cueRange[1],\n startTime,\n endTime\n );\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if (overlap / (endTime - startTime) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n cueRanges.push([startTime, endTime]);\n }\n\n if (this.config.renderTextTracksNatively) {\n const track = this.captionsTracks[trackName];\n this.Cues.newCue(track, startTime, endTime, screen);\n } else {\n const cues = this.Cues.newCue(null, startTime, endTime, screen);\n this.hls.trigger(Events.CUES_PARSED, {\n type: 'captions',\n cues,\n track: trackName,\n });\n }\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n private onInitPtsFound(\n event: Events.INIT_PTS_FOUND,\n { frag, id, initPTS, timescale }: InitPTSFoundData\n ) {\n const { unparsedVttFrags } = this;\n if (id === 'main') {\n this.initPTS[frag.cc] = { baseTime: initPTS, timescale };\n }\n\n // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (unparsedVttFrags.length) {\n this.unparsedVttFrags = [];\n unparsedVttFrags.forEach((frag) => {\n this.onFragLoaded(Events.FRAG_LOADED, frag as FragLoadedData);\n });\n }\n }\n\n private getExistingTrack(trackName: string): TextTrack | null {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n const textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n public createCaptionsTrack(trackName: string) {\n if (this.config.renderTextTracksNatively) {\n this.createNativeTrack(trackName);\n } else {\n this.createNonNativeTrack(trackName);\n }\n }\n\n private createNativeTrack(trackName: string) {\n if (this.captionsTracks[trackName]) {\n return;\n }\n const { captionsProperties, captionsTracks, media } = this;\n const { label, languageCode } = captionsProperties[trackName];\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], media as HTMLMediaElement);\n }\n }\n\n private createNonNativeTrack(trackName: string) {\n if (this.nonNativeCaptionsTracks[trackName]) {\n return;\n }\n // Create a list of a single track for the provider to consume\n const trackProperties: TrackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n const label = trackProperties.label as string;\n const track = {\n _id: trackName,\n label,\n kind: 'captions',\n default: trackProperties.media ? !!trackProperties.media.default : false,\n closedCaptions: trackProperties.media,\n };\n this.nonNativeCaptionsTracks[trackName] = track;\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] });\n }\n\n private createTextTrack(\n kind: TextTrackKind,\n label: string,\n lang?: string\n ): TextTrack | undefined {\n const media = this.media;\n if (!media) {\n return;\n }\n return media.addTextTrack(kind, label, lang);\n }\n\n private onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n this.media = data.media;\n this._cleanTracks();\n }\n\n private onMediaDetaching() {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach((trackName) => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n this.nonNativeCaptionsTracks = {};\n }\n\n private onManifestLoading() {\n this.lastSn = -1; // Detect discontinuity in fragment parsing\n this.lastPartIndex = -1;\n this.prevCC = -1;\n this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests\n this._cleanTracks();\n this.tracks = [];\n this.captionsTracks = {};\n this.nonNativeCaptionsTracks = {};\n this.textTracks = [];\n this.unparsedVttFrags = [];\n this.initPTS = [];\n if (this.cea608Parser1 && this.cea608Parser2) {\n this.cea608Parser1.reset();\n this.cea608Parser2.reset();\n }\n }\n\n private _cleanTracks() {\n // clear outdated subtitles\n const { media } = this;\n if (!media) {\n return;\n }\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n\n private onSubtitleTracksUpdated(\n event: Events.SUBTITLE_TRACKS_UPDATED,\n data: SubtitleTracksUpdatedData\n ) {\n const tracks: Array<MediaPlaylist> = data.subtitleTracks || [];\n const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC);\n if (this.config.enableWebVTT || (hasIMSC1 && this.config.enableIMSC1)) {\n const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);\n if (listIsIdentical) {\n this.tracks = tracks;\n return;\n }\n this.textTracks = [];\n this.tracks = tracks;\n\n if (this.config.renderTextTracksNatively) {\n const inUseTracks = this.media ? this.media.textTracks : null;\n\n this.tracks.forEach((track, index) => {\n let textTrack: TextTrack | undefined;\n if (inUseTracks && index < inUseTracks.length) {\n let inUseTrack: TextTrack | null = null;\n\n for (let i = 0; i < inUseTracks.length; i++) {\n if (canReuseVttTextTrack(inUseTracks[i], track)) {\n inUseTrack = inUseTracks[i];\n break;\n }\n }\n\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (textTrack) {\n clearCurrentCues(textTrack);\n } else {\n const textTrackKind =\n this._captionsOrSubtitlesFromCharacteristics(track);\n textTrack = this.createTextTrack(\n textTrackKind,\n track.name,\n track.lang\n );\n if (textTrack) {\n textTrack.mode = 'disabled';\n }\n }\n if (textTrack) {\n (textTrack as any).groupId = track.groupId;\n this.textTracks.push(textTrack);\n }\n });\n } else if (this.tracks.length) {\n // Create a list of tracks for the provider to consume\n const tracksList = this.tracks.map((track) => {\n return {\n label: track.name,\n kind: track.type.toLowerCase(),\n default: track.default,\n subtitleTrack: track,\n };\n });\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {\n tracks: tracksList,\n });\n }\n }\n }\n\n private _captionsOrSubtitlesFromCharacteristics(\n track: MediaPlaylist\n ): TextTrackKind {\n if (track.attrs.CHARACTERISTICS) {\n const transcribesSpokenDialog = /transcribes-spoken-dialog/gi.test(\n track.attrs.CHARACTERISTICS\n );\n const describesMusicAndSound = /describes-music-and-sound/gi.test(\n track.attrs.CHARACTERISTICS\n );\n\n if (transcribesSpokenDialog && describesMusicAndSound) {\n return 'captions';\n }\n }\n\n return 'subtitles';\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ) {\n if (this.config.enableCEA708Captions && data.captions) {\n data.captions.forEach((captionsTrack) => {\n const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(\n captionsTrack.instreamId as string\n );\n if (!instreamIdMatch) {\n return;\n }\n const trackName = `textTrack${instreamIdMatch[1]}`;\n const trackProperties: TrackProperties =\n this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n trackProperties.label = captionsTrack.name;\n if (captionsTrack.lang) {\n // optional attribute\n trackProperties.languageCode = captionsTrack.lang;\n }\n trackProperties.media = captionsTrack;\n });\n }\n }\n\n private closedCaptionsForLevel(frag: Fragment): string | undefined {\n const level = this.hls.levels[frag.level];\n return level?.attrs['CLOSED-CAPTIONS'];\n }\n\n private onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {\n const { cea608Parser1, cea608Parser2, lastSn, lastPartIndex } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n return;\n }\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (data.frag.type === PlaylistLevelType.MAIN) {\n const sn = data.frag.sn;\n const partIndex = data?.part?.index ?? -1;\n if (\n !(\n sn === lastSn + 1 ||\n (sn === lastSn && partIndex === lastPartIndex + 1)\n )\n ) {\n cea608Parser1.reset();\n cea608Parser2.reset();\n }\n this.lastSn = sn as number;\n this.lastPartIndex = partIndex;\n }\n }\n\n private onFragLoaded(\n event: Events.FRAG_LOADED,\n data: FragDecryptedData | FragLoadedData\n ) {\n const { frag, payload } = data;\n if (frag.type === PlaylistLevelType.SUBTITLE) {\n // If fragment is subtitle type, parse as WebVTT.\n if (payload.byteLength) {\n const decryptData = frag.decryptdata;\n // fragment after decryption has a stats object\n const decrypted = 'stats' in data;\n // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n if (decryptData == null || !decryptData.encrypted || decrypted) {\n const trackPlaylistMedia = this.tracks[frag.level];\n const vttCCs = this.vttCCs;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = {\n start: frag.start,\n prevCC: this.prevCC,\n new: true,\n };\n this.prevCC = frag.cc;\n }\n if (\n trackPlaylistMedia &&\n trackPlaylistMedia.textCodec === IMSC1_CODEC\n ) {\n this._parseIMSC1(frag, payload);\n } else {\n this._parseVTTs(data);\n }\n }\n } else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag,\n error: new Error('Empty subtitle payload'),\n });\n }\n }\n }\n\n private _parseIMSC1(frag: Fragment, payload: ArrayBuffer) {\n const hls = this.hls;\n parseIMSC1(\n payload,\n this.initPTS[frag.cc],\n (cues) => {\n this._appendCues(cues, frag.level);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: true,\n frag: frag,\n });\n },\n (error) => {\n logger.log(`Failed to parse IMSC1: ${error}`);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag: frag,\n error,\n });\n }\n );\n }\n\n private _parseVTTs(data: FragDecryptedData | FragLoadedData) {\n const { frag, payload } = data;\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived\n const { initPTS, unparsedVttFrags } = this;\n const maxAvCC = initPTS.length - 1;\n if (!initPTS[frag.cc] && maxAvCC === -1) {\n unparsedVttFrags.push(data);\n return;\n }\n\n const hls = this.hls;\n // Parse the WebVTT file contents.\n const payloadWebVTT = frag.initSegment?.data\n ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload))\n : payload;\n parseWebVTT(\n payloadWebVTT,\n this.initPTS[frag.cc],\n this.vttCCs,\n frag.cc,\n frag.start,\n (cues) => {\n this._appendCues(cues, frag.level);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: true,\n frag: frag,\n });\n },\n (error) => {\n const missingInitPTS =\n error.message === 'Missing initPTS for VTT MPEGTS';\n if (missingInitPTS) {\n unparsedVttFrags.push(data);\n } else {\n this._fallbackToIMSC1(frag, payload);\n }\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${error}`);\n if (missingInitPTS && maxAvCC > frag.cc) {\n return;\n }\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag: frag,\n error,\n });\n }\n );\n }\n\n private _fallbackToIMSC1(frag: Fragment, payload: ArrayBuffer) {\n // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result\n const trackPlaylistMedia = this.tracks[frag.level];\n if (!trackPlaylistMedia.textCodec) {\n parseIMSC1(\n payload,\n this.initPTS[frag.cc],\n () => {\n trackPlaylistMedia.textCodec = IMSC1_CODEC;\n this._parseIMSC1(frag, payload);\n },\n () => {\n trackPlaylistMedia.textCodec = 'wvtt';\n }\n );\n }\n }\n\n private _appendCues(cues: VTTCue[], fragLevel: number) {\n const hls = this.hls;\n if (this.config.renderTextTracksNatively) {\n const textTrack = this.textTracks[fragLevel];\n // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.\n if (!textTrack || textTrack.mode === 'disabled') {\n return;\n }\n cues.forEach((cue) => addCueToTrack(textTrack, cue));\n } else {\n const currentTrack = this.tracks[fragLevel];\n if (!currentTrack) {\n return;\n }\n const track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;\n hls.trigger(Events.CUES_PARSED, { type: 'subtitles', cues, track });\n }\n }\n\n private onFragDecrypted(\n event: Events.FRAG_DECRYPTED,\n data: FragDecryptedData\n ) {\n const { frag } = data;\n if (frag.type === PlaylistLevelType.SUBTITLE) {\n this.onFragLoaded(Events.FRAG_LOADED, data as unknown as FragLoadedData);\n }\n }\n\n private onSubtitleTracksCleared() {\n this.tracks = [];\n this.captionsTracks = {};\n }\n\n private onFragParsingUserdata(\n event: Events.FRAG_PARSING_USERDATA,\n data: FragParsingUserdataData\n ) {\n const { cea608Parser1, cea608Parser2 } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n return;\n }\n\n const { frag, samples } = data;\n if (\n frag.type === PlaylistLevelType.MAIN &&\n this.closedCaptionsForLevel(frag) === 'NONE'\n ) {\n return;\n }\n // If the event contains captions (found in the bytes property), push all bytes into the parser immediately\n // It will create the proper timestamps based on the PTS value\n for (let i = 0; i < samples.length; i++) {\n const ccBytes = samples[i].bytes;\n if (ccBytes) {\n const ccdatas = this.extractCea608Data(ccBytes);\n cea608Parser1.addData(samples[i].pts, ccdatas[0]);\n cea608Parser2.addData(samples[i].pts, ccdatas[1]);\n }\n }\n }\n\n onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { startOffset, endOffset, endOffsetSubtitles, type }: BufferFlushingData\n ) {\n const { media } = this;\n if (!media || media.currentTime < endOffset) {\n return;\n }\n // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed\n // Forward cues are never removed because we can loose streamed 608 content from recent fragments\n if (!type || type === 'video') {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach((trackName) =>\n removeCuesInRange(captionsTracks[trackName], startOffset, endOffset)\n );\n }\n if (this.config.renderTextTracksNatively) {\n // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed\n if (startOffset === 0 && endOffsetSubtitles !== undefined) {\n const { textTracks } = this;\n Object.keys(textTracks).forEach((trackName) =>\n removeCuesInRange(\n textTracks[trackName],\n startOffset,\n endOffsetSubtitles\n )\n );\n }\n }\n }\n\n private extractCea608Data(byteArray: Uint8Array): number[][] {\n const actualCCBytes: number[][] = [[], []];\n const count = byteArray[0] & 0x1f;\n let position = 2;\n\n for (let j = 0; j < count; j++) {\n const tmpByte = byteArray[position++];\n const ccbyte1 = 0x7f & byteArray[position++];\n const ccbyte2 = 0x7f & byteArray[position++];\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n const ccValid = (0x04 & tmpByte) !== 0; // Support all four channels\n if (ccValid) {\n const ccType = 0x03 & tmpByte;\n if (\n 0x00 /* CEA608 field1*/ === ccType ||\n 0x01 /* CEA608 field2*/ === ccType\n ) {\n // Exclude CEA708 CC data.\n actualCCBytes[ccType].push(ccbyte1);\n actualCCBytes[ccType].push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nfunction canReuseVttTextTrack(\n inUseTrack: (TextTrack & { textTrack1?; textTrack2? }) | null,\n manifestTrack: MediaPlaylist\n): boolean {\n return (\n !!inUseTrack &&\n inUseTrack.label === manifestTrack.name &&\n !(inUseTrack.textTrack1 || inUseTrack.textTrack2)\n );\n}\n\nfunction intersection(x1: number, x2: number, y1: number, y2: number): number {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\n\nfunction newVTTCCs(): VTTCCs {\n return {\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0,\n prevCC: -1,\n new: true,\n },\n };\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} from '../types/events';\nimport StreamController from './stream-controller';\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 this.unregisterListener();\n if (this.hls.config.capLevelToPlayerSize) {\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.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.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 }\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 // 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 && this.mediaHeight > 0 && this.mediaWidth > 0) {\n const levels = this.hls.levels;\n if (levels.length) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);\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 this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\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 = (curLevel, nextLevel) => {\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\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if (\n (level.width >= width || level.height >= height) &&\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","/**\n * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport {\n getKeySystemsForConfig,\n getSupportedMediaKeySystemConfigurations,\n keySystemDomainToKeySystemFormat as keySystemToKeySystemFormat,\n KeySystemFormats,\n keySystemFormatToKeySystemDomain,\n KeySystemIds,\n keySystemIdToKeySystemDomain,\n} from '../utils/mediakeys-helper';\nimport {\n KeySystems,\n requestMediaKeySystemAccess,\n} from '../utils/mediakeys-helper';\nimport { strToUtf8array } from '../utils/keysystem-util';\nimport { base64Decode } from '../utils/numeric-encoding-utils';\nimport { DecryptData, LevelKey } from '../loader/level-key';\nimport Hex from '../utils/hex';\nimport { bin2str, parsePssh, parseSinf } from '../utils/mp4-tools';\nimport { EventEmitter } from 'eventemitter3';\nimport type Hls from '../hls';\nimport type { ComponentAPI } from '../types/component-api';\nimport type {\n MediaAttachedData,\n KeyLoadedData,\n ErrorData,\n ManifestLoadedData,\n} from '../types/events';\nimport type { EMEControllerConfig, HlsConfig, LoadPolicy } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type {\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n} from '../types/loader';\n\nconst LOGGER_PREFIX = '[eme]';\n\ninterface KeySystemAccessPromises {\n keySystemAccess: Promise<MediaKeySystemAccess>;\n mediaKeys?: Promise<MediaKeys>;\n certificate?: Promise<BufferSource | void>;\n}\n\nexport interface MediaKeySessionContext {\n keySystem: KeySystems;\n mediaKeys: MediaKeys;\n decryptdata: LevelKey;\n mediaKeysSession: MediaKeySession;\n keyStatus: MediaKeyStatus;\n licenseXhr?: XMLHttpRequest;\n}\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController implements ComponentAPI {\n public static CDMCleanupPromise: Promise<void> | void;\n\n private readonly hls: Hls;\n private readonly config: EMEControllerConfig & {\n loader: { new (confg: HlsConfig): Loader<LoaderContext> };\n certLoadPolicy: LoadPolicy;\n keyLoadPolicy: LoadPolicy;\n };\n private media: HTMLMediaElement | null = null;\n private keyFormatPromise: Promise<KeySystemFormats> | null = null;\n private keySystemAccessPromises: {\n [keysystem: string]: KeySystemAccessPromises;\n } = {};\n private _requestLicenseFailureCount: number = 0;\n private mediaKeySessions: MediaKeySessionContext[] = [];\n private keyIdToKeySessionPromise: {\n [keyId: string]: Promise<MediaKeySessionContext>;\n } = {};\n private setMediaKeysQueue: Promise<void>[] = EMEController.CDMCleanupPromise\n ? [EMEController.CDMCleanupPromise]\n : [];\n private onMediaEncrypted = this._onMediaEncrypted.bind(this);\n private onWaitingForKey = this._onWaitingForKey.bind(this);\n\n private debug: (msg: any) => void = logger.debug.bind(logger, LOGGER_PREFIX);\n private log: (msg: any) => void = logger.log.bind(logger, LOGGER_PREFIX);\n private warn: (msg: any) => void = logger.warn.bind(logger, LOGGER_PREFIX);\n private error: (msg: any) => void = logger.error.bind(logger, LOGGER_PREFIX);\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n\n public destroy() {\n this.unregisterListeners();\n this.onMediaDetached();\n // Remove any references that could be held in config options or callbacks\n const config = this.config;\n config.requestMediaKeySystemAccessFunc = null;\n config.licenseXhrSetup = config.licenseResponseCallback = undefined;\n config.drmSystems = config.drmSystemOptions = {};\n // @ts-ignore\n this.hls =\n this.onMediaEncrypted =\n this.onWaitingForKey =\n this.keyIdToKeySessionPromise =\n null as any;\n // @ts-ignore\n this.config = null;\n }\n\n private registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n\n private unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n\n private getLicenseServerUrl(keySystem: KeySystems): string | never {\n const { drmSystems, widevineLicenseUrl } = this.config;\n const keySystemConfiguration = drmSystems[keySystem];\n\n if (keySystemConfiguration) {\n return keySystemConfiguration.licenseUrl;\n }\n\n // For backward compatibility\n if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {\n return widevineLicenseUrl;\n }\n\n throw new Error(\n `no license server URL configured for key-system \"${keySystem}\"`\n );\n }\n\n private getServerCertificateUrl(keySystem: KeySystems): string | void {\n const { drmSystems } = this.config;\n const keySystemConfiguration = drmSystems[keySystem];\n\n if (keySystemConfiguration) {\n return keySystemConfiguration.serverCertificateUrl;\n } else {\n this.log(`No Server Certificate in config.drmSystems[\"${keySystem}\"]`);\n }\n }\n\n private attemptKeySystemAccess(\n keySystemsToAttempt: KeySystems[]\n ): Promise<{ keySystem: KeySystems; mediaKeys: MediaKeys }> {\n const levels = this.hls.levels;\n const uniqueCodec = (value: string | undefined, i, a): value is string =>\n !!value && a.indexOf(value) === i;\n const audioCodecs = levels\n .map((level) => level.audioCodec)\n .filter(uniqueCodec);\n const videoCodecs = levels\n .map((level) => level.videoCodec)\n .filter(uniqueCodec);\n if (audioCodecs.length + videoCodecs.length === 0) {\n videoCodecs.push('avc1.42e01e');\n }\n\n return new Promise(\n (\n resolve: (result: {\n keySystem: KeySystems;\n mediaKeys: MediaKeys;\n }) => void,\n reject: (Error) => void\n ) => {\n const attempt = (keySystems) => {\n const keySystem = keySystems.shift();\n this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs)\n .then((mediaKeys) => resolve({ keySystem, mediaKeys }))\n .catch((error) => {\n if (keySystems.length) {\n attempt(keySystems);\n } else if (error instanceof EMEKeyError) {\n reject(error);\n } else {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n error,\n fatal: true,\n },\n error.message\n )\n );\n }\n });\n };\n attempt(keySystemsToAttempt);\n }\n );\n }\n\n private requestMediaKeySystemAccess(\n keySystem: KeySystems,\n supportedConfigurations: MediaKeySystemConfiguration[]\n ): Promise<MediaKeySystemAccess> {\n const { requestMediaKeySystemAccessFunc } = this.config;\n if (!(typeof requestMediaKeySystemAccessFunc === 'function')) {\n let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;\n if (\n requestMediaKeySystemAccess === null &&\n self.location.protocol === 'http:'\n ) {\n errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;\n }\n return Promise.reject(new Error(errMessage));\n }\n\n return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);\n }\n\n private getMediaKeysPromise(\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[]\n ): Promise<MediaKeys> {\n // This can throw, but is caught in event handler callpath\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(\n keySystem,\n audioCodecs,\n videoCodecs,\n this.config.drmSystemOptions\n );\n const keySystemAccessPromises: KeySystemAccessPromises =\n this.keySystemAccessPromises[keySystem];\n let keySystemAccess = keySystemAccessPromises?.keySystemAccess;\n if (!keySystemAccess) {\n this.log(\n `Requesting encrypted media \"${keySystem}\" key-system access with config: ${JSON.stringify(\n mediaKeySystemConfigs\n )}`\n );\n keySystemAccess = this.requestMediaKeySystemAccess(\n keySystem,\n mediaKeySystemConfigs\n );\n const keySystemAccessPromises: KeySystemAccessPromises =\n (this.keySystemAccessPromises[keySystem] = {\n keySystemAccess,\n });\n keySystemAccess.catch((error) => {\n this.log(\n `Failed to obtain access to key-system \"${keySystem}\": ${error}`\n );\n });\n return keySystemAccess.then((mediaKeySystemAccess) => {\n this.log(\n `Access for key-system \"${mediaKeySystemAccess.keySystem}\" obtained`\n );\n\n const certificateRequest = this.fetchServerCertificate(keySystem);\n\n this.log(`Create media-keys for \"${keySystem}\"`);\n keySystemAccessPromises.mediaKeys = mediaKeySystemAccess\n .createMediaKeys()\n .then((mediaKeys) => {\n this.log(`Media-keys created for \"${keySystem}\"`);\n return certificateRequest.then((certificate) => {\n if (certificate) {\n return this.setMediaKeysServerCertificate(\n mediaKeys,\n keySystem,\n certificate\n );\n }\n return mediaKeys;\n });\n });\n\n keySystemAccessPromises.mediaKeys.catch((error) => {\n this.error(\n `Failed to create media-keys for \"${keySystem}\"}: ${error}`\n );\n });\n\n return keySystemAccessPromises.mediaKeys;\n });\n }\n return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys!);\n }\n\n private createMediaKeySessionContext({\n decryptdata,\n keySystem,\n mediaKeys,\n }: {\n decryptdata: LevelKey;\n keySystem: KeySystems;\n mediaKeys: MediaKeys;\n }): MediaKeySessionContext {\n this.log(\n `Creating key-system session \"${keySystem}\" keyId: ${Hex.hexDump(\n decryptdata.keyId! || []\n )}`\n );\n\n const mediaKeysSession = mediaKeys.createSession();\n\n const mediaKeySessionContext: MediaKeySessionContext = {\n decryptdata,\n keySystem,\n mediaKeys,\n mediaKeysSession,\n keyStatus: 'status-pending',\n };\n\n this.mediaKeySessions.push(mediaKeySessionContext);\n\n return mediaKeySessionContext;\n }\n\n private renewKeySession(mediaKeySessionContext: MediaKeySessionContext) {\n const decryptdata = mediaKeySessionContext.decryptdata;\n if (decryptdata.pssh) {\n const keySessionContext = this.createMediaKeySessionContext(\n mediaKeySessionContext\n );\n const keyId = this.getKeyIdString(decryptdata);\n const scheme = 'cenc';\n this.keyIdToKeySessionPromise[keyId] =\n this.generateRequestWithPreferredKeySession(\n keySessionContext,\n scheme,\n decryptdata.pssh,\n 'expired'\n );\n } else {\n this.warn(`Could not renew expired session. Missing pssh initData.`);\n }\n this.removeSession(mediaKeySessionContext);\n }\n\n private getKeyIdString(decryptdata: DecryptData | undefined): string | never {\n if (!decryptdata) {\n throw new Error('Could not read keyId of undefined decryptdata');\n }\n if (decryptdata.keyId === null) {\n throw new Error('keyId is null');\n }\n return Hex.hexDump(decryptdata.keyId);\n }\n\n private updateKeySession(\n mediaKeySessionContext: MediaKeySessionContext,\n data: Uint8Array\n ): Promise<void> {\n const keySession = mediaKeySessionContext.mediaKeysSession;\n this.log(\n `Updating key-session \"${keySession.sessionId}\" for keyID ${Hex.hexDump(\n mediaKeySessionContext.decryptdata?.keyId! || []\n )}\n } (data length: ${data ? data.byteLength : data})`\n );\n return keySession.update(data);\n }\n\n public selectKeySystemFormat(frag: Fragment): Promise<KeySystemFormats> {\n const keyFormats = Object.keys(frag.levelkeys || {}) as KeySystemFormats[];\n if (!this.keyFormatPromise) {\n this.log(\n `Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${\n frag.level\n }) key formats ${keyFormats.join(', ')}`\n );\n this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);\n }\n return this.keyFormatPromise;\n }\n\n private getKeyFormatPromise(\n keyFormats: KeySystemFormats[]\n ): Promise<KeySystemFormats> {\n return new Promise((resolve, reject) => {\n const keySystemsInConfig = getKeySystemsForConfig(this.config);\n const keySystemsToAttempt = keyFormats\n .map(keySystemFormatToKeySystemDomain)\n .filter(\n (value) => !!value && keySystemsInConfig.indexOf(value) !== -1\n ) as any as KeySystems[];\n return this.getKeySystemSelectionPromise(keySystemsToAttempt)\n .then(({ keySystem }) => {\n const keySystemFormat = keySystemToKeySystemFormat(keySystem);\n if (keySystemFormat) {\n resolve(keySystemFormat);\n } else {\n reject(\n new Error(`Unable to find format for key-system \"${keySystem}\"`)\n );\n }\n })\n .catch(reject);\n });\n }\n\n public loadKey(data: KeyLoadedData): Promise<MediaKeySessionContext> {\n const decryptdata = data.keyInfo.decryptdata;\n\n const keyId = this.getKeyIdString(decryptdata);\n const keyDetails = `(keyId: ${keyId} format: \"${decryptdata.keyFormat}\" method: ${decryptdata.method} uri: ${decryptdata.uri})`;\n\n this.log(`Starting session for key ${keyDetails}`);\n\n let keySessionContextPromise = this.keyIdToKeySessionPromise[keyId];\n if (!keySessionContextPromise) {\n keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] =\n this.getKeySystemForKeyPromise(decryptdata).then(\n ({ keySystem, mediaKeys }) => {\n this.throwIfDestroyed();\n this.log(\n `Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`\n );\n\n return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {\n this.throwIfDestroyed();\n const keySessionContext = this.createMediaKeySessionContext({\n keySystem,\n mediaKeys,\n decryptdata,\n });\n const scheme = 'cenc';\n return this.generateRequestWithPreferredKeySession(\n keySessionContext,\n scheme,\n decryptdata.pssh,\n 'playlist-key'\n );\n });\n }\n );\n\n keySessionContextPromise.catch((error) => this.handleError(error));\n }\n\n return keySessionContextPromise;\n }\n\n private throwIfDestroyed(message = 'Invalid state'): void | never {\n if (!this.hls) {\n throw new Error('invalid state');\n }\n }\n\n private handleError(error: EMEKeyError | Error) {\n if (!this.hls) {\n return;\n }\n this.error(error.message);\n if (error instanceof EMEKeyError) {\n this.hls.trigger(Events.ERROR, error.data);\n } else {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n error,\n fatal: true,\n });\n }\n }\n\n private getKeySystemForKeyPromise(\n decryptdata: LevelKey\n ): Promise<{ keySystem: KeySystems; mediaKeys: MediaKeys }> {\n const keyId = this.getKeyIdString(decryptdata);\n const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];\n if (!mediaKeySessionContext) {\n const keySystem = keySystemFormatToKeySystemDomain(\n decryptdata.keyFormat as KeySystemFormats\n );\n const keySystemsToAttempt = keySystem\n ? [keySystem]\n : getKeySystemsForConfig(this.config);\n return this.attemptKeySystemAccess(keySystemsToAttempt);\n }\n return mediaKeySessionContext;\n }\n\n private getKeySystemSelectionPromise(\n keySystemsToAttempt: KeySystems[]\n ): Promise<{ keySystem: KeySystems; mediaKeys: MediaKeys }> | never {\n if (!keySystemsToAttempt.length) {\n keySystemsToAttempt = getKeySystemsForConfig(this.config);\n }\n if (keySystemsToAttempt.length === 0) {\n throw new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,\n fatal: true,\n },\n `Missing key-system license configuration options ${JSON.stringify({\n drmSystems: this.config.drmSystems,\n })}`\n );\n }\n return this.attemptKeySystemAccess(keySystemsToAttempt);\n }\n\n private _onMediaEncrypted(event: MediaEncryptedEvent) {\n const { initDataType, initData } = event;\n this.debug(`\"${event.type}\" event: init data type: \"${initDataType}\"`);\n\n // Ignore event when initData is null\n if (initData === null) {\n return;\n }\n\n let keyId: Uint8Array | undefined;\n let keySystemDomain: KeySystems | undefined;\n\n if (\n initDataType === 'sinf' &&\n this.config.drmSystems[KeySystems.FAIRPLAY]\n ) {\n // Match sinf keyId to playlist skd://keyId=\n const json = bin2str(new Uint8Array(initData));\n try {\n const sinf = base64Decode(JSON.parse(json).sinf);\n const tenc = parseSinf(new Uint8Array(sinf));\n if (!tenc) {\n return;\n }\n keyId = tenc.subarray(8, 24);\n keySystemDomain = KeySystems.FAIRPLAY;\n } catch (error) {\n this.warn('Failed to parse sinf \"encrypted\" event message initData');\n return;\n }\n } else {\n // Support clear-lead key-session creation (otherwise depend on playlist keys)\n const psshInfo = parsePssh(initData);\n if (psshInfo === null) {\n return;\n }\n if (\n psshInfo.version === 0 &&\n psshInfo.systemId === KeySystemIds.WIDEVINE &&\n psshInfo.data\n ) {\n keyId = psshInfo.data.subarray(8, 24);\n }\n keySystemDomain = keySystemIdToKeySystemDomain(\n psshInfo.systemId as KeySystemIds\n );\n }\n\n if (!keySystemDomain || !keyId) {\n return;\n }\n\n const keyIdHex = Hex.hexDump(keyId);\n const { keyIdToKeySessionPromise, mediaKeySessions } = this;\n\n let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex];\n for (let i = 0; i < mediaKeySessions.length; i++) {\n // Match playlist key\n const keyContext = mediaKeySessions[i];\n const decryptdata = keyContext.decryptdata;\n if (decryptdata.pssh || !decryptdata.keyId) {\n continue;\n }\n const oldKeyIdHex = Hex.hexDump(decryptdata.keyId);\n if (\n keyIdHex === oldKeyIdHex ||\n decryptdata.uri.replace(/-/g, '').indexOf(keyIdHex) !== -1\n ) {\n keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex];\n delete keyIdToKeySessionPromise[oldKeyIdHex];\n decryptdata.pssh = new Uint8Array(initData);\n decryptdata.keyId = keyId;\n keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] =\n keySessionContextPromise.then(() => {\n return this.generateRequestWithPreferredKeySession(\n keyContext,\n initDataType,\n initData,\n 'encrypted-event-key-match'\n );\n });\n break;\n }\n }\n\n if (!keySessionContextPromise) {\n // Clear-lead key (not encountered in playlist)\n keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] =\n this.getKeySystemSelectionPromise([keySystemDomain]).then(\n ({ keySystem, mediaKeys }) => {\n this.throwIfDestroyed();\n const decryptdata = new LevelKey(\n 'ISO-23001-7',\n keyIdHex,\n keySystemToKeySystemFormat(keySystem) ?? ''\n );\n decryptdata.pssh = new Uint8Array(initData);\n decryptdata.keyId = keyId as Uint8Array;\n return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {\n this.throwIfDestroyed();\n const keySessionContext = this.createMediaKeySessionContext({\n decryptdata,\n keySystem,\n mediaKeys,\n });\n return this.generateRequestWithPreferredKeySession(\n keySessionContext,\n initDataType,\n initData,\n 'encrypted-event-no-match'\n );\n });\n }\n );\n }\n keySessionContextPromise.catch((error) => this.handleError(error));\n }\n\n private _onWaitingForKey(event: Event) {\n this.log(`\"${event.type}\" event`);\n }\n\n private attemptSetMediaKeys(\n keySystem: KeySystems,\n mediaKeys: MediaKeys\n ): Promise<void> {\n const queue = this.setMediaKeysQueue.slice();\n\n this.log(`Setting media-keys for \"${keySystem}\"`);\n // Only one setMediaKeys() can run at one time, and multiple setMediaKeys() operations\n // can be queued for execution for multiple key sessions.\n const setMediaKeysPromise = Promise.all(queue).then(() => {\n if (!this.media) {\n throw new Error(\n 'Attempted to set mediaKeys without media element attached'\n );\n }\n return this.media.setMediaKeys(mediaKeys);\n });\n this.setMediaKeysQueue.push(setMediaKeysPromise);\n return setMediaKeysPromise.then(() => {\n this.log(`Media-keys set for \"${keySystem}\"`);\n queue.push(setMediaKeysPromise!);\n this.setMediaKeysQueue = this.setMediaKeysQueue.filter(\n (p) => queue.indexOf(p) === -1\n );\n });\n }\n\n private generateRequestWithPreferredKeySession(\n context: MediaKeySessionContext,\n initDataType: string,\n initData: ArrayBuffer | null,\n reason:\n | 'playlist-key'\n | 'encrypted-event-key-match'\n | 'encrypted-event-no-match'\n | 'expired'\n ): Promise<MediaKeySessionContext> | never {\n const generateRequestFilter =\n this.config.drmSystems?.[context.keySystem]?.generateRequest;\n if (generateRequestFilter) {\n try {\n const mappedInitData: ReturnType<typeof generateRequestFilter> =\n generateRequestFilter.call(this.hls, initDataType, initData, context);\n if (!mappedInitData) {\n throw new Error(\n 'Invalid response from configured generateRequest filter'\n );\n }\n initDataType = mappedInitData.initDataType;\n initData = context.decryptdata.pssh = mappedInitData.initData\n ? new Uint8Array(mappedInitData.initData)\n : null;\n } catch (error) {\n this.warn(error.message);\n if (this.hls?.config.debug) {\n throw error;\n }\n }\n }\n\n if (initData === null) {\n this.log(`Skipping key-session request for \"${reason}\" (no initData)`);\n return Promise.resolve(context);\n }\n\n const keyId = this.getKeyIdString(context.decryptdata);\n this.log(\n `Generating key-session request for \"${reason}\": ${keyId} (init data type: ${initDataType} length: ${\n initData ? initData.byteLength : null\n })`\n );\n\n const licenseStatus = new EventEmitter();\n\n context.mediaKeysSession.onmessage = (event: MediaKeyMessageEvent) => {\n const keySession = context.mediaKeysSession;\n if (!keySession) {\n licenseStatus.emit('error', new Error('invalid state'));\n return;\n }\n const { messageType, message } = event;\n this.log(\n `\"${messageType}\" message event for session \"${keySession.sessionId}\" message size: ${message.byteLength}`\n );\n if (\n messageType === 'license-request' ||\n messageType === 'license-renewal'\n ) {\n this.renewLicense(context, message).catch((error) => {\n this.handleError(error);\n licenseStatus.emit('error', error);\n });\n } else if (messageType === 'license-release') {\n if (context.keySystem === KeySystems.FAIRPLAY) {\n this.updateKeySession(context, strToUtf8array('acknowledged'));\n this.removeSession(context);\n }\n } else {\n this.warn(`unhandled media key message type \"${messageType}\"`);\n }\n };\n\n context.mediaKeysSession.onkeystatuseschange = (\n event: MediaKeyMessageEvent\n ) => {\n const keySession = context.mediaKeysSession;\n if (!keySession) {\n licenseStatus.emit('error', new Error('invalid state'));\n return;\n }\n this.onKeyStatusChange(context);\n const keyStatus = context.keyStatus;\n licenseStatus.emit('keyStatus', keyStatus);\n if (keyStatus === 'expired') {\n this.warn(`${context.keySystem} expired for key ${keyId}`);\n this.renewKeySession(context);\n }\n };\n\n const keyUsablePromise = new Promise(\n (resolve: (value?: void) => void, reject) => {\n licenseStatus.on('error', reject);\n\n licenseStatus.on('keyStatus', (keyStatus) => {\n if (keyStatus.startsWith('usable')) {\n resolve();\n } else if (keyStatus === 'output-restricted') {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,\n fatal: false,\n },\n 'HDCP level output restricted'\n )\n );\n } else if (keyStatus === 'internal-error') {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,\n fatal: true,\n },\n `key status changed to \"${keyStatus}\"`\n )\n );\n } else if (keyStatus === 'expired') {\n reject(new Error('key expired while generating request'));\n } else {\n this.warn(`unhandled key status change \"${keyStatus}\"`);\n }\n });\n }\n );\n\n return context.mediaKeysSession\n .generateRequest(initDataType, initData)\n .then(() => {\n this.log(\n `Request generated for key-session \"${context.mediaKeysSession?.sessionId}\" keyId: ${keyId}`\n );\n })\n .catch((error) => {\n throw new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n error,\n fatal: false,\n },\n `Error generating key-session request: ${error}`\n );\n })\n .then(() => keyUsablePromise)\n .catch((error) => {\n licenseStatus.removeAllListeners();\n this.removeSession(context);\n throw error;\n })\n .then(() => {\n licenseStatus.removeAllListeners();\n return context;\n });\n }\n\n private onKeyStatusChange(mediaKeySessionContext: MediaKeySessionContext) {\n mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach(\n (status: MediaKeyStatus, keyId: BufferSource) => {\n this.log(\n `key status change \"${status}\" for keyStatuses keyId: ${Hex.hexDump(\n 'buffer' in keyId\n ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength)\n : new Uint8Array(keyId)\n )} session keyId: ${Hex.hexDump(\n new Uint8Array(mediaKeySessionContext.decryptdata.keyId || [])\n )} uri: ${mediaKeySessionContext.decryptdata.uri}`\n );\n mediaKeySessionContext.keyStatus = status;\n }\n );\n }\n\n private fetchServerCertificate(\n keySystem: KeySystems\n ): Promise<BufferSource | void> {\n const config = this.config;\n const Loader = config.loader;\n const certLoader = new Loader(config as HlsConfig) as Loader<LoaderContext>;\n const url = this.getServerCertificateUrl(keySystem);\n if (!url) {\n return Promise.resolve();\n }\n this.log(`Fetching serverCertificate for \"${keySystem}\"`);\n return new Promise((resolve, reject) => {\n const loaderContext: LoaderContext = {\n responseType: 'arraybuffer',\n url,\n };\n const loadPolicy = config.certLoadPolicy.default;\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n };\n const loaderCallbacks: LoaderCallbacks<LoaderContext> = {\n onSuccess: (response, stats, context, networkDetails) => {\n resolve(response.data as ArrayBuffer);\n },\n onError: (response, contex, networkDetails, stats) => {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details:\n ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,\n fatal: true,\n networkDetails,\n response: {\n url: loaderContext.url,\n data: undefined,\n ...response,\n },\n },\n `\"${keySystem}\" certificate request failed (${url}). Status: ${response.code} (${response.text})`\n )\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details:\n ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,\n fatal: true,\n networkDetails,\n response: {\n url: loaderContext.url,\n data: undefined,\n },\n },\n `\"${keySystem}\" certificate request timed out (${url})`\n )\n );\n },\n onAbort: (stats, context, networkDetails) => {\n reject(new Error('aborted'));\n },\n };\n certLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n });\n }\n\n private setMediaKeysServerCertificate(\n mediaKeys: MediaKeys,\n keySystem: KeySystems,\n cert: BufferSource\n ): Promise<MediaKeys> {\n return new Promise((resolve, reject) => {\n mediaKeys\n .setServerCertificate(cert)\n .then((success) => {\n this.log(\n `setServerCertificate ${\n success ? 'success' : 'not supported by CDM'\n } (${cert?.byteLength}) on \"${keySystem}\"`\n );\n resolve(mediaKeys);\n })\n .catch((error) => {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details:\n ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,\n error,\n fatal: true,\n },\n error.message\n )\n );\n });\n });\n }\n\n private renewLicense(\n context: MediaKeySessionContext,\n keyMessage: ArrayBuffer\n ): Promise<void> {\n return this.requestLicense(context, new Uint8Array(keyMessage)).then(\n (data: ArrayBuffer) => {\n return this.updateKeySession(context, new Uint8Array(data)).catch(\n (error) => {\n throw new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,\n error,\n fatal: true,\n },\n error.message\n );\n }\n );\n }\n );\n }\n\n private setupLicenseXHR(\n xhr: XMLHttpRequest,\n url: string,\n keysListItem: MediaKeySessionContext,\n licenseChallenge: Uint8Array\n ): Promise<{ xhr: XMLHttpRequest; licenseChallenge: Uint8Array }> {\n const licenseXhrSetup = this.config.licenseXhrSetup;\n\n if (!licenseXhrSetup) {\n xhr.open('POST', url, true);\n\n return Promise.resolve({ xhr, licenseChallenge });\n }\n\n return Promise.resolve()\n .then(() => {\n if (!keysListItem.decryptdata) {\n throw new Error('Key removed');\n }\n return licenseXhrSetup.call(\n this.hls,\n xhr,\n url,\n keysListItem,\n licenseChallenge\n );\n })\n .catch((error: Error) => {\n if (!keysListItem.decryptdata) {\n // Key session removed. Cancel license request.\n throw error;\n }\n // let's try to open before running setup\n xhr.open('POST', url, true);\n\n return licenseXhrSetup.call(\n this.hls,\n xhr,\n url,\n keysListItem,\n licenseChallenge\n );\n })\n .then((licenseXhrSetupResult) => {\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n const finalLicenseChallenge = licenseXhrSetupResult\n ? licenseXhrSetupResult\n : licenseChallenge;\n return { xhr, licenseChallenge: finalLicenseChallenge };\n });\n }\n\n private requestLicense(\n keySessionContext: MediaKeySessionContext,\n licenseChallenge: Uint8Array\n ): Promise<ArrayBuffer> {\n const keyLoadPolicy = this.config.keyLoadPolicy.default;\n return new Promise((resolve, reject) => {\n const url = this.getLicenseServerUrl(keySessionContext.keySystem);\n this.log(`Sending license request to URL: ${url}`);\n const xhr = new XMLHttpRequest();\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange = () => {\n if (!this.hls || !keySessionContext.mediaKeysSession) {\n return reject(new Error('invalid state'));\n }\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n let data = xhr.response;\n this.log(\n `License received ${\n data instanceof ArrayBuffer ? data.byteLength : data\n }`\n );\n const licenseResponseCallback = this.config.licenseResponseCallback;\n if (licenseResponseCallback) {\n try {\n data = licenseResponseCallback.call(\n this.hls,\n xhr,\n url,\n keySessionContext\n );\n } catch (error) {\n this.error(error);\n }\n }\n resolve(data);\n } else {\n const retryConfig = keyLoadPolicy.errorRetry;\n const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;\n this._requestLicenseFailureCount++;\n if (\n this._requestLicenseFailureCount > maxNumRetry ||\n (xhr.status >= 400 && xhr.status < 500)\n ) {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true,\n networkDetails: xhr,\n response: {\n url,\n data: undefined as any,\n code: xhr.status,\n text: xhr.statusText,\n },\n },\n `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`\n )\n );\n } else {\n const attemptsLeft =\n maxNumRetry - this._requestLicenseFailureCount + 1;\n this.warn(\n `Retrying license request, ${attemptsLeft} attempts left`\n );\n this.requestLicense(keySessionContext, licenseChallenge).then(\n resolve,\n reject\n );\n }\n }\n }\n };\n if (\n keySessionContext.licenseXhr &&\n keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE\n ) {\n keySessionContext.licenseXhr.abort();\n }\n keySessionContext.licenseXhr = xhr;\n\n this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(\n ({ xhr, licenseChallenge }) => {\n xhr.send(licenseChallenge);\n }\n );\n });\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) {\n if (!this.config.emeEnabled) {\n return;\n }\n\n const media = data.media;\n\n // keep reference of media\n this.media = media;\n\n media.addEventListener('encrypted', this.onMediaEncrypted);\n media.addEventListener('waitingforkey', this.onWaitingForKey);\n }\n\n private onMediaDetached() {\n const media = this.media;\n const mediaKeysList = this.mediaKeySessions;\n if (media) {\n media.removeEventListener('encrypted', this.onMediaEncrypted);\n media.removeEventListener('waitingforkey', this.onWaitingForKey);\n this.media = null;\n }\n\n this._requestLicenseFailureCount = 0;\n this.setMediaKeysQueue = [];\n this.mediaKeySessions = [];\n this.keyIdToKeySessionPromise = {};\n LevelKey.clearKeyUriToKeyIdMap();\n\n // Close all sessions and remove media keys from the video element.\n const keySessionCount = mediaKeysList.length;\n EMEController.CDMCleanupPromise = Promise.all(\n mediaKeysList\n .map((mediaKeySessionContext) =>\n this.removeSession(mediaKeySessionContext)\n )\n .concat(\n media?.setMediaKeys(null).catch((error) => {\n this.log(\n `Could not clear media keys: ${error}. media.src: ${media?.src}`\n );\n })\n )\n )\n .then(() => {\n if (keySessionCount) {\n this.log('finished closing key sessions and clearing media keys');\n mediaKeysList.length = 0;\n }\n })\n .catch((error) => {\n this.log(\n `Could not close sessions and clear media keys: ${error}. media.src: ${media?.src}`\n );\n });\n }\n\n private onManifestLoading() {\n this.keyFormatPromise = null;\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n { sessionKeys }: ManifestLoadedData\n ) {\n if (!sessionKeys || !this.config.emeEnabled) {\n return;\n }\n if (!this.keyFormatPromise) {\n const keyFormats: KeySystemFormats[] = sessionKeys.reduce(\n (formats: KeySystemFormats[], sessionKey: LevelKey) => {\n if (\n formats.indexOf(sessionKey.keyFormat as KeySystemFormats) === -1\n ) {\n formats.push(sessionKey.keyFormat as KeySystemFormats);\n }\n return formats;\n },\n []\n );\n this.log(\n `Selecting key-system from session-keys ${keyFormats.join(', ')}`\n );\n this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);\n }\n }\n\n private removeSession(\n mediaKeySessionContext: MediaKeySessionContext\n ): Promise<void> | void {\n const { mediaKeysSession, licenseXhr } = mediaKeySessionContext;\n if (mediaKeysSession) {\n this.log(\n `Remove licenses and keys and close session ${mediaKeysSession.sessionId}`\n );\n mediaKeysSession.onmessage = null;\n mediaKeysSession.onkeystatuseschange = null;\n if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {\n licenseXhr.abort();\n }\n mediaKeySessionContext.mediaKeysSession =\n mediaKeySessionContext.decryptdata =\n mediaKeySessionContext.licenseXhr =\n undefined!;\n const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);\n if (index > -1) {\n this.mediaKeySessions.splice(index, 1);\n }\n return mediaKeysSession\n .remove()\n .catch((error) => {\n this.log(`Could not remove session: ${error}`);\n })\n .then(() => {\n return mediaKeysSession.close();\n })\n .catch((error) => {\n this.log(`Could not close session: ${error}`);\n });\n }\n }\n}\n\nclass EMEKeyError extends Error {\n public readonly data: ErrorData;\n constructor(\n data: Omit<ErrorData, 'error'> & { error?: Error },\n message: string\n ) {\n super(message);\n data.error ||= new Error(message);\n this.data = data as ErrorData;\n data.err = data.error;\n }\n}\n\nexport default EMEController;\n","/**\n * CMCD spec version\n */\nexport const CMCDVersion = 1;\n\n/**\n * CMCD Object Type\n */\nexport const enum CMCDObjectType {\n MANIFEST = 'm',\n AUDIO = 'a',\n VIDEO = 'v',\n MUXED = 'av',\n INIT = 'i',\n CAPTION = 'c',\n TIMED_TEXT = 'tt',\n KEY = 'k',\n OTHER = 'o',\n}\n\n/**\n * CMCD Streaming Format\n */\nexport const CMCDStreamingFormatHLS = 'h';\n\n/**\n * CMCD Streaming Type\n */\nconst enum CMCDStreamType {\n VOD = 'v',\n LIVE = 'l',\n}\n\n/**\n * CMCD Headers\n */\nexport interface CMCDHeaders {\n 'CMCD-Object': string;\n 'CMCD-Request': string;\n 'CMCD-Session': string;\n 'CMCD-Status': string;\n}\n\n/**\n * CMCD\n */\nexport interface CMCD {\n /////////////////\n // CMCD Object //\n /////////////////\n\n /**\n * Encoded bitrate\n *\n * The encoded bitrate of the audio or video object being requested. This may not be known precisely by the player; however,\n * it MAY be estimated based upon playlist/manifest declarations. If the playlist declares both peak and average bitrate values,\n * the peak value should be transmitted.\n *\n * Integer kbps\n */\n br?: number;\n\n /**\n * Object duration\n *\n * The playback duration in milliseconds of the object being requested. If a partial segment is being requested, then this value\n * MUST indicate the playback duration of that part and not that of its parent segment. This value can be an approximation of the\n * estimated duration if the explicit value is not known.\n *\n * Integer milliseconds\n */\n d?: number;\n\n /**\n * Object type\n *\n * The media type of the current object being requested:\n * - `m` = text file, such as a manifest or playlist\n * - `a` = audio only\n * - `v` = video only\n * - `av` = muxed audio and video\n * - `i` = init segment\n * - `c` = caption or subtitle\n * - `tt` = ISOBMFF timed text track\n * - `k` = cryptographic key, license or certificate.\n * - `o` = other\n *\n * If the object type being requested is unknown, then this key MUST NOT be used.\n */\n ot?: CMCDObjectType;\n\n /**\n * Top bitrate\n *\n * The highest bitrate rendition in the manifest or playlist that the client is allowed to play, given current codec, licensing and\n * sizing constraints.\n *\n * Integer Kbps\n */\n tb?: number;\n\n //////////////////\n // CMCD Request //\n //////////////////\n /**\n * Buffer length\n *\n * The buffer length associated with the media object being requested. This value MUST be rounded to the nearest 100 ms. This key SHOULD only be\n * sent with an object type of ‘a’, ‘v’ or ‘av’.\n *\n * Integer milliseconds\n */\n bl?: number;\n\n /**\n * Deadline\n *\n * Deadline from the request time until the first sample of this Segment/Object needs to be available in order to not create a buffer underrun or\n * any other playback problems. This value MUST be rounded to the nearest 100ms. For a playback rate of 1, this may be equivalent to the player’s\n * remaining buffer length.\n *\n * Integer milliseconds\n */\n dl?: number;\n\n /**\n * Measured mtp CMCD throughput\n *\n * The throughput between client and server, as measured by the client and MUST be rounded to the nearest 100 kbps. This value, however derived,\n * SHOULD be the value that the client is using to make its next Adaptive Bitrate switching decision. If the client is connected to multiple\n * servers concurrently, it must take care to report only the throughput measured against the receiving server. If the client has multiple concurrent\n * connections to the server, then the intent is that this value communicates the aggregate throughput the client sees across all those connections.\n *\n * Integer kbps\n */\n mtp?: number;\n\n /**\n * Next object request\n *\n * Relative path of the next object to be requested. This can be used to trigger pre-fetching by the CDN. This MUST be a path relative to the current\n * request. This string MUST be URLEncoded. The client SHOULD NOT depend upon any pre-fetch action being taken - it is merely a request for such a\n * pre-fetch to take place.\n *\n * String\n */\n nor?: string;\n\n /**\n * Next range request\n *\n * If the next request will be a partial object request, then this string denotes the byte range to be requested. If the ‘nor’ field is not set, then the\n * object is assumed to match the object currently being requested. The client SHOULD NOT depend upon any pre-fetch action being taken – it is merely a\n * request for such a pre-fetch to take place. Formatting is similar to the HTTP Range header, except that the unit MUST be ‘byte’, the ‘Range:’ prefix is\n * NOT required and specifying multiple ranges is NOT allowed. Valid combinations are:\n *\n * - `\"\\<range-start\\>-\"`\n * - `\"\\<range-start\\>-\\<range-end\\>\"`\n * - `\"-\\<suffix-length\\>\"`\n *\n * String\n */\n nrr?: string;\n\n /**\n * Startup\n *\n * Key is included without a value if the object is needed urgently due to startup, seeking or recovery after a buffer-empty event. The media SHOULD not be\n * rendering when this request is made. This key MUST not be sent if it is FALSE.\n *\n * Boolean\n */\n su?: boolean;\n\n //////////////////\n // CMCD Session //\n //////////////////\n\n /**\n * Content ID\n *\n * A unique string identifying the current content. Maximum length is 64 characters. This value is consistent across multiple different\n * sessions and devices and is defined and updated at the discretion of the service provider.\n *\n * String\n */\n cid?: string;\n\n /**\n * Playback rate\n *\n * `1` if real-time, `2` if double speed, `0` if not playing. SHOULD only be sent if not equal to `1`.\n *\n * Decimal\n */\n pr?: number;\n\n /**\n * Streaming format\n *\n * The streaming format that defines the current request.\n *\n * - `d` = MPEG DASH\n * - `h` = HTTP Live Streaming (HLS)\n * - `s` = Smooth Streaming\n * - `o` = other\n *\n * If the streaming format being requested is unknown, then this key MUST NOT be used.\n */\n sf?: typeof CMCDStreamingFormatHLS;\n\n /**\n * Session ID\n *\n * A GUID identifying the current playback session. A playback session typically ties together segments belonging to a single media asset.\n * Maximum length is 64 characters. It is RECOMMENDED to conform to the UUID specification.\n *\n * String\n */\n sid?: string;\n\n /**\n * Stream type\n * - `v` = all segments are available – e.g., VOD\n * - `l` = segments become available over time – e.g., LIVE\n */\n st?: CMCDStreamType;\n\n /**\n * CMCD version\n *\n * The version of this specification used for interpreting the defined key names and values. If this key is omitted, the client and server MUST\n * interpret the values as being defined by version 1. Client SHOULD omit this field if the version is 1.\n *\n * Integer\n */\n v?: number;\n\n /////////////////\n // CMCD Status //\n /////////////////\n\n /**\n * Buffer starvation\n *\n * Key is included without a value if the buffer was starved at some point between the prior request and this object request,\n * resulting in the player being in a rebuffering state and the video or audio playback being stalled. This key MUST NOT be\n * sent if the buffer was not starved since the prior request.\n *\n * If the object type `ot` key is sent along with this key, then the `bs` key refers to the buffer associated with the particular\n * object type. If no object type is communicated, then the buffer state applies to the current session.\n *\n * Boolean\n */\n bs?: boolean;\n\n /**\n * Requested maximum throughput\n *\n * The requested maximum throughput that the client considers sufficient for delivery of the asset. Values MUST be rounded to the\n * nearest 100kbps. For example, a client would indicate that the current segment, encoded at 2Mbps, is to be delivered at no more\n * than 10Mbps, by using rtp=10000.\n *\n * Note: This can benefit clients by preventing buffer saturation through over-delivery and can also deliver a community benefit\n * through fair-share delivery. The concept is that each client receives the throughput necessary for great performance, but no more.\n * The CDN may not support the rtp feature.\n *\n * Integer kbps\n */\n rtp?: number;\n}\n","import { Events } from '../events';\nimport Hls from '../hls';\nimport {\n CMCD,\n CMCDHeaders,\n CMCDObjectType,\n CMCDStreamingFormatHLS,\n CMCDVersion,\n} from '../types/cmcd';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { Fragment } from '../loader/fragment';\nimport type { BufferCreatedData, MediaAttachedData } from '../types/events';\nimport type {\n FragmentLoaderContext,\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n PlaylistLoaderContext,\n} from '../types/loader';\nimport type {\n FragmentLoaderConstructor,\n HlsConfig,\n PlaylistLoaderConstructor,\n} from '../config';\n\n/**\n * Controller to deal with Common Media Client Data (CMCD)\n * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf\n */\nexport default class CMCDController implements ComponentAPI {\n private hls: Hls;\n private config: HlsConfig;\n private media?: HTMLMediaElement;\n private sid?: string;\n private cid?: string;\n private useHeaders: boolean = false;\n private initialized: boolean = false;\n private starved: boolean = false;\n private buffering: boolean = true;\n private audioBuffer?: SourceBuffer; // eslint-disable-line no-restricted-globals\n private videoBuffer?: SourceBuffer; // eslint-disable-line no-restricted-globals\n\n constructor(hls: Hls) {\n this.hls = hls;\n const config = (this.config = hls.config);\n const { cmcd } = config;\n\n if (cmcd != null) {\n config.pLoader = this.createPlaylistLoader();\n config.fLoader = this.createFragmentLoader();\n\n this.sid = cmcd.sessionId || CMCDController.uuid();\n this.cid = cmcd.contentId;\n this.useHeaders = cmcd.useHeaders === true;\n this.registerListeners();\n }\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n }\n\n destroy() {\n this.unregisterListeners();\n this.onMediaDetached();\n\n // @ts-ignore\n this.hls = this.config = this.audioBuffer = this.videoBuffer = null;\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) {\n this.media = data.media;\n this.media.addEventListener('waiting', this.onWaiting);\n this.media.addEventListener('playing', this.onPlaying);\n }\n\n private onMediaDetached() {\n if (!this.media) {\n return;\n }\n\n this.media.removeEventListener('waiting', this.onWaiting);\n this.media.removeEventListener('playing', this.onPlaying);\n\n // @ts-ignore\n this.media = null;\n }\n\n private onBufferCreated(\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData\n ) {\n this.audioBuffer = data.tracks.audio?.buffer;\n this.videoBuffer = data.tracks.video?.buffer;\n }\n\n private onWaiting = () => {\n if (this.initialized) {\n this.starved = true;\n }\n\n this.buffering = true;\n };\n\n private onPlaying = () => {\n if (!this.initialized) {\n this.initialized = true;\n }\n\n this.buffering = false;\n };\n\n /**\n * Create baseline CMCD data\n */\n private createData(): CMCD {\n return {\n v: CMCDVersion,\n sf: CMCDStreamingFormatHLS,\n sid: this.sid,\n cid: this.cid,\n pr: this.media?.playbackRate,\n mtp: this.hls.bandwidthEstimate / 1000,\n };\n }\n\n /**\n * Apply CMCD data to a request.\n */\n private apply(context: LoaderContext, data: CMCD = {}) {\n // apply baseline data\n Object.assign(data, this.createData());\n\n const isVideo =\n data.ot === CMCDObjectType.INIT ||\n data.ot === CMCDObjectType.VIDEO ||\n data.ot === CMCDObjectType.MUXED;\n\n if (this.starved && isVideo) {\n data.bs = true;\n data.su = true;\n this.starved = false;\n }\n\n if (data.su == null) {\n data.su = this.buffering;\n }\n\n // TODO: Implement rtp, nrr, nor, dl\n\n if (this.useHeaders) {\n const headers = CMCDController.toHeaders(data);\n if (!Object.keys(headers).length) {\n return;\n }\n\n if (!context.headers) {\n context.headers = {};\n }\n\n Object.assign(context.headers, headers);\n } else {\n const query = CMCDController.toQuery(data);\n if (!query) {\n return;\n }\n\n context.url = CMCDController.appendQueryToUri(context.url, query);\n }\n }\n\n /**\n * Apply CMCD data to a manifest request.\n */\n private applyPlaylistData = (context: PlaylistLoaderContext) => {\n try {\n this.apply(context, {\n ot: CMCDObjectType.MANIFEST,\n su: !this.initialized,\n });\n } catch (error) {\n logger.warn('Could not generate manifest CMCD data.', error);\n }\n };\n\n /**\n * Apply CMCD data to a segment request\n */\n private applyFragmentData = (context: FragmentLoaderContext) => {\n try {\n const fragment = context.frag;\n const level = this.hls.levels[fragment.level];\n const ot = this.getObjectType(fragment);\n const data: CMCD = {\n d: fragment.duration * 1000,\n ot,\n };\n\n if (\n ot === CMCDObjectType.VIDEO ||\n ot === CMCDObjectType.AUDIO ||\n ot == CMCDObjectType.MUXED\n ) {\n data.br = level.bitrate / 1000;\n data.tb = this.getTopBandwidth(ot) / 1000;\n data.bl = this.getBufferLength(ot);\n }\n\n this.apply(context, data);\n } catch (error) {\n logger.warn('Could not generate segment CMCD data.', error);\n }\n };\n\n /**\n * The CMCD object type.\n */\n private getObjectType(fragment: Fragment): CMCDObjectType | undefined {\n const { type } = fragment;\n\n if (type === 'subtitle') {\n return CMCDObjectType.TIMED_TEXT;\n }\n\n if (fragment.sn === 'initSegment') {\n return CMCDObjectType.INIT;\n }\n\n if (type === 'audio') {\n return CMCDObjectType.AUDIO;\n }\n\n if (type === 'main') {\n if (!this.hls.audioTracks.length) {\n return CMCDObjectType.MUXED;\n }\n\n return CMCDObjectType.VIDEO;\n }\n\n return undefined;\n }\n\n /**\n * Get the highest bitrate.\n */\n private getTopBandwidth(type: CMCDObjectType) {\n let bitrate: number = 0;\n let levels;\n const hls = this.hls;\n\n if (type === CMCDObjectType.AUDIO) {\n levels = hls.audioTracks;\n } else {\n const max = hls.maxAutoLevel;\n const len = max > -1 ? max + 1 : hls.levels.length;\n levels = hls.levels.slice(0, len);\n }\n\n for (const level of levels) {\n if (level.bitrate > bitrate) {\n bitrate = level.bitrate;\n }\n }\n\n return bitrate > 0 ? bitrate : NaN;\n }\n\n /**\n * Get the buffer length for a media type in milliseconds\n */\n private getBufferLength(type: CMCDObjectType) {\n const media = this.hls.media;\n const buffer =\n type === CMCDObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;\n\n if (!buffer || !media) {\n return NaN;\n }\n\n const info = BufferHelper.bufferInfo(\n buffer,\n media.currentTime,\n this.config.maxBufferHole\n );\n\n return info.len * 1000;\n }\n\n /**\n * Create a playlist loader\n */\n private createPlaylistLoader(): PlaylistLoaderConstructor | undefined {\n const { pLoader } = this.config;\n const apply = this.applyPlaylistData;\n const Ctor = pLoader || (this.config.loader as PlaylistLoaderConstructor);\n\n return class CmcdPlaylistLoader {\n private loader: Loader<PlaylistLoaderContext>;\n\n constructor(config: HlsConfig) {\n this.loader = new Ctor(config);\n }\n\n get stats() {\n return this.loader.stats;\n }\n\n get context() {\n return this.loader.context;\n }\n\n destroy() {\n this.loader.destroy();\n }\n\n abort() {\n this.loader.abort();\n }\n\n load(\n context: PlaylistLoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<PlaylistLoaderContext>\n ) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n\n /**\n * Create a playlist loader\n */\n private createFragmentLoader(): FragmentLoaderConstructor | undefined {\n const { fLoader } = this.config;\n const apply = this.applyFragmentData;\n const Ctor = fLoader || (this.config.loader as FragmentLoaderConstructor);\n\n return class CmcdFragmentLoader {\n private loader: Loader<FragmentLoaderContext>;\n\n constructor(config: HlsConfig) {\n this.loader = new Ctor(config);\n }\n\n get stats() {\n return this.loader.stats;\n }\n\n get context() {\n return this.loader.context;\n }\n\n destroy() {\n this.loader.destroy();\n }\n\n abort() {\n this.loader.abort();\n }\n\n load(\n context: FragmentLoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<FragmentLoaderContext>\n ) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n\n /**\n * Generate a random v4 UUI\n *\n * @returns {string}\n */\n static uuid(): string {\n const url = URL.createObjectURL(new Blob());\n const uuid = url.toString();\n URL.revokeObjectURL(url);\n return uuid.slice(uuid.lastIndexOf('/') + 1);\n }\n\n /**\n * Serialize a CMCD data object according to the rules defined in the\n * section 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static serialize(data: CMCD): string {\n const results: string[] = [];\n const isValid = (value: any) =>\n !Number.isNaN(value) && value != null && value !== '' && value !== false;\n const toRounded = (value: number) => Math.round(value);\n const toHundred = (value: number) => toRounded(value / 100) * 100;\n const toUrlSafe = (value: string) => encodeURIComponent(value);\n const formatters = {\n br: toRounded,\n d: toRounded,\n bl: toHundred,\n dl: toHundred,\n mtp: toHundred,\n nor: toUrlSafe,\n rtp: toHundred,\n tb: toRounded,\n };\n\n const keys = Object.keys(data || {}).sort();\n\n for (const key of keys) {\n let value = data[key];\n\n // ignore invalid values\n if (!isValid(value)) {\n continue;\n }\n\n // Version should only be reported if not equal to 1.\n if (key === 'v' && value === 1) {\n continue;\n }\n\n // Playback rate should only be sent if not equal to 1.\n if (key == 'pr' && value === 1) {\n continue;\n }\n\n // Certain values require special formatting\n const formatter = formatters[key];\n if (formatter) {\n value = formatter(value);\n }\n\n // Serialize the key/value pair\n const type = typeof value;\n let result: string;\n\n if (key === 'ot' || key === 'sf' || key === 'st') {\n result = `${key}=${value}`;\n } else if (type === 'boolean') {\n result = key;\n } else if (type === 'number') {\n result = `${key}=${value}`;\n } else {\n result = `${key}=${JSON.stringify(value)}`;\n }\n\n results.push(result);\n }\n\n return results.join(',');\n }\n\n /**\n * Convert a CMCD data object to request headers according to the rules\n * defined in the section 2.1 and 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static toHeaders(data: CMCD): Partial<CMCDHeaders> {\n const keys = Object.keys(data);\n const headers = {};\n const headerNames = ['Object', 'Request', 'Session', 'Status'];\n const headerGroups = [{}, {}, {}, {}];\n const headerMap = {\n br: 0,\n d: 0,\n ot: 0,\n tb: 0,\n bl: 1,\n dl: 1,\n mtp: 1,\n nor: 1,\n nrr: 1,\n su: 1,\n cid: 2,\n pr: 2,\n sf: 2,\n sid: 2,\n st: 2,\n v: 2,\n bs: 3,\n rtp: 3,\n };\n\n for (const key of keys) {\n // Unmapped fields are mapped to the Request header\n const index = headerMap[key] != null ? headerMap[key] : 1;\n headerGroups[index][key] = data[key];\n }\n\n for (let i = 0; i < headerGroups.length; i++) {\n const value = CMCDController.serialize(headerGroups[i]);\n if (value) {\n headers[`CMCD-${headerNames[i]}`] = value;\n }\n }\n\n return headers;\n }\n\n /**\n * Convert a CMCD data object to query args according to the rules\n * defined in the section 2.2 and 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static toQuery(data: CMCD): string {\n return `CMCD=${encodeURIComponent(CMCDController.serialize(data))}`;\n }\n\n /**\n * Append query args to a uri.\n */\n static appendQueryToUri(uri, query) {\n if (!query) {\n return uri;\n }\n\n const separator = uri.includes('?') ? '&' : '?';\n return `${uri}${separator}${query}`;\n }\n}\n","import { Events } from '../events';\nimport { Level } from '../types/level';\nimport { AttrList } from '../utils/attr-list';\nimport { addGroupId } from './level-controller';\nimport { ErrorActionFlags, NetworkErrorAction } from './error-controller';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type {\n ErrorData,\n ManifestLoadedData,\n ManifestParsedData,\n} from '../types/events';\nimport type { RetryConfig } from '../config';\nimport type {\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n LoaderResponse,\n LoaderStats,\n} from '../types/loader';\nimport type { LevelParsed } from '../types/level';\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\ntype PathwayClone = {\n 'BASE-ID': string;\n ID: string;\n 'URI-REPLACEMENT': UriReplacement;\n};\n\ntype 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(): void {\n this.started = true;\n self.clearTimeout(this.reloadTimer);\n if (this.enabled && this.uri) {\n if (this.updated) {\n const ttl = Math.max(\n this.timeToLoad * 1000 - (performance.now() - this.updated),\n 0\n );\n this.scheduleRefresh(this.uri, ttl);\n } else {\n this.loadSteeringManifest(this.uri);\n }\n }\n }\n\n stopLoad(): void {\n this.started = false;\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n self.clearTimeout(this.reloadTimer);\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 let pathwayPriority = this.pathwayPriority;\n const pathwayId = this.pathwayId;\n if (!this.penalizedPathways[pathwayId]) {\n this.penalizedPathways[pathwayId] = performance.now();\n }\n if (!pathwayPriority && this.levels) {\n // If PATHWAY-PRIORITY was not provided, list pathways for error handling\n pathwayPriority = this.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 !== pathwayId;\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 (penalizedPathways[pathwayId]) {\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 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 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 levelParsed: LevelParsed = Object.assign({}, baseLevel as any);\n levelParsed.details = undefined;\n levelParsed.url = performUriReplacement(\n baseLevel.uri,\n baseLevel.attrs['STABLE-VARIANT-ID'],\n 'PER-VARIANT-URIS',\n uriReplacement\n );\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 levelParsed.attrs = attributes;\n const clonedLevel = new Level(levelParsed);\n addGroupId(clonedLevel, 'audio', clonedAudioGroupId);\n addGroupId(clonedLevel, 'text', clonedSubtitleGroupId);\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 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 self.clearTimeout(this.reloadTimer);\n this.reloadTimer = self.setTimeout(() => {\n this.loadSteeringManifest(uri);\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;\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 }\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(this.stats, this.context, this.loader);\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) {\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.stats.aborted) return;\n return xhrSetup(xhr, context.url);\n })\n .catch((error: Error) => {\n xhr.open('GET', context.url, true);\n return xhrSetup(xhr, context.url);\n })\n .then(() => {\n if (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 = this.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 if (shouldRetry(retryConfig, retryCount, false, status)) {\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 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(this.stats, this.context, this.loader);\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 `${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${\n context.url\n }, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${\n this.retryDelay\n }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","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;\n private response!: Response;\n private controller: AbortController;\n public context!: LoaderContext;\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 = this.callbacks = null;\n this.abortInternal();\n }\n\n abortInternal(): void {\n const response = this.response;\n if (!response?.ok) {\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(this.stats, this.context, this.response);\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)\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 this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n }, maxLoadTimeMs - (first - stats.loading.start));\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;\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 { fixLineBreaks } from './vttparser';\nimport type { CaptionScreen, Row } from './cea-608-parser';\nimport { generateCueId } from './webvtt-parser';\nimport { addCueToTrack } from './texttrack-utils';\n\nconst WHITESPACE_CHAR = /\\s/;\n\nexport interface CuesInterface {\n newCue(\n track: TextTrack | null,\n startTime: number,\n endTime: number,\n captionScreen: CaptionScreen\n ): VTTCue[];\n}\n\nconst Cues: CuesInterface = {\n newCue(\n track: TextTrack | null,\n startTime: number,\n endTime: number,\n captionScreen: CaptionScreen\n ): VTTCue[] {\n const result: VTTCue[] = [];\n let row: Row;\n // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers\n let cue: VTTCue;\n let indenting: boolean;\n let indent: number;\n let text: string;\n const Cue = (self.VTTCue || self.TextTrackCue) as any;\n\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (let c = 0; c < row.chars.length; c++) {\n if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {\n indent++;\n } else {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n // To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n if (indent >= 16) {\n indent--;\n } else {\n indent++;\n }\n\n const cueText = fixLineBreaks(text.trim());\n const id = generateCueId(startTime, endTime, cueText);\n\n // If this cue already exists in the track do not push it\n if (!track?.cues?.getCueById(id)) {\n cue = new Cue(startTime, endTime, cueText);\n cue.id = id;\n cue.line = r + 1;\n cue.align = 'left';\n // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)\n // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608\n // Firefox throws an exception and captions break with out of bounds 0-100 values\n cue.position = 10 + Math.min(80, Math.floor((indent * 8) / 32) * 10);\n result.push(cue);\n }\n }\n }\n if (track && result.length) {\n // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome\n result.sort((cueA, cueB) => {\n if (cueA.line === 'auto' || cueB.line === 'auto') {\n return 0;\n }\n if (cueA.line > 8 && cueB.line > 8) {\n return cueB.line - cueA.line;\n }\n return cueA.line - cueB.line;\n });\n result.forEach((cue) => addCueToTrack(track, cue));\n }\n return result;\n },\n};\n\nexport default Cues;\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 PlaylistLoaderContext,\n} from './types/loader';\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 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 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};\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};\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 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 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 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 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 initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n backBufferLength: Infinity, // used by buffer-controller\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 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\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 { 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 { isSupported } from './is-supported';\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 { HdcpLevels } 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 { ComponentAPI, NetworkComponentAPI } from './types/component-api';\nimport type { MediaPlaylist } from './types/media-playlist';\nimport type { HlsConfig } from './config';\nimport type { HdcpLevel, Level } from './types/level';\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 _emitter: HlsEventEmitter = new EventEmitter();\n private _autoLevelCapping: number;\n private _maxHdcpLevel: HdcpLevel = null;\n private abrController: AbrController;\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\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 isSupported(): boolean {\n return isSupported();\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 this._autoLevelCapping = -1;\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 (e) {\n logger.error(\n 'An internal error happened while handling event ' +\n event +\n '. Error message: \"' +\n e.message +\n '\". Here is a stacktrace:',\n e\n );\n this.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal: false,\n event: event,\n error: e,\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 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.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.networkControllers.forEach((controller) => {\n controller.stopLoad();\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, urlId = 0) {\n this.levelController.removeLevel(levelIndex, urlId);\n }\n\n /**\n * @returns an array of levels (variants) sorted by HDCP-LEVEL, BANDWIDTH, SCORE, and RESOLUTION (height)\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.loadLevel = newLevel;\n this.abrController.clearTimer();\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 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 get startLevel(): number {\n return this.levelController.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 /**\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 }\n }\n\n get maxHdcpLevel(): HdcpLevel {\n return this._maxHdcpLevel;\n }\n\n set maxHdcpLevel(value: HdcpLevel) {\n if (HdcpLevels.indexOf(value) > -1) {\n this._maxHdcpLevel = value;\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 && 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 /**\n * next automatically selected quality level\n */\n get nextAutoLevel(): number {\n // ensure next auto level is between min and max auto level\n return Math.min(\n Math.max(this.abrController.nextAutoLevel, this.minAutoLevel),\n this.maxAutoLevel\n );\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 = Math.max(this.minAutoLevel, 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 * 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 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 MediaPlaylist,\n ErrorDetails,\n ErrorTypes,\n Events,\n Level,\n HlsListeners,\n HlsEventEmitter,\n HlsConfig,\n BufferInfo,\n HdcpLevels,\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 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 { 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 {\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 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","consolePrintFn","type","func","self","console","bind","enableLogs","debugConfig","id","_len","arguments","functions","Array","_key","forEach","exportLoggerFunctions","e","logger","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","attr","parseAttrList","hasOwnProperty","this","clientAttrs","push","_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","isSCTE35Attribute","DateRange","dateRangeAttr","dateRangeWithSameId","_startDate","_endDate","_badValueForSameId","previousAttr","key","Object","call","ID","_extends","Date","endDate","_isFiniteNumber","getTime","_createClass","get","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","byteRange","byteRangeEndOffset","set","Fragment","_BaseSegment","_this","_decryptdata","rawProgramDateTime","programDateTime","tagList","sn","levelkeys","loader","keyLoader","level","cc","startPTS","endPTS","startDTS","endDTS","deltaPTS","maxStartPTS","minEndPTS","stats","urlId","data","bitrateTest","title","initSegment","endList","gap","_inheritsLoose","_proto2","setKeyFormat","keyFormat","getDecryptData","abortRequests","_this$loader","_this$keyLoader","abort","setElementaryStreamInfo","partial","min","max","clearElementaryStreamInfo","NONE","identity","keyFormats","keys","_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","base64Decode","base64encodedStr","from","atob","c","charCodeAt","convertDataUriToArrayBytes","uri","keyIdbytes","paddedkeyIdbytes","colonsplit","keydata","semicolonsplit","commasplit","isbase64","splice","strToUtf8array","subarray","str","unescape","encodeURIComponent","KeySystems","CLEARKEY","FAIRPLAY","PLAYREADY","WIDEVINE","KeySystemFormats","keySystemFormatToKeySystemDomain","format","KeySystemIds","keySystemDomainToKeySystemFormat","keySystem","getKeySystemsForConfig","config","drmSystems","widevineLicenseUrl","keySystemsToAttempt","filter","requestMediaKeySystemAccess","navigator","sliceUint8","array","decoder","isHeader","offset","isFooter","getID3Data","front","readSize","size","canParse","isTimeStampFrame","frame","getFrameData","String","fromCharCode","getID3Frames","id3Data","frames","frameData","decodeFrame","decodePrivFrame","decodeURLFrame","decodeTextFrame","owner","utf8ArrayToStr","privateData","buffer","description","text","readTimeStamp","timeStampFrame","byteLength","pts33Bit","timestamp","round","exitOnNull","getTextDecoder","decoded","decode","idx","char2","char3","out","userAgent","includes","TextDecoder","Hex","h","toString","UINT32_MAX","pow","RemuxerTrackIdConfig","id3","bin2str","apply","readUint16","val","readUint32","readSint32","writeUint32","findBox","results","endbox","subresults","parseSegmentIndex","sidx","references","timescale","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","parseInitSegment","result","traks","trak","tkhd","trackId","mdhd","hdlr","hdlrType","soun","vide","stsd","codec","trex","track","default","flags","parseSinf","sinf","schm","computeRawDurationFromSamples","trun","sampleCount","appendUint8Array","data1","data2","temp","parseSamples","timeOffset","seiSamples","videoData","samples","isHEVCFlavor","map","moof","moofOffset","byteOffset","traf","baseTime","tfdt","undefined","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","endOfCaptions","b","leftOver","providerCode","userStructure","userDataType","firstByte","enabled","totalBytes","byteArray","bytes","uuidStrArray","userDataBytes","uuid","userData","EPBPositions","newLength","newData","sourceIndex","shift","mp4pssh","systemId","keyids","RangeError","kids","kidCount","k","DataView","setUint32","dataSize","payload","mp4Box","keyUriToKeyIdMap","LevelKey","method","formatversions","iv","keyFormatVersions","isCommonEncryption","keyId","pssh","clearKeyUriToKeyIdMap","isSupported","segmentNumber","uint8View","createInitializationVector","keyBytes","PlayReadyKeySystemUUID","keyBytesUtf16","Uint16Array","keyByteStr","xmlKeyBytes","keyData","DOMParser","parseFromString","getElementsByTagName","childNodes","nodeValue","getAttribute","keyIdArray","swap","to","cur","changeEndianness","padded","VARIABLE_REPLACEMENT_REGEX","hasVariableReferences","test","substituteVariablesInAttributes","parsed","attributeNames","name","substituteVariables","variableReference","variableName","variableValue","addVariableDefinition","parentUrl","NAME","VALUE","QUERYPARAM","searchParams","URL","has","message","importVariableDefinition","sourceVariableList","IMPORT","getMediaSource","MediaSource","WebKitMediaSource","sampleEntryCodesISO","a3ds","alac","alaw","dra1","dtsc","dtse","dtsh","enca","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","isCodecSupportedInMp4","_MediaSource$isTypeSu","isTypeSupported","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","convertAVC1ToAVCOTI","avcdata","resolve","isMediaPlaylist","parseMasterPlaylist","string","contentSteering","levels","sessionData","sessionKeys","levelsWithKnownCodecs","_level$unknownCodecs","bitrate","resolution","setCodecs","CODECS","videoCodec","unknownCodecs","tag","attributes","sessionAttrs","dataId","sessionKey","parseKey","variableAttributes","contentSteeringAttributes","pathwayId","parseStartTimeOffset","stripUnknownCodecLevels","parseMasterPlaylistMedia","groupsByType","AUDIO","audioCodec","SUBTITLES","textCodec","TYPE","medias","media","groupId","instreamId","LANGUAGE","autoselect","forced","lang","URI","groupCodec","assignCodec","parseLevelPlaylist","levelUrlId","multivariantVariableList","currentInitSegment","currentSN","currentPart","discontinuityCounter","prevFrag","firstPdtIndex","createNextFrag","setFragLevelKeys","assignProgramDateTime","value1","value2","toUpperCase","skipAttrs","unshift","dateRange","isValid","levelKey","mapAttrs","init","setInitSegment","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","codecs","filtered","typeCodes","isCodecType","preferred","groupItem","codecProperty","codecValue","parse","endProgramDateTime","_isFiniteNumber4","BYTERANGE","some","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","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","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","_objectSpread","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","addCueToTrack","cue","mode","cues","getCueById","addCue","textTrackCue","TextTrackCue","startTime","endTime","err2","clearCurrentCues","removeCue","removeCuesInRange","predicate","cuesFound","firstCueInRange","time","left","right","mid","getFirstCueIndexAfterTime","getCuesInRange","MetadataSchema","getCueClass","VTTCue","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","createTrack","getID3Track","textTracks","textTrack","kind","label","addTextTrack","_this$hls$config","enableEmsgMetadataCues","enableID3MetadataCues","ID3","j","updateId3CueEnds","_this$id3Track","_ref","startOffset","endOffset","_hls$config","_ref2","hasProgramDateTime","enableDateRangeMetadataCues","ids","idsToRemove","_loop","dateTimeOffset","_loop2","appendedDateRangeCues","durationKnown","nextDateRangeWithSameClass","reduce","filterMapArray","candidate","sort","a","LatencyController","currentTime","stallCount","_latency","timeupdateHandler","timeupdate","addEventListener","removeEventListener","_this$levelDetails","BUFFER_STALLED_ERROR","latency","computeLatency","_this$config","lowLatencyMode","maxLiveSyncPlaybackRate","targetLatency","distanceFromTarget","inLiveRange","maxLatency","forwardBufferLength","rate","exp","edgeStalled","playbackRate","estimateLiveEdge","edge","age","liveEdge","liveMaxLatencyDuration","liveMaxLatencyDurationCount","_this$config2","liveSyncDuration","liveSyncDurationCount","userConfig","maxLiveSyncOnStallIncrease","syncPosition","drift","maxLevelUpdateAge","bufferedRanges","buffered","HdcpLevels","HlsSkip","HlsUrlParameters","msn","skip","addDirectives","href","Level","_attrs","codecSet","audioGroupIds","fragmentError","loadError","realBitrate","textGroupIds","_urlId","addFallback","newValue","_this$audioGroupIds","_this$textGroupIds","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","isTimeoutError","FRAG_LOAD_TIMEOUT","KEY_LOAD_TIMEOUT","getRetryConfig","isTimeout","getRetryDelay","retryConfig","retryCount","backoffFactor","backoff","getLoaderConfigWithoutReties","loderConfig","shouldRetry","httpStatus","onLine","retryForHttpStatus","BinarySearch","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","findFragmentByPTS","fragPrevious","bufferEnd","maxFragLookUpTolerance","fragNext","fragmentWithinToleranceTest","foundFragment","candidateLookupTolerance","pdtWithinToleranceTest","pdtBufferEnd","chromeOrFirefox","RENDITION_PENALTY_DURATION_MS","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","audioGroupId","textGroupId","KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED","restrictedHdcpLevel","hdcpLevel","BUFFER_ADD_CODEC_ERROR","REMUX_ALLOC_ERROR","INTERNAL_EXCEPTION","BUFFER_APPENDING_ERROR","BUFFER_APPEND_ERROR","BUFFER_FULL_ERROR","LEVEL_SWITCH_ERROR","BUFFER_SEEK_OVER_HOLE","BUFFER_NUDGE_ON_STALL","KEY_SYSTEM_ERROR","_data$response","variantLevelIndex","fragLoadPolicy","keyLoadPolicy","startsWith","fragmentErrors","acc","_data$response2","autoLevelEnabled","_data$frag2","_data$context2","nextLevel","minAutoLevel","maxAutoLevel","fragErrorType","playlistErrorType","playlistErrorGroupId","levelCandidate","fragCandidate","nextAutoLevel","_data$errorAction","sendAlternateToPenaltyBox","resolved","switchLevel","redundantFailover","maxHdcpLevel","nextLoadLevel","redundantLevels","errorUrlId","penalizeRendition","newUrlId","penalizedRendition","currentPenaltyState","lastErrorPerfMs","lastErrorDetails","position","candidateFrag","errors","lastCandidateError","checkExpired","lv","v","_ret","BasePlaylistController","logPrefix","timer","requestScheduled","canLoad","clearTimer","clearTimeout","loadPlaylist","switchParams","playlistUri","foundIndex","currentGoal","hlsUrlParameters","shouldLoadPlaylist","playlist","shouldReloadPlaylist","playlistLoaded","previousDetails","elapsed","endSn","lastPart","lastAdvanced","cdnAge","segments","toFixed","getDeliveryDirectives","bufferInfo","mainForwardBufferInfo","reloadInterval","distanceToLiveEdgeMs","lastSegmentDuration","computeReloadInterval","estimatedTimeUntilUpdate","setTimeout","previousDeliveryDirectives","getSkipValue","checkRetry","errorEvent","errorDetails","_ref$retryCount","_errorEvent$context","delay","LevelController","_BasePlaylistControll","contentSteeringController","_levels","_firstLevel","_startLevel","currentLevel","currentLevelIndex","manualLevelIndex","steering","onParsedComplete","onManifestLoaded","onLevelLoaded","LEVELS_UPDATED","onLevelsUpdated","AUDIO_TRACK_SWITCHED","onAudioTrackSwitched","FRAG_LOADED","onFragLoaded","resetLevels","levelFromSet","levelSet","levelParsed","_levelParsed$audioCod","FRAMERATE","PATHWAY","RESOLUTION","addGroupId","filterAndSortMediaOptions","unfilteredLevels","resolutionFound","videoCodecFound","audioCodecFound","assignTrackIdsByGroup","unsortedLevels","SCORE","firstLevelInPlaylist","filterParsedLevels","audioOnly","edata","firstLevel","altAudio","t","MANIFEST_PARSED","autoStartLoad","forceStartLoad","Promise","then","MEDIA_ERROR","MANIFEST_INCOMPATIBLE_CODECS_ERROR","_ref3","_data$deliveryDirecti2","_data$deliveryDirecti","curLevel","removeLevel","_this3","filterLevelAndGroupByIdIndex","_ref4","newLevel","OTHER_ERROR","lastLevelIndex","lastLevel","lastPathwayId","levelSwitchingData","maxBitrate","LEVEL_SWITCHING","configStartLevel","startLevel","tracks","FragmentState","FragmentTracker","activePartLists","endListFragments","timeRanges","bufferPadding","hasGaps","BUFFER_APPENDED","onBufferAppended","FRAG_BUFFERED","onFragBuffered","getAppendedFrag","activeParts","activePart","appendedPTS","getBufferedFrag","fragmentEntity","body","detectEvictedFragments","elementaryStream","timeRange","playlistType","appendedPart","appendedPartSn","esData","range","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","_this4","snToRemove","removeAllFragments","_fragmentEntity$range","_fragmentEntity$range2","_fragmentEntity$range3","MIN_CHUNK_SIZE","FragmentLoader","partLoadTimeout","onProgress","reject","LoadError","FragmentILoader","fLoader","DefaultILoader","tags","createGapLoadError","createLoaderContext","highWaterMark","resetLoader","resetIV","decryptdata","onAbort","INTERNAL_ABORTED","loadPart","updateStatsFromPart","partLoadedData","fragStats","partStats","partTotal","estTotalParts","estLoadedParts","estRemainingBytes","fragLoading","partLoading","segment","headers","rangeStart","rangeEnd","byteRangeStartOffset","_frag$decryptdata","byteRangeStart","byteRangeEnd","fragmentLen","_Error","_wrapNativeSuper","KeyLoader","keyUriToKeyInfo","emeController","detach","keyInfo","mediaKeySessionContext","createKeyLoadError","loadClear","loadingFrag","emeEnabled","selectKeySystemFormat","keySystemFormat","loadInternal","_keyInfo","_keyInfo2","_keyInfo$mediaKeySess","keyLoadPromise","keyStatus","keyLoadedData","loadKeyHTTP","loadKeyEME","keySessionContextPromise","loadKey","keySessionContext","catch","TaskLoop","_boundTick","_tickTimer","_tickInterval","_tickCallCount","tick","onHandlerDestroying","onHandlerDestroyed","clearNextTick","clearInterval","hasInterval","hasNextTick","setInterval","millis","doTick","tickImmediate","noopBuffered","BufferHelper","isBuffered","getBuffered","pos","maxHoleDuration","vbuffered","bufferedInfo","nextStart","diff","buffered2","buf2len","buf2end","bufferStartNext","bufferLen","bufferStart","ChunkMetadata","transmuxing","executeStart","executeEnd","findFirstFragWithCC","firstFrag","currentFrag","adjustFragmentStart","sliding","adjustSlidingStart","alignStream","lastFrag","shouldAlignOnDiscontinuities","referenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","findDiscontinuousReferenceFrag","alignDiscontinuities","lastDetails","lastPDT","newPDT","alignPDT","alignMediaPlaylistByPDT","refDetails","refFragments","refFrag","refPDT","targetPDT","AESCrypto","subtle","aesIV","decrypt","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","ksRows","keySize","keySchedule","invKeySchedule","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","d","x","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","enableSoftwareAES","browserCrypto","crypto","webkitSubtle","isSync","flush","reset","outputBytes","paddingBytes","getUint8","softwareDecrypt","decryptResult","webCryptoDecrypt","logOnce","currentChunk","getValidChunk","aesKey","onWebCryptoError","splitPoint","msg","TimeRanges","r","State","BaseStreamController","_TaskLoop","fragmentTracker","fragCurrent","transmuxer","_state","mediaBuffer","lastCurrentTime","nextLoadPosition","loadedmetadata","retryDate","fragmentLoader","levelLastLoaded","startFragRequested","decrypter","initPTS","onvseeking","onvended","_assertThisInitialized","onTickEnd","resetTransmuxer","state","_streamEnded","getLevelDetails","_this$levels$this$lev","onMediaSeeking","onMediaEnded","ended","maxBufferHole","resetLoadingState","tolerance","fragStartOffset","fragEndOffset","pastFragment","loadFragment","targetBufferTime","_loadFragForPlayback","_doFragLoad","fragContextChanged","_handleFragmentLoadProgress","_handleFragmentLoadComplete","resetFragmentLoading","clearTrackerIfNeeded","_this$mediaBuffer","getFwdBufferInfo","minForwardBufferLength","maxBufferLength","reduceMaxBufferLength","checkLiveUpdate","flushMainBuffer","flushScope","_loadInitSegment","decryptData","decryptedData","FRAG_DECRYPTED","tstart","tdecrypt","fragBufferedComplete","_frag$startPTS","_frag$endPTS","_this$fragCurrent","_this$fragPrevious","NaN","seekToStartPos","fragLoadedEndData","partsLoaded","complete","fragLoaded","chunkMeta","progressCallback","keyLoadingPromise","KEY_LOADED","KEY_LOADING","getNextPart","doFragPartsLoad","handleFragLoadError","FRAG_LOADING","loadedEndOfParts","dataOnProgress","progressive","all","fragLoadedData","fromPart","_this5","initialPartList","loadedPart","nextPart","handleFragLoadAborted","_handleTransmuxerFlush","getCurrentContext","updateLevelTiming","getFragmentWithSN","bufferFragmentData","noBacktracking","_buffer","BUFFER_APPENDING","dropped","flushBufferGap","fragDuration","segmentFraction","bufferable","getLoadPosition","getFwdBufferInfoAtPos","bufferedFragAtPos","getMaxBufferLength","levelBitrate","maxBufLen","maxBufferSize","maxMaxBufferLength","threshold","minLength","fragOrPart","getNextFragment","fragLen","initialLiveManifestSize","getInitialLiveFragment","liveSyncPosition","getFragmentAtPosition","mapToInitFragWhenRequired","isLoopLoading","trackerState","getNextFragmentLoopLoading","gapStart","nextFragment","nextbufferInfo","contiguous","independentAttrOmitted","PDTValue","isArray","seg","findFragmentByPDT","targetSN","findFragWithCC","liveStart","loadingParts","curSNIdx","fragState","nextFrag","synchronizeToLiveEdge","withinSlidingWindow","readyState","alignPlaylists","slidingStart","firstLevelLoad","aligned","alignedSlidingStart","waitForCdnTuneIn","setStartPosition","offsetInMultivariantPlaylist","onFragmentOrKeyLoadError","filterType","_this$fragCurrent2","gapTagEncountered","_ref2$retryCount","_this$levelLastLoaded","resetStartWhenNotLoaded","resetFragmentErrors","reduceLengthAndFlushBuffer","flushBuffer","afterBufferFlushed","bufferType","bufferedTimeRanges","resetWhenMissingContext","_this$levelLastLoaded2","removeUnbufferedFrags","_this$transmuxer","_this6","parsedDuration","LEVEL_PTS_UPDATED","FRAG_PARSED","recoverWorkerError","_this$levelLastLoaded3","_this$fragCurrent3","nextState","previousState","getSourceBuffer","SourceBuffer","WebKitSourceBuffer","dummyTrack","inputTimeScale","pid","sequenceNumber","BaseAudioDemuxer","_audioTrack","_id3Track","frameIndex","cachedData","basePTS","lastPTS","resetInitSegment","trackDuration","resetTimeStamp","deaultTimestamp","resetContiguity","appendFrame","demux","lastDataIndex","initPTSFn","dts","sample","partialData","videoTrack","demuxSampleAes","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","headerLength","frameLength","newOffset","initTrackConfig","observer","samplerate","adtsObjectType","adtsExtensionSamplingIndex","adtsChannelConfig","toLowerCase","manifestCodec","adtsSamplingRates","adtsSamplingIndex","channelCount","getAudioConfig","getFrameDuration","unit","stamp","header","parseFrameHeader","missing","AACDemuxer","_BaseAudioDemuxer","container","segmentCodec","ADTS","canGetFrameLength","emsgSchemePattern","MP4Demuxer","txtTrack","captionTrack","initData","_initData$video","_initData$audio","videoSamples","segmentedData","segmentedRange","valid","remainder","moofs","last","segmentValidRange","extractID3Track","emsgs","emsgInfo","schemeIdUri","timeScale","presentationTimeDelta","presentationTime","eventDuration","leftPresentationTime","rightPresentationTime","_isSafeInteger","parseEmsg","chromeVersion","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","mpegVersion","mpegLayer","bitRateIndex","sampleRateIndex","paddingBit","channelMode","bitRate","sampleCoefficient","bytesInSlot","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","pixelRatio","ceil","readSliceType","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","callback","curUnit","encryptedBuffer","decryptedBuffer","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","uint8DecryptedData","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","units","PACKET_LENGTH","TSDemuxer","typeSupported","sampleAes","pmtParsed","_duration","_pmtId","_avcTrack","_txtTrack","aacOverFlow","avcSample","syncOffset","scanwindow","foundPat","packetStart","tsPackets","parsePID","pesData","isSampleAes","pes","avcId","avcData","audioId","id3Id","audioData","unknownPID","pmtId","tsPacketErrors","stt","parsePES","parseAVCPES","parseAACPES","parseMPEGPES","parseID3PES","parsePAT","parsedPIDs","parsePMT","avc","emit","demuxResult","extractRemainingSamples","parseAVCNALu","spsfound","audFound","pushAccessUnit","createAVCSample","_avcSample2","iskey","_avcSample","sliceType","sps","codecarray","codecstring","pps","getLastNalUnit","_avcSample3","lastUnit","overflow","naluState","lastState","lastUnitStart","lastUnitType","tmp","frameMissingBytes","sampleLength","frameOverflowBytes","recoverable","frameDuration","MpegAudio","id3Sample","tableEnd","mpeg","mp3","stream","pesLen","pesHdrLen","pesPts","pesDts","pesFlags","payloadStartOffset","dataLen","avcTrack","nbSamples","lastSample","MP3Demuxer","AAC","getSilentFrame","MP4","types","avcC","btrt","dinf","dref","esds","ftyp","mdat","mdia","mfhd","minf","moov","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsz","stts","vmhd","smhd","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","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","cts","arraylen","isLeading","paddingValue","isNonSync","degradPrio","movie","toTimescaleFromBase","destScale","srcBase","toMsFromMpegTsClock","safariWebkitVersion","MP4Remuxer","vendor","ISGenerated","_initPTS","_initDTS","nextAvcDts","nextAudioPts","videoSampleDuration","isAudioContiguous","isVideoContiguous","defaultTimeStamp","resetNextTimestamp","getVideoStartPts","rolloverDetected","minPTS","normalizePts","remux","accurateTimeOffset","audioTimeOffset","videoTimeOffset","hasAudio","hasVideo","enoughAudioSamples","enoughVideoSamples","generateIS","firstKeyFramePTS","firstKeyFrameIndex","findKeyframeIndex","forceKeyFrameOnDiscontinuity","audiovideoTimestampDelta","remuxAudio","audioTrackLength","remuxVideo","firstKeyFrame","flushTextTrackMetadataCueSamples","flushTextTrackUserdataCueSamples","initDTS","audioSamples","computePTSDTS","metadata","firstDTS","lastDTS","inputSamples","outputSamples","mp4SampleDuration","maxPTS","NEGATIVE_INFINITY","sortSamples","initTime","deltadts","deltapts","inputDuration","averageSampleDuration","foundHole","foundOverlap","firstPTS","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","MUX_ERROR","stretchedLastFrame","minDtsDelta","minPtsDelta","maxDtsDelta","maxPtsDelta","avcSampleUnits","mp4SampleLength","unitData","unitDataLen","ptsDelta","lastFrameDuration","stretchShortVideoTrack","gapTolerance","deltaToFrameEnd","compositionTimeOffset","Mp4Sample","nextDts","nextPts","nb","scaleFactor","inputSampleDuration","rawMPEG","alignedWithVideo","timeOffsetMpegTS","maxAudioFramesDrift","newStamp","fillFrame","audioSample","unitLen","remuxEmptyAudio","init90kHz","silentFrame","reference","isKeyframe","Mp4SampleFlags","PassThroughRemuxer","emitInitSegment","initTracks","lastEndTime","defaultInitPTS","generateInitSegment","sampleEntries","encBoxes","isAudio","enc","tenc","tencKeyId","patchEncyptionData","getParsedTrackCodec","_initData","_initData2","rawDuration","videoDuration","audioDuration","trafs","trackDefault","truns","sidxDuration","sidxs","dur","ref","getDuration","fmp4","getStartDTS","decodeTime","minDuration","isInvalidInitPts","upper","lower","offsetStartDTS","parsedCodec","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","Remuxer","Demuxer","p","Function","TransmuxConfig","TransmuxState","prefix","EE","fn","once","addListener","emitter","TypeError","listener","evt","_events","_eventsCount","clearEvent","EventEmitter","__proto__","eventNames","events","names","getOwnPropertySymbols","listeners","handlers","l","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","enableWorker","blob","objectURL","scriptURL","mp4","Worker","workerPath","location","worker","Blob","__HLS_WORKER_BUNDLE__","createObjectURL","onWorkerMessage","onerror","filename","lineno","resetWorker","_this$workerContext","revokeObjectURL","terminate","_frag$initSegment","_lastFrag$initSegment","snDiff","partDiff","ArrayBuffer","handleTransmuxComplete","transmuxerError","_this$workerContext2","GapController","nudgeRetry","stallReported","stalled","moved","seeking","poll","activeFrag","seeked","beginSeek","paused","hasEnoughBuffer","noBufferGap","startJump","maxStartGapJump","partialOrGap","_trySkipBufferHole","tnow","stalledDuration","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","highBufferWatchdogPeriod","_tryNudgeBuffer","bufferStarved","waiting","gapLength","startGap","startFrag","startProvisioned","moreToLoad","provisioned","targetTime","nudgeMaxRetry","nudgeOffset","StreamController","_BaseStreamController","audioCodecSwap","gapController","_forceStartLoad","fragPlaying","onvplaying","onvseeked","fragLastKbps","couldBacktrack","backtrackFragment","audioCodecSwitch","videoBuffer","onManifestParsed","FRAG_LOAD_EMERGENCY_ABORTED","onFragLoadEmergencyAborted","AUDIO_TRACK_SWITCHING","onAudioTrackSwitching","BUFFER_CREATED","onBufferCreated","BUFFER_FLUSHED","onBufferFlushed","testBandwidth","_levels$level","_this$media","doTickIdle","checkBuffer","checkFragmentChanged","startFragPrefetch","levelInfo","getMainFwdBufferInfo","BUFFER_EOS","manualLevel","_this$backtrackFragme","backtrackFrag","_loadBitrateTestFrag","followingBufferedFrag","immediateLevelSwitch","abortCurrentFrag","nextLevelSwitch","fetchdelay","fragPlayingCurrent","bufferedFrag","nextBufferedFrag","maxStart","startPts","onMediaPlaying","onMediaSeeked","BUFFER_RESET","_sourceBuffer$prototy","sourceBuffer","aac","heaac","changeType","_curLevel$details","newLevelId","_getAudioCodec","_handleTransmuxComplete","fromAltAudio","mediaTrack","alternate","swapAudioCodec","defaultAudioCodec","_id3$samples","mapFragment","_bufferInitSegment","FRAG_PARSING_INIT_SEGMENT","INIT_PTS_FOUND","isFirstFragment","isFirstInDiscontinuity","backtrack","emittedID3","emittedText","FRAG_PARSING_USERDATA","ua","levelCodec","BUFFER_CODECS","trackName","fragCurrentLevel","FRAG_CHANGED","LEVEL_SWITCHED","epocMs","EWMA","halfLife","estimate","weight","alpha_","estimate_","totalWeight_","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","AbrController","lastLevelLoadSec","lastLoadedFragLevel","_nextAutoLevel","onCheck","_abandonRulesCheck","partCurrent","bitrateTestDelay","bwEstimator","abrEwmaSlowVoD","abrEwmaFastVoD","abrEwmaDefaultEstimate","onFragLoading","onLevelSwitching","_data$part","ignoreFragment","getTimeToLoadFrag","timeToFirstByteSec","bandwidth","fragSizeBits","isSwitch","_data$stats","abrEwmaSlowLive","abrEwmaFastLive","timeLoading","ttfbEstimate","bufferStarvationDelay","loadedFirstByte","expectedLen","timeStreaming","loadRate","fragLoadedDelay","bwe","fragLevelNextLoadedDelay","levelNextBitrate","abrMaxWithRealBitrate","loadedBytes","loadedDuration","fragBufferedData","processingMs","getNextABRAutoLevel","currentFragDuration","avgbw","bestLevel","findBestLevel","abrBandWidthFactor","abrBandWidthUpFactor","maxStarvationDelay","bwFactor","bwUpFactor","maxLoadingDelay","currentBw","maxFetchDuration","currentCodecSet","ttfbEstimateSec","levelSkippedMin","levelSkippedMax","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","nextABRAutoLevel","ChunkCache","chunks","dataLength","chunk","concatUint8Arrays","AudioStreamController","videoTrackCC","waitingVideoCC","bufferedTrack","switchingTrack","waitingData","mainDetails","bufferFlushed","cachedTrackLoadedData","AUDIO_TRACKS_UPDATED","onAudioTracksUpdated","onAudioTrackLoaded","onBufferReset","onInitPtsFound","_levels$trackId","cache","clearWaitingFragment","trackDetails","mainBufferInfo","atGap","atBufferSyncLimit","mainFrag","mainBufferLength","maxConfigBuffer","mediaPlaylist","_track$details","completeAudioSwitch","_track$details2","bufferedAttributes","switchAttributes","CHANNELS","AudioTrackController","tracksInGroup","currentTrack","selectDefaultTrack","trackInActiveGroup","audioTracksUpdated","selectInitialTrack","setAudioTrack","newId","lastTrack","findTrackId","subtitleOptionsIdentical","trackList1","trackList2","subtitleAttributesIdentical","attrs1","attrs2","stableRenditionId","subtitleAttribute","SubtitleStreamController","currentTrackId","tracksBuffered","SUBTITLE_TRACKS_UPDATED","onSubtitleTracksUpdated","SUBTITLE_TRACK_SWITCH","onSubtitleTrackSwitch","onSubtitleTrackLoaded","SUBTITLE_FRAG_PROCESSED","onSubtitleFragProcessed","success","fragStart","fragEnd","endOffsetSubtitles","mediaBufferTimeRanges","mainSlidingStartFragment","levelTargetDuration","foundFrag","lookupTolerance","BufferableInstance","timeranges","getRange","DOMException","SubtitleTrackController","queuedDefaultTrack","trackChangeListener","onTextTracksChanged","asyncPollTrackChange","pollTrackChange","useTextTrackPolling","subtitlePollingInterval","_subtitleDisplay","subtitleTrack","filterSubtitleTracks","initialTrackId","subtitleTracksUpdated","setSubtitleTrack","toggleTrackModes","groupTracks","oldTrack","nextTrack","subtitleDisplay","_tracks$newId","_track$groupId","renderTextTracksNatively","textTrackList","BufferOperationQueue","sourceBufferReference","buffers","queues","append","operation","queue","executeNext","insertAbort","appendBlocker","execute","promise","onStart","onComplete","sb","updating","shiftAndExecuteNext","current","VIDEO_CODEC_PROFILE_REPACE","BufferController","_objectUrl","operationQueue","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","lastMpegAudioChunk","appendError","pendingTracks","_onMediaSourceOpen","_onMediaEmptied","updateMediaElementDuration","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","src","_initSourceBuffer","hasSourceTypes","getSourceBufferTypes","MEDIA_ATTACHING","onMediaAttaching","onBufferAppending","onBufferCodecs","onBufferEos","onFragParsed","onFragChanged","codecEvents","ms","endOfStream","removeAttribute","MEDIA_DETACHED","removeBufferListeners","removeSourceBuffer","sourceBufferCount","_data$trackName","currentCodec","nextCodec","mimeType","appendChangeType","eventData","chunkStats","bufferAppendingStart","fragBuffering","partBuffering","checkTimestampOffset","timestampOffset","appendExecutor","QUOTA_EXCEEDED_ERR","appendErrorMaxRetry","flushOperation","removeExecutor","_this7","buffersAppendedTo","blockBuffers","flushBackBuffer","_this8","ending","sourceBufferTypes","backBufferLength","liveBackBufferLength","maxBackBufferLength","targetBackBufferPosition","BACK_BUFFER_REACHED","LIVE_BACK_BUFFER_REACHED","levelDuration","mediaDuration","msDuration","liveDurationInfinity","updateSeekableRange","setLiveSeekableRange","pendingTracksCount","createSourceBuffers","BUFFER_INCOMPATIBLE_CODECS_ERROR","addSourceBuffer","sbName","addBufferListener","_onSBUpdateStart","_onSBUpdateEnd","_onSBUpdateError","removeStart","removeEnd","remove","appendBuffer","onUnblocked","_this9","blockingOperations","specialCea608CharsCodes","getCharForByte","byte","charCode","NR_ROWS","NR_COLS","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","CaptionsLogger","verboseLevel","severity","m","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","setStyles","styles","attribs","style","isDefault","equals","other","copy","newPenState","StyledUnicodeChar","uchar","penState","_proto3","setChar","setPenState","newChar","isEmpty","Row","chars","currPenState","cueStartTime","_proto4","equal","empty","setCursor","absPos","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","rows","currRow","nrRollUpRows","lastOutputScreen","_proto5","setPen","setPAC","pacData","newRow","row","topRowIndex","prevLineTime","indent","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","_proto6","getHandler","setHandler","newHandler","setMode","newMode","insertChars","screen","outputDataUpdate","ccRCL","ccBS","ccAOF","ccAON","ccDER","ccRU","ccFON","ccRDC","ccTR","ccRTD","ccEDM","ccCR","ccENM","ccEOC","ccTO","nrCols","ccMIDROW","secondByte","colorIndex","dispatch","newCue","dispatchCue","cueSplitAtTime","Cea608Parser","field","out1","out2","channels","currentChannel","cmdHistory","_proto7","channel","addData","byteList","cmdFound","charsFound","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","currChNr","hasCmdRepeated","setLastCmd","interpretPAC","pacIndex","channelNr","oneCode","charCodes","charCode1","hexCodes","OutputFilter","timelineController","cueRanges","addCues","createCaptionsTrack","AllowedDirections","AllowedAlignments","isAllowedValue","allowed","lcValue","findAlignSetting","extend","obj","rest","cobj","baseObj","enumerable","hasBeenReset","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","defineProperty","setting","findDirectionSetting","SyntaxError","displayState","getCueAsHTML","WebVTT","convertCueToDOMTree","StringDecoder","options","decodeURIComponent","parseTimeStamp","computeSeconds","s","f","Settings","values","dflt","defaultKey","alt","n","integer","percent","parseOptions","keyValueDelim","groupDelim","kv","defaults","center","align","parseCue","regionList","oInput","consumeTimeStamp","ts","skipWhitespace","settings","vals","region","vertical","line","lineAlign","snapToLines","consumeCueSettings","fixLineBreaks","VTTParser","oncue","onparsingerror","onflush","collectNextLine","alreadyCollectedLine","hasSubstring","LINEBREAKS","inputString","searchString","hash","generateCueId","parseWebVTT","vttByteArray","vttCCs","callBack","errorCallBack","srcScale","parsingError","parser","vttLines","cueTime","timestampMapMPEGTS","timestampMapLOCAL","inHeader","currCC","cueOffset","webVttMpegTsMapOffset","new","prevCC","presentationOffset","_prevCC","calculateOffset","timeString","secs","mins","hours","cueString2millis","IMSC1_CODEC","HMSF_REGEX","TIME_UNIT_REGEX","textAlignToLineAlign","parseIMSC1","ttmlList","syncTime","ttml","tt","defaultRateInfo","frameRate","subFrameRate","frameRateMultiplier","tickRate","rateInfo","styleElements","collectionToDictionary","getElementCollection","regionElements","cueElements","cueElement","cueText","getTextContent","hasAttribute","parseTtmlTime","timestampParsingError","ttsNs","regionStyle","styleAttributes","regionStyleName","getAttributeNS","getTtmlStyles","textAlign","parseTTML","fromElement","parentName","childName","querySelectorAll","elementsWithId","dict","element","node","_node$childNodes","nodeName","textContent","ns","hasAttributeNS","timeAttributeValue","parseHoursMinutesSecondsFrames","parseTimeUnits","TimelineController","Cues","unparsedVttFrags","captionsTracks","nonNativeCaptionsTracks","cea608Parser1","cea608Parser2","captionsProperties","cueHandler","textTrack1","captionsTextTrack1Label","languageCode","captionsTextTrack1LanguageCode","textTrack2","captionsTextTrack2Label","captionsTextTrack2LanguageCode","textTrack3","captionsTextTrack3Label","captionsTextTrack3LanguageCode","textTrack4","captionsTextTrack4Label","captionsTextTrack4LanguageCode","enableCEA708Captions","channel1","channel2","channel3","channel4","onFragParsingUserdata","onFragDecrypted","SUBTITLE_TRACKS_CLEARED","onSubtitleTracksCleared","x1","y1","y2","merged","cueRange","overlap","CUES_PARSED","getExistingTrack","createNativeTrack","createNonNativeTrack","_captionsProperties$t","existingTrack","createTextTrack","trackProperties","closedCaptions","NON_NATIVE_TEXT_TRACKS_FOUND","_cleanTracks","hasIMSC1","enableWebVTT","enableIMSC1","inUseTracks","inUseTrack","canReuseVttTextTrack","textTrackKind","_captionsOrSubtitlesFromCharacteristics","tracksList","CHARACTERISTICS","transcribesSpokenDialog","describesMusicAndSound","captionsTrack","instreamIdMatch","closedCaptionsForLevel","_data$part$index","decrypted","trackPlaylistMedia","_parseIMSC1","_parseVTTs","_appendCues","maxAvCC","missingInitPTS","_fallbackToIMSC1","fragLevel","ccBytes","ccdatas","extractCea608Data","actualCCBytes","tmpByte","ccbyte1","ccbyte2","ccType","manifestTrack","CapLevelController","autoLevelCapping","restrictedLevels","clientRect","streamController","setStreamController","unregisterListener","capLevelToPlayerSize","stopCapping","FPS_DROP_LEVEL_CAPPING","onFpsDropLevelCapping","droppedLevel","isLevelAllowed","HTMLVideoElement","startCapping","detectPlayerSize","mediaHeight","mediaWidth","getMaxLevel","capLevelIndex","validLevels","getMaxLevelByMediaSize","getDimensions","boundsRect","getBoundingClientRect","bottom","top","restrictedLevel","maxLevelIndex","contentScaleFactor","ignoreDevicePixelRatio","devicePixelRatio","FPSController","isVideoPlaybackQualityAvailable","lastTime","lastDroppedFrames","lastDecodedFrames","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","currentPeriod","currentDropped","currentDecoded","droppedFPS","FPS_DROP","totalDroppedFrames","fpsDroppedMonitoringThreshold","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","LOGGER_PREFIX","EMEController","keyFormatPromise","keySystemAccessPromises","_requestLicenseFailureCount","mediaKeySessions","keyIdToKeySessionPromise","setMediaKeysQueue","CDMCleanupPromise","onMediaEncrypted","_onMediaEncrypted","onWaitingForKey","_onWaitingForKey","onMediaDetached","requestMediaKeySystemAccessFunc","licenseXhrSetup","licenseResponseCallback","drmSystemOptions","getLicenseServerUrl","keySystemConfiguration","licenseUrl","getServerCertificateUrl","serverCertificateUrl","attemptKeySystemAccess","uniqueCodec","audioCodecs","videoCodecs","attempt","keySystems","getMediaKeysPromise","mediaKeys","EMEKeyError","KEY_SYSTEM_NO_ACCESS","supportedConfigurations","errMessage","protocol","mediaKeySystemConfigs","initDataTypes","persistentState","distinctiveIdentifier","sessionTypes","sessionType","audioCapabilities","contentType","robustness","audioRobustness","encryptionScheme","audioEncryptionScheme","videoCapabilities","videoRobustness","videoEncryptionScheme","createMediaKeySystemConfigurations","getSupportedMediaKeySystemConfigurations","keySystemAccess","mediaKeySystemAccess","certificateRequest","fetchServerCertificate","createMediaKeys","certificate","setMediaKeysServerCertificate","createMediaKeySessionContext","mediaKeysSession","createSession","renewKeySession","getKeyIdString","generateRequestWithPreferredKeySession","removeSession","updateKeySession","_mediaKeySessionConte","keySession","sessionId","getKeyFormatPromise","keySystemsInConfig","getKeySystemSelectionPromise","keySystemToKeySystemFormat","keyDetails","getKeySystemForKeyPromise","throwIfDestroyed","attemptSetMediaKeys","handleError","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_CONFIGURED_LICENSE","initDataType","keySystemDomain","json","psshInfo","boxSize","dataSizeOrKidCount","parsePssh","keySystemIdToKeySystemDomain","keyIdHex","keyContext","oldKeyIdHex","_keySystemToKeySystem","setMediaKeysPromise","setMediaKeys","_this$config$drmSyste","_this$config$drmSyste2","generateRequestFilter","generateRequest","mappedInitData","_this$hls","licenseStatus","onmessage","messageType","renewLicense","onkeystatuseschange","onKeyStatusChange","keyUsablePromise","KEY_SYSTEM_STATUS_INTERNAL_ERROR","_context$mediaKeysSes","KEY_SYSTEM_NO_SESSION","keyStatuses","status","certLoader","certLoadPolicy","contex","KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED","cert","setServerCertificate","KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED","keyMessage","_this10","requestLicense","KEY_SYSTEM_SESSION_UPDATE_FAILED","setupLicenseXHR","xhr","keysListItem","licenseChallenge","_this11","open","licenseXhrSetupResult","_this12","XMLHttpRequest","onreadystatechange","KEY_SYSTEM_LICENSE_REQUEST_FAILED","statusText","attemptsLeft","licenseXhr","DONE","_ref5","send","_this13","mediaKeysList","keySessionCount","_ref6","formats","_this14","close","_this15","CMCDObjectType","CMCDController","sid","cid","useHeaders","initialized","starved","audioBuffer","onWaiting","onPlaying","applyPlaylistData","ot","su","applyFragmentData","getObjectType","br","tb","getTopBandwidth","bl","getBufferLength","cmcd","createPlaylistLoader","createFragmentLoader","contentId","_data$tracks$audio","_data$tracks$video","createData","sf","pr","mtp","bandwidthEstimate","isVideo","bs","toHeaders","toQuery","appendQueryToUri","_step","_iterator","_createForOfIteratorHelperLoose","done","Ctor","CmcdPlaylistLoader","callbacks","CmcdFragmentLoader","serialize","_step2","toRounded","toHundred","formatters","dl","nor","rtp","_iterator2","formatter","headerNames","headerGroups","headerMap","nrr","st","_i","_keys","separator","ContentSteeringController","pathwayPriority","timeToLoad","reloadTimer","started","penalizedPathways","ttl","scheduleRefresh","loadSteeringManifest","levelToRemove","pathways","updatePathwayPriority","pathwayLevels","getLevelsForPathway","selectedIndex","selectedLevel","levelAfterChange","clonePathways","pathwayClones","audioGroupCloneMap","subtitleGroupCloneMap","pathwayClone","cloneId","baseId","uriReplacement","clonedVariants","baseLevel","performUriReplacement","clonedAudioGroupId","clonedSubtitleGroupId","clonedLevel","cloneRenditionGroups","throughput","steeringManifestLoadPolicy","steeringData","VERSION","TTL","reloadUri","getResponseHeader","retryAfter","ttlMs","groupCloneMap","clonedTracks","clonedTrack","stableId","perOptionKey","perVariantUri","host","HOST","PARAMS","perOptionUris","AGE_HEADER_LINE_REGEX","XhrLoader","xhrSetup","requestTimeout","retryTimeout","abortInternal","onprogress","_this$callbacks","openAndSendXhr","_config$loadPolicy","setRequestHeader","readystatechange","loadprogress","loadtimeout","useResponse","responseText","responseURL","lengthComputable","getAllResponseHeaders","FetchLoader","fetchSetup","request","controller","getRequest","AbortController","ok","initParams","signal","credentials","Headers","getRequestParameters","isArrayBuffer","LENGTH","fetch","FetchError","contentRange","byteRangeLength","byteRangeHeader","getByteRangeLength","contentLength","getContentLength","loadProgressively","responseData","loaderResponse","chunkCache","reader","getReader","pump","read","Request","WHITESPACE_CHAR","hlsDefaultConfig","abrController","bufferController","capLevelController","errorController","fpsController","minAutoBitrate","manifestLoadingTimeOut","manifestLoadingMaxRetry","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","fragLoadingTimeOut","fragLoadingMaxRetry","fragLoadingRetryDelay","fragLoadingMaxRetryTimeout","captionScreen","indenting","_track$cues","cueA","cueB","subtitleStreamController","subtitleTrackController","audioStreamController","audioTrackController","cmcdController","deepCpy","enableStreamingMode","currentLoader","ReadableStream","fetchSupported","Hls","coreComponents","networkControllers","_emitter","_autoLevelCapping","_maxHdcpLevel","latencyController","levelController","_media","defaultConfig","defaultsCopy","deprecatedSettings","policyName","policyNotSet","report","deprecatedSetting","mergeConfig","DefaultConfig","ConfigAbrController","ConfigBufferController","ConfigCapLevelController","ConfigErrorController","ConfigFpsController","playListLoader","id3TrackController","ConfigContentSteeringController","createController","AudioStreamControllerClass","SubtitleStreamControllerClass","sourceBufferValidAPI","ControllerClass","components","controllerInstance","eventObject","DESTROYING","detachMedia","component","attachMedia","loadSource","loadedSource","loadingSource","recoverMediaError","shouldStartCapping","newCapLevelToPlayerSize","currentProgramDateTime","audioTrackId","subtitleTrackId"],"mappings":"swHAEA,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,IAAK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ACNhjD,KAAM,GACNE,KAAM,GACNJ,KAAM,GACNlC,KAAM,GACNkB,KAAM,GACNR,KAAM,GACNT,KAAM,GACNolD,KAAM,GACNC,KAAM,IAIEvB,EAAIC,MACRD,EAAIC,MAAMj4D,eAAee,KAC3Bi3D,EAAIC,MAAMl3D,GAAK,CACbA,EAAEgM,WAAW,GACbhM,EAAEgM,WAAW,GACbhM,EAAEgM,WAAW,GACbhM,EAAEgM,WAAW,KAKnB,IAAMysD,EAAY,IAAI14D,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,IAGI24D,EAAY,IAAI34D,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,IAGFk3D,EAAI0B,WAAa,CACf7wD,MAAO2wD,EACP5wD,MAAO6wD,GAGT,IAAMpB,EAAO,IAAIv3D,WAAW,CAC1B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,IACA,IACA,GACA,EACA,EACA,EACA,IAGIo4D,EAAO,IAAIp4D,WAAW,CAC1B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAGFk3D,EAAI2B,KAAO3B,EAAI4B,KAAO5B,EAAI6B,KAAOX,EAEjClB,EAAI8B,KAAO,IAAIh5D,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAEFk3D,EAAI+B,KAAO,IAAIj5D,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAEF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,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,KAEFq5D,EACA/C,EAAIsC,IACFtC,EAAIC,MAAME,KACV,IAAIr3D,WAAW,CACb,EACA,GACA,IACA,IACA,EACA,GACA,IACA,IACA,EACA,GACA,IACA,OAGJk3D,EAAIsC,IACFtC,EAAIC,MAAMc,KACV,IAAIj4D,WAAW,CACbk6D,GAAY,GACXA,GAAY,GAAM,IAClBA,GAAY,EAAK,IACP,IAAXA,EACAC,GAAY,GACXA,GAAY,GAAM,IAClBA,GAAY,EAAK,IACP,IAAXA,OAIPjD,EAEMM,KAAP,SAAY1jD,GACV,IAAMsmD,EAAYtmD,EAAMjG,OAAO1R,OAC/B,OAAO,IAAI6D,WACT,CACE,EACA,EACA,EACA,EAEA,EACA,GAAOo6D,EACP,EACA,EACA,EAEA,EACA,GAAOA,EACP,GACA,GACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAEA,GAEC3/B,OAAO,CAAC2/B,IACR3/B,OAAO3mB,EAAMjG,QACb4sB,OAAO,CAAC,EAAM,EAAM,MAE1By8B,EAEMz4C,KAAP,SAAY3K,GACV,IAAM01C,EAAa11C,EAAM01C,WACzB,OAAO0N,EAAIsC,IACTtC,EAAIC,MAAM14C,KACV,IAAIze,WAAW,CACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA8T,EAAMk2C,aACN,EACA,GACA,EACA,EACA,EACA,EACCR,GAAc,EAAK,IACP,IAAbA,EACA,EACA,IAEF0N,EAAIsC,IAAItC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3BA,GAAqB,EAAK,IACP,IAApBA,EACAC,GAAqB,GACpBA,GAAqB,GAAM,IAC3BA,GAAqB,EAAK,IACP,IAApBA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,EACA,EACA,EACCh5D,GAAS,EAAK,IACP,IAARA,EACA,EACA,EACCC,GAAU,EAAK,IACP,IAATA,EACA,EACA,MAGLs2D,EAEM7hD,KAAP,SAAYvB,EAAO8lD,GACjB,IAAMS,EAAwBnD,EAAIgB,KAAKpkD,GACjC5V,EAAK4V,EAAM5V,GACXo8D,EAA+B39D,KAAKwO,MACxCyuD,GAAuBtoD,GAAa,IAEhCipD,EAA+B59D,KAAKwO,MACxCyuD,GAAuBtoD,GAAa,IAEtC,OAAO4lD,EAAIsC,IACTtC,EAAIC,MAAM9hD,KACV6hD,EAAIsC,IACFtC,EAAIC,MAAM1hD,KACV,IAAIzV,WAAW,CACb,EACA,EACA,EACA,EACA9B,GAAM,GACLA,GAAM,GAAM,IACZA,GAAM,EAAK,IACP,IAALA,KAGJg5D,EAAIsC,IACFtC,EAAIC,MAAM5hD,KACV,IAAIvV,WAAW,CACb,EACA,EACA,EACA,EACAs6D,GAAgC,GAC/BA,GAAgC,GAAM,IACtCA,GAAgC,EAAK,IACP,IAA/BA,EACAC,GAAgC,GAC/BA,GAAgC,GAAM,IACtCA,GAAgC,EAAK,IACP,IAA/BA,KAGJrD,EAAI7iD,KACFP,EACAumD,EAAsBl+D,OACpB,GACA,GACA,EACA,GACA,EACA,GAEJk+D,EAEJ,EAEAnD,EAIO/jD,KAAP,SAAYW,GAEV,OADAA,EAAMzR,SAAWyR,EAAMzR,UAAY,WAC5B60D,EAAIs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