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

1 line
No EOL
1.7 MiB
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

{"version":3,"file":"hls.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/global.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/utils/level-helper.ts","src/utils/error-helper.ts","src/utils/binary-search.ts","src/controller/fragment-finders.ts","src/controller/error-controller.ts","src/controller/base-playlist-controller.ts","src/utils/ewma.ts","src/utils/ewma-bandwidth-estimator.ts","src/utils/mediacapabilities-helper.ts","src/utils/hdr.ts","src/utils/rendition-helper.ts","src/controller/abr-controller.ts","src/task-loop.ts","src/controller/fragment-tracker.ts","src/utils/buffer-helper.ts","src/types/transmuxer.ts","src/utils/discontinuities.ts","src/loader/fragment-loader.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/demux/chunk-cache.ts","src/demux/dummy-demuxed-track.ts","src/demux/audio/base-audio-demuxer.ts","src/demux/audio/adts.ts","src/demux/audio/mpegaudio.ts","src/demux/audio/aacdemuxer.ts","src/demux/mp4demuxer.ts","src/demux/audio/dolby.ts","src/demux/audio/ac3-demuxer.ts","src/demux/video/base-video-parser.ts","src/demux/video/exp-golomb.ts","src/demux/video/avc-video-parser.ts","src/demux/sample-aes.ts","src/demux/tsdemuxer.ts","src/demux/audio/mp3demuxer.ts","src/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/utils/media-option-attributes.ts","src/controller/audio-stream-controller.ts","src/controller/audio-track-controller.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","node_modules/@svta/common-media-library/dist/cta/CmObjectType.js","node_modules/@svta/common-media-library/dist/cta/CmStreamingFormat.js","node_modules/@svta/common-media-library/dist/cmcd/CmcdHeaderField.js","node_modules/@svta/common-media-library/dist/cmcd/CmcdHeaderMap.js","node_modules/@svta/common-media-library/dist/structuredfield/SfItem.js","node_modules/@svta/common-media-library/dist/structuredfield/SfToken.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/DICT.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/throwError.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/BARE_ITEM.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/BOOLEAN.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/BYTES.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/DECIMAL.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/INTEGER.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/STRING_REGEX.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/TOKEN.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/KEY.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeError.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeByteSequence.js","node_modules/@svta/common-media-library/dist/utils/base64encode.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeInteger.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/isInvalidInt.js","node_modules/@svta/common-media-library/dist/utils/roundToEven.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeDecimal.js","node_modules/@svta/common-media-library/dist/structuredfield/utils/STRING.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeToken.js","node_modules/@svta/common-media-library/dist/cta/utils/symbolToStr.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeBareItem.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeString.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeBoolean.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeDate.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeKey.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeParams.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeItem.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeDict.js","node_modules/@svta/common-media-library/dist/structuredfield/serialize/serializeInnerList.js","node_modules/@svta/common-media-library/dist/cta/utils/isTokenField.js","node_modules/@svta/common-media-library/dist/cta/utils/isValid.js","node_modules/@svta/common-media-library/dist/cmcd/CmcdFormatters.js","node_modules/@svta/common-media-library/dist/utils/urlToRelativePath.js","node_modules/@svta/common-media-library/dist/cmcd/encodeCmcd.js","node_modules/@svta/common-media-library/dist/structuredfield/encodeSfDict.js","node_modules/@svta/common-media-library/dist/cmcd/utils/processCmcd.js","node_modules/@svta/common-media-library/dist/cmcd/appendCmcdHeaders.js","node_modules/@svta/common-media-library/dist/cmcd/toCmcdHeaders.js","node_modules/@svta/common-media-library/dist/cmcd/CMCD_PARAM.js","node_modules/@svta/common-media-library/dist/cmcd/appendCmcdQuery.js","node_modules/@svta/common-media-library/dist/cmcd/toCmcdQuery.js","src/controller/cmcd-controller.ts","node_modules/@svta/common-media-library/dist/utils/uuid.js","src/controller/content-steering-controller.ts","src/utils/xhr-loader.ts","src/utils/fetch-loader.ts","src/controller/level-controller.ts","src/utils/cues.ts","src/config.ts","src/loader/key-loader.ts","src/is-supported.ts","src/controller/gap-controller.ts","src/controller/stream-controller.ts","src/hls.ts"],"sourcesContent":["// see https://tools.ietf.org/html/rfc1808\n\n(function (root) {\n var URL_REGEX =\n /^(?=((?:[a-zA-Z0-9+\\-.]+:)?))\\1(?=((?:\\/\\/[^\\/?#]*)?))\\2(?=((?:(?:[^?#\\/]*\\/)*[^;?#\\/]*)?))\\3((?:;[^?#]*)?)(\\?[^#]*)?(#[^]*)?$/;\n var FIRST_SEGMENT_REGEX = /^(?=([^\\/?#]*))\\1([^]*)$/;\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/)[^\\/]*(?=\\/)/g;\n\n var URLToolkit = {\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n // E.g\n // With opts.alwaysNormalize = false (default, spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n // With opts.alwaysNormalize = true (not spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n opts = opts || {};\n // remove any remaining space and CRLF\n baseURL = baseURL.trim();\n relativeURL = relativeURL.trim();\n if (!relativeURL) {\n // 2a) If the embedded URL is entirely empty, it inherits the\n // entire base URL (i.e., is set equal to the base URL)\n // and we are done.\n if (!opts.alwaysNormalize) {\n return baseURL;\n }\n var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n if (!basePartsForNormalise) {\n throw new Error('Error trying to parse base URL.');\n }\n basePartsForNormalise.path = URLToolkit.normalizePath(\n basePartsForNormalise.path\n );\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\n }\n var relativeParts = URLToolkit.parseURL(relativeURL);\n if (!relativeParts) {\n throw new Error('Error trying to parse relative URL.');\n }\n if (relativeParts.scheme) {\n // 2b) If the embedded URL starts with a scheme name, it is\n // interpreted as an absolute URL and we are done.\n if (!opts.alwaysNormalize) {\n return relativeURL;\n }\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n return URLToolkit.buildURLFromParts(relativeParts);\n }\n var baseParts = URLToolkit.parseURL(baseURL);\n if (!baseParts) {\n throw new Error('Error trying to parse base URL.');\n }\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n baseParts.netLoc = pathParts[1];\n baseParts.path = pathParts[2];\n }\n if (baseParts.netLoc && !baseParts.path) {\n baseParts.path = '/';\n }\n var builtParts = {\n // 2c) Otherwise, the embedded URL inherits the scheme of\n // the base URL.\n scheme: baseParts.scheme,\n netLoc: relativeParts.netLoc,\n path: null,\n params: relativeParts.params,\n query: relativeParts.query,\n fragment: relativeParts.fragment,\n };\n if (!relativeParts.netLoc) {\n // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n // Step 7. Otherwise, the embedded URL inherits the <net_loc>\n // (if any) of the base URL.\n builtParts.netLoc = baseParts.netLoc;\n // 4) If the embedded URL path is preceded by a slash \"/\", the\n // path is not relative and we skip to Step 7.\n if (relativeParts.path[0] !== '/') {\n if (!relativeParts.path) {\n // 5) If the embedded URL path is empty (and not preceded by a\n // slash), then the embedded URL inherits the base URL path\n builtParts.path = baseParts.path;\n // 5a) if the embedded URL's <params> is non-empty, we skip to\n // step 7; otherwise, it inherits the <params> of the base\n // URL (if any) and\n if (!relativeParts.params) {\n builtParts.params = baseParts.params;\n // 5b) if the embedded URL's <query> is non-empty, we skip to\n // step 7; otherwise, it inherits the <query> of the base\n // URL (if any) and we skip to step 7.\n if (!relativeParts.query) {\n builtParts.query = baseParts.query;\n }\n }\n } else {\n // 6) The last segment of the base URL's path (anything\n // following the rightmost slash \"/\", or the entire path if no\n // slash is present) is removed and the embedded URL's path is\n // appended in its place.\n var baseURLPath = baseParts.path;\n var newPath =\n baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +\n relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize\n ? URLToolkit.normalizePath(relativeParts.path)\n : relativeParts.path;\n }\n return URLToolkit.buildURLFromParts(builtParts);\n },\n parseURL: function (url) {\n var parts = URL_REGEX.exec(url);\n if (!parts) {\n return null;\n }\n return {\n scheme: parts[1] || '',\n netLoc: parts[2] || '',\n path: parts[3] || '',\n params: parts[4] || '',\n query: parts[5] || '',\n fragment: parts[6] || '',\n };\n },\n normalizePath: function (path) {\n // The following operations are\n // then applied, in order, to the new path:\n // 6a) All occurrences of \"./\", where \".\" is a complete path\n // segment, are removed.\n // 6b) If the path ends with \".\" as a complete path segment,\n // that \".\" is removed.\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n // complete path segment not equal to \"..\", are removed.\n // Removal of these path segments is performed iteratively,\n // removing the leftmost matching pattern on each iteration,\n // until no matching pattern remains.\n // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n // complete path segment not equal to \"..\", that\n // \"<segment>/..\" is removed.\n while (\n path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length\n ) {}\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function (parts) {\n return (\n parts.scheme +\n parts.netLoc +\n parts.path +\n parts.params +\n parts.query +\n parts.fragment\n );\n },\n };\n\n if (typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if (typeof define === 'function' && define.amd)\n define([], function () {\n return URLToolkit;\n });\n else if (typeof exports === 'object') exports['URLToolkit'] = URLToolkit;\n else root['URLToolkit'] = URLToolkit;\n})(this);\n","// https://caniuse.com/mdn-javascript_builtins_number_isfinite\nexport const isFiniteNumber =\n Number.isFinite ||\n function (value) {\n return typeof value === 'number' && isFinite(value);\n };\n\n// https://caniuse.com/mdn-javascript_builtins_number_issafeinteger\nexport const isSafeInteger =\n Number.isSafeInteger ||\n function (value) {\n return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;\n };\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n","import {\n ManifestLoadedData,\n ManifestLoadingData,\n MediaAttachedData,\n MediaAttachingData,\n LevelLoadingData,\n LevelLoadedData,\n ManifestParsedData,\n LevelUpdatedData,\n LevelsUpdatedData,\n FragParsingUserdataData,\n FragDecryptedData,\n FragLoadedData,\n InitPTSFoundData,\n CuesParsedData,\n SubtitleFragProcessedData,\n NonNativeTextTracksData,\n FragLoadingData,\n AudioTrackLoadedData,\n SubtitleTrackLoadedData,\n ErrorData,\n AudioTrackSwitchingData,\n AudioTrackSwitchedData,\n KeyLoadedData,\n KeyLoadingData,\n SubtitleTrackSwitchData,\n SubtitleTracksUpdatedData,\n LevelSwitchedData,\n FragChangedData,\n BufferAppendingData,\n BufferCodecsData,\n FragParsingMetadataData,\n FragParsingInitSegmentData,\n FragBufferedData,\n BufferFlushingData,\n BufferEOSData,\n LevelSwitchingData,\n MaxAutoLevelUpdatedData,\n FPSDropLevelCappingData,\n FPSDropData,\n BufferCreatedData,\n BufferAppendedData,\n LevelPTSUpdatedData,\n FragParsedData,\n AudioTracksUpdatedData,\n FragLoadEmergencyAbortedData,\n BackBufferData,\n LiveBackBufferData,\n TrackLoadingData,\n BufferFlushedData,\n SteeringManifestLoadedData,\n} from './types/events';\n\nexport enum Events {\n // Fired before MediaSource is attaching to media element\n MEDIA_ATTACHING = 'hlsMediaAttaching',\n // Fired when MediaSource has been successfully attached to media element\n MEDIA_ATTACHED = 'hlsMediaAttached',\n // Fired before detaching MediaSource from media element\n MEDIA_DETACHING = 'hlsMediaDetaching',\n // Fired when MediaSource has been detached from media element\n MEDIA_DETACHED = 'hlsMediaDetached',\n // Fired when the buffer is going to be reset\n BUFFER_RESET = 'hlsBufferReset',\n // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS = 'hlsBufferCodecs',\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n BUFFER_CREATED = 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING = 'hlsBufferAppending',\n // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}\n BUFFER_APPENDED = 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n BUFFER_EOS = 'hlsBufferEos',\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n BUFFER_FLUSHING = 'hlsBufferFlushing',\n // fired when the media buffer has been flushed - data: { }\n BUFFER_FLUSHED = 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING = 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }\n MANIFEST_LOADED = 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED = 'hlsManifestParsed',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING = 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED = 'hlsLevelSwitched',\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n LEVEL_LOADING = 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }\n LEVEL_LOADED = 'hlsLevelLoaded',\n // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }\n LEVEL_UPDATED = 'hlsLevelUpdated',\n // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }\n LEVEL_PTS_UPDATED = 'hlsLevelPtsUpdated',\n // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }\n LEVELS_UPDATED = 'hlsLevelsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED = 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING = 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED = 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING = 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }\n AUDIO_TRACK_LOADED = 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED = 'hlsSubtitleTracksUpdated',\n // fired to notify that subtitle tracks were cleared as a result of stopping the media\n SUBTITLE_TRACKS_CLEARED = 'hlsSubtitleTracksCleared',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH = 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING = 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }\n SUBTITLE_TRACK_LOADED = 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED = 'hlsSubtitleFragProcessed',\n // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n CUES_PARSED = 'hlsCuesParsed',\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n NON_NATIVE_TEXT_TRACKS_FOUND = 'hlsNonNativeTextTracksFound',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }\n INIT_PTS_FOUND = 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING = 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED = 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }\n FRAG_LOADED = 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED = 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n FRAG_PARSING_INIT_SEGMENT = 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA = 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA = 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n // FRAG_PARSING_DATA = 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED = 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }\n FRAG_BUFFERED = 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED = 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP = 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }\n FPS_DROP_LEVEL_CAPPING = 'hlsFpsDropLevelCapping',\n // triggered when maxAutoLevel changes - data { autoLevelCapping, levels, maxAutoLevel, minAutoLevel, maxHdcpLevel }\n MAX_AUTO_LEVEL_UPDATED = 'hlsMaxAutoLevelUpdated',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n ERROR = 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n DESTROYING = 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING = 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }\n KEY_LOADED = 'hlsKeyLoaded',\n // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }\n LIVE_BACK_BUFFER_REACHED = 'hlsLiveBackBufferReached',\n // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }\n BACK_BUFFER_REACHED = 'hlsBackBufferReached',\n // fired after steering manifest has been loaded - data: { steeringManifest: SteeringManifest object, url: steering manifest URL }\n STEERING_MANIFEST_LOADED = 'hlsSteeringManifestLoaded',\n}\n\n/**\n * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.\n */\nexport interface HlsListeners {\n [Events.MEDIA_ATTACHING]: (\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) => void;\n [Events.MEDIA_ATTACHED]: (\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ) => void;\n [Events.MEDIA_DETACHING]: (event: Events.MEDIA_DETACHING) => void;\n [Events.MEDIA_DETACHED]: (event: Events.MEDIA_DETACHED) => void;\n [Events.BUFFER_RESET]: (event: Events.BUFFER_RESET) => void;\n [Events.BUFFER_CODECS]: (\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData,\n ) => void;\n [Events.BUFFER_CREATED]: (\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData,\n ) => void;\n [Events.BUFFER_APPENDING]: (\n event: Events.BUFFER_APPENDING,\n data: BufferAppendingData,\n ) => void;\n [Events.BUFFER_APPENDED]: (\n event: Events.BUFFER_APPENDED,\n data: BufferAppendedData,\n ) => void;\n [Events.BUFFER_EOS]: (event: Events.BUFFER_EOS, data: BufferEOSData) => void;\n [Events.BUFFER_FLUSHING]: (\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData,\n ) => void;\n [Events.BUFFER_FLUSHED]: (\n event: Events.BUFFER_FLUSHED,\n data: BufferFlushedData,\n ) => void;\n [Events.MANIFEST_LOADING]: (\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) => void;\n [Events.MANIFEST_LOADED]: (\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ) => void;\n [Events.MANIFEST_PARSED]: (\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) => void;\n [Events.LEVEL_SWITCHING]: (\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData,\n ) => void;\n [Events.LEVEL_SWITCHED]: (\n event: Events.LEVEL_SWITCHED,\n data: LevelSwitchedData,\n ) => void;\n [Events.LEVEL_LOADING]: (\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData,\n ) => void;\n [Events.LEVEL_LOADED]: (\n event: Events.LEVEL_LOADED,\n data: LevelLoadedData,\n ) => void;\n [Events.LEVEL_UPDATED]: (\n event: Events.LEVEL_UPDATED,\n data: LevelUpdatedData,\n ) => void;\n [Events.LEVEL_PTS_UPDATED]: (\n event: Events.LEVEL_PTS_UPDATED,\n data: LevelPTSUpdatedData,\n ) => void;\n [Events.LEVELS_UPDATED]: (\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData,\n ) => void;\n [Events.AUDIO_TRACKS_UPDATED]: (\n event: Events.AUDIO_TRACKS_UPDATED,\n data: AudioTracksUpdatedData,\n ) => void;\n [Events.AUDIO_TRACK_SWITCHING]: (\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData,\n ) => void;\n [Events.AUDIO_TRACK_SWITCHED]: (\n event: Events.AUDIO_TRACK_SWITCHED,\n data: AudioTrackSwitchedData,\n ) => void;\n [Events.AUDIO_TRACK_LOADING]: (\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData,\n ) => void;\n [Events.AUDIO_TRACK_LOADED]: (\n event: Events.AUDIO_TRACK_LOADED,\n data: AudioTrackLoadedData,\n ) => void;\n [Events.SUBTITLE_TRACKS_UPDATED]: (\n event: Events.SUBTITLE_TRACKS_UPDATED,\n data: SubtitleTracksUpdatedData,\n ) => void;\n [Events.SUBTITLE_TRACKS_CLEARED]: (\n event: Events.SUBTITLE_TRACKS_CLEARED,\n ) => void;\n [Events.SUBTITLE_TRACK_SWITCH]: (\n event: Events.SUBTITLE_TRACK_SWITCH,\n data: SubtitleTrackSwitchData,\n ) => void;\n [Events.SUBTITLE_TRACK_LOADING]: (\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData,\n ) => void;\n [Events.SUBTITLE_TRACK_LOADED]: (\n event: Events.SUBTITLE_TRACK_LOADED,\n data: SubtitleTrackLoadedData,\n ) => void;\n [Events.SUBTITLE_FRAG_PROCESSED]: (\n event: Events.SUBTITLE_FRAG_PROCESSED,\n data: SubtitleFragProcessedData,\n ) => void;\n [Events.CUES_PARSED]: (\n event: Events.CUES_PARSED,\n data: CuesParsedData,\n ) => void;\n [Events.NON_NATIVE_TEXT_TRACKS_FOUND]: (\n event: Events.NON_NATIVE_TEXT_TRACKS_FOUND,\n data: NonNativeTextTracksData,\n ) => void;\n [Events.INIT_PTS_FOUND]: (\n event: Events.INIT_PTS_FOUND,\n data: InitPTSFoundData,\n ) => void;\n [Events.FRAG_LOADING]: (\n event: Events.FRAG_LOADING,\n data: FragLoadingData,\n ) => void;\n // [Events.FRAG_LOAD_PROGRESS]: TodoEventType\n [Events.FRAG_LOAD_EMERGENCY_ABORTED]: (\n event: Events.FRAG_LOAD_EMERGENCY_ABORTED,\n data: FragLoadEmergencyAbortedData,\n ) => void;\n [Events.FRAG_LOADED]: (\n event: Events.FRAG_LOADED,\n data: FragLoadedData,\n ) => void;\n [Events.FRAG_DECRYPTED]: (\n event: Events.FRAG_DECRYPTED,\n data: FragDecryptedData,\n ) => void;\n [Events.FRAG_PARSING_INIT_SEGMENT]: (\n event: Events.FRAG_PARSING_INIT_SEGMENT,\n data: FragParsingInitSegmentData,\n ) => void;\n [Events.FRAG_PARSING_USERDATA]: (\n event: Events.FRAG_PARSING_USERDATA,\n data: FragParsingUserdataData,\n ) => void;\n [Events.FRAG_PARSING_METADATA]: (\n event: Events.FRAG_PARSING_METADATA,\n data: FragParsingMetadataData,\n ) => void;\n // [Events.FRAG_PARSING_DATA]: TodoEventType\n [Events.FRAG_PARSED]: (\n event: Events.FRAG_PARSED,\n data: FragParsedData,\n ) => void;\n [Events.FRAG_BUFFERED]: (\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData,\n ) => void;\n [Events.FRAG_CHANGED]: (\n event: Events.FRAG_CHANGED,\n data: FragChangedData,\n ) => void;\n [Events.FPS_DROP]: (event: Events.FPS_DROP, data: FPSDropData) => void;\n [Events.FPS_DROP_LEVEL_CAPPING]: (\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData,\n ) => void;\n [Events.MAX_AUTO_LEVEL_UPDATED]: (\n event: Events.MAX_AUTO_LEVEL_UPDATED,\n data: MaxAutoLevelUpdatedData,\n ) => void;\n [Events.ERROR]: (event: Events.ERROR, data: ErrorData) => void;\n [Events.DESTROYING]: (event: Events.DESTROYING) => void;\n [Events.KEY_LOADING]: (\n event: Events.KEY_LOADING,\n data: KeyLoadingData,\n ) => void;\n [Events.KEY_LOADED]: (event: Events.KEY_LOADED, data: KeyLoadedData) => void;\n [Events.LIVE_BACK_BUFFER_REACHED]: (\n event: Events.LIVE_BACK_BUFFER_REACHED,\n data: LiveBackBufferData,\n ) => void;\n [Events.BACK_BUFFER_REACHED]: (\n event: Events.BACK_BUFFER_REACHED,\n data: BackBufferData,\n ) => void;\n [Events.STEERING_MANIFEST_LOADED]: (\n event: Events.STEERING_MANIFEST_LOADED,\n data: SteeringManifestLoadedData,\n ) => void;\n}\nexport interface HlsEventEmitter {\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context,\n ): void;\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context,\n ): void;\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E): void;\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E],\n context?: Context,\n once?: boolean,\n ): void;\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][];\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1],\n ): boolean;\n listenerCount<E extends keyof HlsListeners>(event: E): number;\n}\n","export enum ErrorTypes {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR = 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR = 'mediaError',\n // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR = 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR = 'muxError',\n // Identifier for all other errors\n OTHER_ERROR = 'otherError',\n}\n\nexport enum ErrorDetails {\n KEY_SYSTEM_NO_KEYS = 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS = 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION = 'keySystemNoSession',\n KEY_SYSTEM_NO_CONFIGURED_LICENSE = 'keySystemNoConfiguredLicense',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED = 'keySystemLicenseRequestFailed',\n KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED = 'keySystemServerCertificateRequestFailed',\n KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED = 'keySystemServerCertificateUpdateFailed',\n KEY_SYSTEM_SESSION_UPDATE_FAILED = 'keySystemSessionUpdateFailed',\n KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED = 'keySystemStatusOutputRestricted',\n KEY_SYSTEM_STATUS_INTERNAL_ERROR = 'keySystemStatusInternalError',\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR = 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT = 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR = 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR = 'manifestIncompatibleCodecsError',\n // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: \"no fragments found in level\", level: index of the bad level }\n LEVEL_EMPTY_ERROR = 'levelEmptyError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR = 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT = 'levelLoadTimeOut',\n // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }\n LEVEL_PARSING_ERROR = 'levelParsingError',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR = 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR = 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT = 'audioTrackLoadTimeOut',\n // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n SUBTITLE_LOAD_ERROR = 'subtitleTrackLoadError',\n // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n SUBTITLE_TRACK_LOAD_TIMEOUT = 'subtitleTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR = 'fragLoadError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT = 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n FRAG_DECRYPT_ERROR = 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR = 'fragParsingError',\n // Identifier for a fragment or part load skipped because of a GAP tag or attribute\n FRAG_GAP = 'fragGap',\n // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }\n REMUX_ALLOC_ERROR = 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR = 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT = 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR = 'bufferAddCodecError',\n // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }\n BUFFER_INCOMPATIBLE_CODECS_ERROR = 'bufferIncompatibleCodecsError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR = 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR = 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR = 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR = 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE = 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL = 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION = 'internalException',\n // Identifier for an internal call to abort a loader\n INTERNAL_ABORTED = 'aborted',\n // Uncategorized error\n UNKNOWN = 'unknown',\n}\n","export interface ILogFunction {\n (message?: any, ...optionalParams: any[]): void;\n}\n\nexport interface ILogger {\n trace: ILogFunction;\n debug: ILogFunction;\n log: ILogFunction;\n warn: ILogFunction;\n info: ILogFunction;\n error: ILogFunction;\n}\n\nconst noop: ILogFunction = function () {};\n\nconst fakeLogger: ILogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop,\n};\n\nlet exportedLogger: ILogger = fakeLogger;\n\n// let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction consolePrintFn(type: string): ILogFunction {\n const func: ILogFunction = self.console[type];\n if (func) {\n return func.bind(self.console, `[${type}] >`);\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(\n debugConfig: boolean | ILogger,\n ...functions: string[]\n): void {\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type]\n ? debugConfig[type].bind(debugConfig)\n : consolePrintFn(type);\n });\n}\n\nexport function enableLogs(debugConfig: boolean | ILogger, id: string): void {\n // check that console is available\n if (\n (typeof console === 'object' && debugConfig === true) ||\n typeof debugConfig === 'object'\n ) {\n exportLoggerFunctions(\n debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error',\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log(\n `Debug logs enabled for \"${id}\" in hls.js version ${__VERSION__}`,\n );\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n } else {\n exportedLogger = fakeLogger;\n }\n}\n\nexport const logger: ILogger = exportedLogger;\n","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/;\nconst ATTR_LIST_REGEX = /(.+?)=(\".*?\"|.*?)(?:,|$)/g;\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nexport class AttrList {\n [key: string]: any;\n\n constructor(attrs: string | Record<string, any>) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n Object.assign(this, attrs);\n }\n\n get clientAttrs(): string[] {\n return Object.keys(this).filter((attr) => attr.substring(0, 2) === 'X-');\n }\n\n decimalInteger(attrName: string): number {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n hexadecimalInteger(attrName: string) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber(attrName: string): number {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n decimalFloatingPoint(attrName: string): number {\n return parseFloat(this[attrName]);\n }\n\n optionalFloat(attrName: string, defaultValue: number): number {\n const value = this[attrName];\n return value ? parseFloat(value) : defaultValue;\n }\n\n enumeratedString(attrName: string): string | undefined {\n return this[attrName];\n }\n\n bool(attrName: string): boolean {\n return this[attrName] === 'YES';\n }\n\n decimalResolution(attrName: string):\n | {\n width: number;\n height: number;\n }\n | undefined {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10),\n };\n }\n\n static parseAttrList(input: string): Record<string, any> {\n let match;\n const attrs = {};\n const quote = '\"';\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let value = match[2];\n\n if (\n value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === value.length - 1\n ) {\n value = value.slice(1, -1);\n }\n const name = match[1].trim();\n attrs[name] = value;\n }\n return attrs;\n }\n}\n","import { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\n\n// Avoid exporting const enum so that these values can be inlined\nconst enum DateRangeAttribute {\n ID = 'ID',\n CLASS = 'CLASS',\n START_DATE = 'START-DATE',\n DURATION = 'DURATION',\n END_DATE = 'END-DATE',\n END_ON_NEXT = 'END-ON-NEXT',\n PLANNED_DURATION = 'PLANNED-DURATION',\n SCTE35_OUT = 'SCTE35-OUT',\n SCTE35_IN = 'SCTE35-IN',\n}\n\nexport function isDateRangeCueAttribute(attrName: string): boolean {\n return (\n attrName !== DateRangeAttribute.ID &&\n attrName !== DateRangeAttribute.CLASS &&\n attrName !== DateRangeAttribute.START_DATE &&\n attrName !== DateRangeAttribute.DURATION &&\n attrName !== DateRangeAttribute.END_DATE &&\n attrName !== DateRangeAttribute.END_ON_NEXT\n );\n}\n\nexport function isSCTE35Attribute(attrName: string): boolean {\n return (\n attrName === DateRangeAttribute.SCTE35_OUT ||\n attrName === DateRangeAttribute.SCTE35_IN\n );\n}\n\nexport class DateRange {\n public attr: AttrList;\n private _startDate: Date;\n private _endDate?: Date;\n private _badValueForSameId?: string;\n\n constructor(dateRangeAttr: AttrList, dateRangeWithSameId?: DateRange) {\n if (dateRangeWithSameId) {\n const previousAttr = dateRangeWithSameId.attr;\n for (const key in previousAttr) {\n if (\n Object.prototype.hasOwnProperty.call(dateRangeAttr, key) &&\n dateRangeAttr[key] !== previousAttr[key]\n ) {\n logger.warn(\n `DATERANGE tag attribute: \"${key}\" does not match for tags with ID: \"${dateRangeAttr.ID}\"`,\n );\n this._badValueForSameId = key;\n break;\n }\n }\n // Merge DateRange tags with the same ID\n dateRangeAttr = Object.assign(\n new AttrList({}),\n previousAttr,\n dateRangeAttr,\n );\n }\n this.attr = dateRangeAttr;\n this._startDate = new Date(dateRangeAttr[DateRangeAttribute.START_DATE]);\n if (DateRangeAttribute.END_DATE in this.attr) {\n const endDate = new Date(this.attr[DateRangeAttribute.END_DATE]);\n if (Number.isFinite(endDate.getTime())) {\n this._endDate = endDate;\n }\n }\n }\n\n get id(): string {\n return this.attr.ID;\n }\n\n get class(): string {\n return this.attr.CLASS;\n }\n\n get startDate(): Date {\n return this._startDate;\n }\n\n get endDate(): Date | null {\n if (this._endDate) {\n return this._endDate;\n }\n const duration = this.duration;\n if (duration !== null) {\n return new Date(this._startDate.getTime() + duration * 1000);\n }\n return null;\n }\n\n get duration(): number | null {\n if (DateRangeAttribute.DURATION in this.attr) {\n const duration = this.attr.decimalFloatingPoint(\n DateRangeAttribute.DURATION,\n );\n if (Number.isFinite(duration)) {\n return duration;\n }\n } else if (this._endDate) {\n return (this._endDate.getTime() - this._startDate.getTime()) / 1000;\n }\n return null;\n }\n\n get plannedDuration(): number | null {\n if (DateRangeAttribute.PLANNED_DURATION in this.attr) {\n return this.attr.decimalFloatingPoint(\n DateRangeAttribute.PLANNED_DURATION,\n );\n }\n return null;\n }\n\n get endOnNext(): boolean {\n return this.attr.bool(DateRangeAttribute.END_ON_NEXT);\n }\n\n get isValid(): boolean {\n return (\n !!this.id &&\n !this._badValueForSameId &&\n Number.isFinite(this.startDate.getTime()) &&\n (this.duration === null || this.duration >= 0) &&\n (!this.endOnNext || !!this.class)\n );\n }\n}\n","import type {\n HlsPerformanceTiming,\n HlsProgressivePerformanceTiming,\n LoaderStats,\n} from '../types/loader';\n\nexport class LoadStats implements LoaderStats {\n aborted: boolean = false;\n loaded: number = 0;\n retry: number = 0;\n total: number = 0;\n chunkCount: number = 0;\n bwEstimate: number = 0;\n loading: HlsProgressivePerformanceTiming = { start: 0, first: 0, end: 0 };\n parsing: HlsPerformanceTiming = { start: 0, end: 0 };\n buffering: HlsProgressivePerformanceTiming = { start: 0, first: 0, end: 0 };\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport { LevelKey } from './level-key';\nimport { LoadStats } from './load-stats';\nimport { AttrList } from '../utils/attr-list';\nimport type {\n FragmentLoaderContext,\n KeyLoaderContext,\n Loader,\n PlaylistLevelType,\n} from '../types/loader';\nimport type { KeySystemFormats } from '../utils/mediakeys-helper';\n\nexport const enum ElementaryStreamTypes {\n AUDIO = 'audio',\n VIDEO = 'video',\n AUDIOVIDEO = 'audiovideo',\n}\n\nexport interface ElementaryStreamInfo {\n startPTS: number;\n endPTS: number;\n startDTS: number;\n endDTS: number;\n partial?: boolean;\n}\n\nexport type ElementaryStreams = Record<\n ElementaryStreamTypes,\n ElementaryStreamInfo | null\n>;\n\nexport class BaseSegment {\n private _byteRange: [number, number] | null = null;\n private _url: string | null = null;\n\n // baseurl is the URL to the playlist\n public readonly baseurl: string;\n // relurl is the portion of the URL that comes from inside the playlist.\n public relurl?: string;\n // Holds the types of data this fragment supports\n public elementaryStreams: ElementaryStreams = {\n [ElementaryStreamTypes.AUDIO]: null,\n [ElementaryStreamTypes.VIDEO]: null,\n [ElementaryStreamTypes.AUDIOVIDEO]: null,\n };\n\n constructor(baseurl: string) {\n this.baseurl = baseurl;\n }\n\n // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n setByteRange(value: string, previous?: BaseSegment) {\n const params = value.split('@', 2);\n let start: number;\n if (params.length === 1) {\n start = previous?.byteRangeEndOffset || 0;\n } else {\n start = parseInt(params[1]);\n }\n this._byteRange = [start, parseInt(params[0]) + start];\n }\n\n get byteRange(): [number, number] | [] {\n if (!this._byteRange) {\n return [];\n }\n\n return this._byteRange;\n }\n\n get byteRangeStartOffset(): number | undefined {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset(): number | undefined {\n return this.byteRange[1];\n }\n\n get url(): string {\n if (!this._url && this.baseurl && this.relurl) {\n this._url = buildAbsoluteURL(this.baseurl, this.relurl, {\n alwaysNormalize: true,\n });\n }\n return this._url || '';\n }\n\n set url(value: string) {\n this._url = value;\n }\n}\n\n/**\n * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.\n */\nexport class Fragment extends BaseSegment {\n private _decryptdata: LevelKey | null = null;\n\n public rawProgramDateTime: string | null = null;\n public programDateTime: number | null = null;\n public tagList: Array<string[]> = [];\n\n // EXTINF has to be present for a m3u8 to be considered valid\n public duration: number = 0;\n // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'\n public sn: number | 'initSegment' = 0;\n // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption\n // core difference from the private field _decryptdata is the lack of the initialized IV\n // _decryptdata will set the IV for this segment based on the segment number in the fragment\n public levelkeys?: { [key: string]: LevelKey };\n // A string representing the fragment type\n public readonly type: PlaylistLevelType;\n // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading\n public loader: Loader<FragmentLoaderContext> | null = null;\n // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading\n public keyLoader: Loader<KeyLoaderContext> | null = null;\n // The level/track index to which the fragment belongs\n public level: number = -1;\n // The continuity counter of the fragment\n public cc: number = 0;\n // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n public startPTS?: number;\n // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n public endPTS?: number;\n // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public startDTS!: number;\n // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public endDTS!: number;\n // The start time of the fragment, as listed in the manifest. Updated after transmux complete.\n public start: number = 0;\n // Set by `updateFragPTSDTS` in level-helper\n public deltaPTS?: number;\n // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public maxStartPTS?: number;\n // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public minEndPTS?: number;\n // Load/parse timing information\n public stats: LoadStats = new LoadStats();\n // Init Segment bytes (unset for media segments)\n public data?: Uint8Array;\n // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered\n public bitrateTest: boolean = false;\n // #EXTINF segment title\n public title: string | null = null;\n // The Media Initialization Section for this segment\n public initSegment: Fragment | null = null;\n // Fragment is the last fragment in the media playlist\n public endList?: boolean;\n // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded\n public gap?: boolean;\n // Deprecated\n public urlId: number = 0;\n\n constructor(type: PlaylistLevelType, baseurl: string) {\n super(baseurl);\n this.type = type;\n }\n\n get decryptdata(): LevelKey | null {\n const { levelkeys } = this;\n if (!levelkeys && !this._decryptdata) {\n return null;\n }\n\n if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {\n const key = this.levelkeys.identity;\n if (key) {\n this._decryptdata = key.getDecryptData(this.sn);\n } else {\n const keyFormats = Object.keys(this.levelkeys);\n if (keyFormats.length === 1) {\n return (this._decryptdata = this.levelkeys[\n keyFormats[0]\n ].getDecryptData(this.sn));\n } else {\n // Multiple keys. key-loader to call Fragment.setKeyFormat based on selected key-system.\n }\n }\n }\n\n return this._decryptdata;\n }\n\n get end(): number {\n return this.start + this.duration;\n }\n\n get endProgramDateTime() {\n if (this.programDateTime === null) {\n return null;\n }\n\n if (!Number.isFinite(this.programDateTime)) {\n return null;\n }\n\n const duration = !Number.isFinite(this.duration) ? 0 : this.duration;\n\n return this.programDateTime + duration * 1000;\n }\n\n get encrypted() {\n // At the m3u8-parser level we need to add support for manifest signalled keyformats\n // when we want the fragment to start reporting that it is encrypted.\n // Currently, keyFormat will only be set for identity keys\n if (this._decryptdata?.encrypted) {\n return true;\n } else if (this.levelkeys) {\n const keyFormats = Object.keys(this.levelkeys);\n const len = keyFormats.length;\n if (len > 1 || (len === 1 && this.levelkeys[keyFormats[0]].encrypted)) {\n return true;\n }\n }\n\n return false;\n }\n\n setKeyFormat(keyFormat: KeySystemFormats) {\n if (this.levelkeys) {\n const key = this.levelkeys[keyFormat];\n if (key && !this._decryptdata) {\n this._decryptdata = key.getDecryptData(this.sn);\n }\n }\n }\n\n abortRequests(): void {\n this.loader?.abort();\n this.keyLoader?.abort();\n }\n\n setElementaryStreamInfo(\n type: ElementaryStreamTypes,\n startPTS: number,\n endPTS: number,\n startDTS: number,\n endDTS: number,\n partial: boolean = false,\n ) {\n const { elementaryStreams } = this;\n const info = elementaryStreams[type];\n if (!info) {\n elementaryStreams[type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n partial,\n };\n return;\n }\n\n info.startPTS = Math.min(info.startPTS, startPTS);\n info.endPTS = Math.max(info.endPTS, endPTS);\n info.startDTS = Math.min(info.startDTS, startDTS);\n info.endDTS = Math.max(info.endDTS, endDTS);\n }\n\n clearElementaryStreamInfo() {\n const { elementaryStreams } = this;\n elementaryStreams[ElementaryStreamTypes.AUDIO] = null;\n elementaryStreams[ElementaryStreamTypes.VIDEO] = null;\n elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;\n }\n}\n\n/**\n * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.\n */\nexport class Part extends BaseSegment {\n public readonly fragOffset: number = 0;\n public readonly duration: number = 0;\n public readonly gap: boolean = false;\n public readonly independent: boolean = false;\n public readonly relurl: string;\n public readonly fragment: Fragment;\n public readonly index: number;\n public stats: LoadStats = new LoadStats();\n\n constructor(\n partAttrs: AttrList,\n frag: Fragment,\n baseurl: string,\n index: number,\n previous?: Part,\n ) {\n super(baseurl);\n this.duration = partAttrs.decimalFloatingPoint('DURATION');\n this.gap = partAttrs.bool('GAP');\n this.independent = partAttrs.bool('INDEPENDENT');\n this.relurl = partAttrs.enumeratedString('URI') as string;\n this.fragment = frag;\n this.index = index;\n const byteRange = partAttrs.enumeratedString('BYTERANGE');\n if (byteRange) {\n this.setByteRange(byteRange, previous);\n }\n if (previous) {\n this.fragOffset = previous.fragOffset + previous.duration;\n }\n }\n\n get start(): number {\n return this.fragment.start + this.fragOffset;\n }\n\n get end(): number {\n return this.start + this.duration;\n }\n\n get loaded(): boolean {\n const { elementaryStreams } = this;\n return !!(\n elementaryStreams.audio ||\n elementaryStreams.video ||\n elementaryStreams.audiovideo\n );\n }\n}\n","import { Part } from './fragment';\nimport type { Fragment } from './fragment';\nimport type { AttrList } from '../utils/attr-list';\nimport type { DateRange } from './date-range';\nimport type { VariableMap } from '../types/level';\n\nconst DEFAULT_TARGET_DURATION = 10;\n\n/**\n * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.\n */\nexport class LevelDetails {\n public PTSKnown: boolean = false;\n public alignedSliding: boolean = false;\n public averagetargetduration?: number;\n public endCC: number = 0;\n public endSN: number = 0;\n public fragments: Fragment[];\n public fragmentHint?: Fragment;\n public partList: Part[] | null = null;\n public dateRanges: Record<string, DateRange>;\n public live: boolean = true;\n public ageHeader: number = 0;\n public advancedDateTime?: number;\n public updated: boolean = true;\n public advanced: boolean = true;\n public availabilityDelay?: number; // Manifest reload synchronization\n public misses: number = 0;\n public startCC: number = 0;\n public startSN: number = 0;\n public startTimeOffset: number | null = null;\n public targetduration: number = 0;\n public totalduration: number = 0;\n public type: string | null = null;\n public url: string;\n public m3u8: string = '';\n public version: number | null = null;\n public canBlockReload: boolean = false;\n public canSkipUntil: number = 0;\n public canSkipDateRanges: boolean = false;\n public skippedSegments: number = 0;\n public recentlyRemovedDateranges?: string[];\n public partHoldBack: number = 0;\n public holdBack: number = 0;\n public partTarget: number = 0;\n public preloadHint?: AttrList;\n public renditionReports?: AttrList[];\n public tuneInGoal: number = 0;\n public deltaUpdateFailed?: boolean;\n public driftStartTime: number = 0;\n public driftEndTime: number = 0;\n public driftStart: number = 0;\n public driftEnd: number = 0;\n public encryptedFragments: Fragment[];\n public playlistParsingError: Error | null = null;\n public variableList: VariableMap | null = null;\n public hasVariableRefs = false;\n\n constructor(baseUrl: string) {\n this.fragments = [];\n this.encryptedFragments = [];\n this.dateRanges = {};\n this.url = baseUrl;\n }\n\n reloaded(previous: LevelDetails | undefined) {\n if (!previous) {\n this.advanced = true;\n this.updated = true;\n return;\n }\n const partSnDiff = this.lastPartSn - previous.lastPartSn;\n const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;\n this.updated =\n this.endSN !== previous.endSN ||\n !!partIndexDiff ||\n !!partSnDiff ||\n !this.live;\n this.advanced =\n this.endSN > previous.endSN ||\n partSnDiff > 0 ||\n (partSnDiff === 0 && partIndexDiff > 0);\n if (this.updated || this.advanced) {\n this.misses = Math.floor(previous.misses * 0.6);\n } else {\n this.misses = previous.misses + 1;\n }\n this.availabilityDelay = previous.availabilityDelay;\n }\n\n get hasProgramDateTime(): boolean {\n if (this.fragments.length) {\n return Number.isFinite(\n this.fragments[this.fragments.length - 1].programDateTime as number,\n );\n }\n return false;\n }\n\n get levelTargetDuration(): number {\n return (\n this.averagetargetduration ||\n this.targetduration ||\n DEFAULT_TARGET_DURATION\n );\n }\n\n get drift(): number {\n const runTime = this.driftEndTime - this.driftStartTime;\n if (runTime > 0) {\n const runDuration = this.driftEnd - this.driftStart;\n return (runDuration * 1000) / runTime;\n }\n return 1;\n }\n\n get edge(): number {\n return this.partEnd || this.fragmentEnd;\n }\n\n get partEnd(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].end;\n }\n return this.fragmentEnd;\n }\n\n get fragmentEnd(): number {\n if (this.fragments?.length) {\n return this.fragments[this.fragments.length - 1].end;\n }\n return 0;\n }\n\n get age(): number {\n if (this.advancedDateTime) {\n return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;\n }\n return 0;\n }\n\n get lastPartIndex(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].index;\n }\n return -1;\n }\n\n get lastPartSn(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].fragment.sn as number;\n }\n return this.endSN;\n }\n}\n","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","/** returns `undefined` is `self` is missing, e.g. in node */\nexport const optionalSelf = typeof self !== 'undefined' ? self : undefined;\n","import type { DRMSystemOptions, EMEControllerConfig } from '../config';\nimport { optionalSelf } from './global';\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 (\n systemId === KeySystemIds.CENC ||\n systemId === KeySystemIds.CLEARKEY\n ) {\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 (optionalSelf?.navigator?.requestMediaKeySystemAccess) {\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 || 'optional',\n distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || 'optional',\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 { KeySystemIds } from './mediakeys-helper';\nimport type { PassthroughTrack, UserdataSample } from '../types/demuxer';\nimport type { DecryptData } from '../loader/level-key';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\nconst push = [].push;\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nexport const RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4,\n};\n\nexport function bin2str(data: Uint8Array): string {\n return String.fromCharCode.apply(null, data);\n}\n\nexport function readUint16(buffer: Uint8Array, offset: number): number {\n const val = (buffer[offset] << 8) | buffer[offset + 1];\n return val < 0 ? 65536 + val : val;\n}\n\nexport function readUint32(buffer: Uint8Array, offset: number): number {\n const val = readSint32(buffer, offset);\n return val < 0 ? 4294967296 + val : val;\n}\n\nexport function readUint64(buffer: Uint8Array, offset: number) {\n let result = readUint32(buffer, offset);\n result *= Math.pow(2, 32);\n result += readUint32(buffer, offset + 4);\n return result;\n}\n\nexport function readSint32(buffer: Uint8Array, offset: number): number {\n return (\n (buffer[offset] << 24) |\n (buffer[offset + 1] << 16) |\n (buffer[offset + 2] << 8) |\n buffer[offset + 3]\n );\n}\n\nexport function writeUint32(buffer: Uint8Array, offset: number, value: number) {\n buffer[offset] = value >> 24;\n buffer[offset + 1] = (value >> 16) & 0xff;\n buffer[offset + 2] = (value >> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n}\n\n// Find \"moof\" box\nexport function hasMoofData(data: Uint8Array): boolean {\n const end = data.byteLength;\n for (let i = 0; i < end; ) {\n const size = readUint32(data, i);\n if (\n size > 8 &&\n data[i + 4] === 0x6d &&\n data[i + 5] === 0x6f &&\n data[i + 6] === 0x6f &&\n data[i + 7] === 0x66\n ) {\n return true;\n }\n i = size > 1 ? i + size : end;\n }\n return false;\n}\n\n// Find the data for a box specified by its path\nexport function findBox(data: Uint8Array, path: string[]): Uint8Array[] {\n const results = [] as Uint8Array[];\n if (!path.length) {\n // short-circuit the search for empty paths\n return results;\n }\n const end = data.byteLength;\n\n for (let i = 0; i < end; ) {\n const size = readUint32(data, i);\n const type = bin2str(data.subarray(i + 4, i + 8));\n const endbox = size > 1 ? i + size : end;\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push(data.subarray(i + 8, endbox));\n } else {\n // recursively search for the next box along the path\n const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));\n if (subresults.length) {\n push.apply(results, subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n}\n\ntype SidxInfo = {\n earliestPresentationTime: number;\n timescale: number;\n version: number;\n referencesCount: number;\n references: any[];\n};\n\nexport function parseSegmentIndex(sidx: Uint8Array): SidxInfo | null {\n const references: any[] = [];\n\n const version = sidx[0];\n\n // set initial offset, we skip the reference ID (not needed)\n let index = 8;\n\n const timescale = readUint32(sidx, index);\n index += 4;\n\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n earliestPresentationTime = readUint32(sidx, index);\n firstOffset = readUint32(sidx, index + 4);\n index += 8;\n } else {\n earliestPresentationTime = readUint64(sidx, index);\n firstOffset = readUint64(sidx, index + 8);\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.length + firstOffset;\n\n const referencesCount = readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7fffffff;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n logger.warn('SIDX has hierarchical references (not supported)');\n return null;\n }\n\n const subsegmentDuration = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1,\n },\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n };\n}\n\n/**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param initSegment the bytes of the init segment\n * @returns a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n\nexport interface InitDataTrack {\n timescale: number;\n id: number;\n codec: string;\n}\n\ntype HdlrType = ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO;\n\nexport interface InitData extends Array<any> {\n [index: number]:\n | {\n timescale: number;\n type: HdlrType;\n default?: {\n duration: number;\n flags: number;\n };\n }\n | undefined;\n audio?: InitDataTrack;\n video?: InitDataTrack;\n caption?: InitDataTrack;\n}\n\nexport function parseInitSegment(initSegment: Uint8Array): InitData {\n const result: InitData = [];\n const traks = findBox(initSegment, ['moov', 'trak']);\n for (let i = 0; i < traks.length; i++) {\n const trak = traks[i];\n const tkhd = findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd[0];\n const trackId = readUint32(tkhd, version === 0 ? 12 : 20);\n const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd[0];\n const timescale = readUint32(mdhd, version === 0 ? 12 : 20);\n const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = bin2str(hdlr.subarray(8, 12));\n const type: HdlrType | undefined = {\n soun: ElementaryStreamTypes.AUDIO as const,\n vide: ElementaryStreamTypes.VIDEO as const,\n }[hdlrType];\n if (type) {\n // Parse codec details\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n const stsdData = parseStsd(stsd);\n result[trackId] = { timescale, type };\n result[type] = { timescale, id: trackId, ...stsdData };\n }\n }\n }\n }\n }\n\n const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);\n trex.forEach((trex) => {\n const trackId = readUint32(trex, 4);\n const track = result[trackId];\n if (track) {\n track.default = {\n duration: readUint32(trex, 12),\n flags: readUint32(trex, 20),\n };\n }\n });\n\n return result;\n}\n\nfunction parseStsd(stsd: Uint8Array): { codec: string; encrypted: boolean } {\n const sampleEntries = stsd.subarray(8);\n const sampleEntriesEnd = sampleEntries.subarray(8 + 78);\n const fourCC = bin2str(sampleEntries.subarray(4, 8));\n let codec = fourCC;\n const encrypted = fourCC === 'enca' || fourCC === 'encv';\n if (encrypted) {\n const encBox = findBox(sampleEntries, [fourCC])[0];\n const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);\n const sinfs = findBox(encBoxChildren, ['sinf']);\n sinfs.forEach((sinf) => {\n const schm = findBox(sinf, ['schm'])[0];\n if (schm) {\n const scheme = bin2str(schm.subarray(4, 8));\n if (scheme === 'cbcs' || scheme === 'cenc') {\n const frma = findBox(sinf, ['frma'])[0];\n if (frma) {\n // for encrypted content codec fourCC will be in frma\n codec = bin2str(frma);\n }\n }\n }\n });\n }\n switch (codec) {\n case 'avc1':\n case 'avc2':\n case 'avc3':\n case 'avc4': {\n // extract profile + compatibility + level out of avcC box\n const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];\n codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);\n break;\n }\n case 'mp4a': {\n const codecBox = findBox(sampleEntries, [fourCC])[0];\n const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];\n if (esdsBox && esdsBox.length > 12) {\n let i = 4;\n // ES Descriptor tag\n if (esdsBox[i++] !== 0x03) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n i += 2; // skip es_id;\n const flags = esdsBox[i++];\n if (flags & 0x80) {\n i += 2; // skip dependency es_id\n }\n if (flags & 0x40) {\n i += esdsBox[i++]; // skip URL\n }\n // Decoder config descriptor\n if (esdsBox[i++] !== 0x04) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n const objectType = esdsBox[i++];\n if (objectType === 0x40) {\n codec += '.' + toHex(objectType);\n } else {\n break;\n }\n i += 12;\n // Decoder specific info\n if (esdsBox[i++] !== 0x05) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n const firstByte = esdsBox[i++];\n let audioObjectType = (firstByte & 0xf8) >> 3;\n if (audioObjectType === 31) {\n audioObjectType +=\n 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);\n }\n codec += '.' + audioObjectType;\n }\n break;\n }\n case 'hvc1':\n case 'hev1': {\n const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];\n const profileByte = hvcCBox[1];\n const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];\n const generalProfileIdc = profileByte & 0x1f;\n const profileCompat = readUint32(hvcCBox, 2);\n const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';\n const levelIDC = hvcCBox[12];\n const constraintIndicator = hvcCBox.subarray(6, 12);\n codec += '.' + profileSpace + generalProfileIdc;\n codec += '.' + profileCompat.toString(16).toUpperCase();\n codec += '.' + tierFlag + levelIDC;\n let constraintString = '';\n for (let i = constraintIndicator.length; i--; ) {\n const byte = constraintIndicator[i];\n if (byte || constraintString) {\n const encodedByte = byte.toString(16).toUpperCase();\n constraintString = '.' + encodedByte + constraintString;\n }\n }\n codec += constraintString;\n break;\n }\n case 'dvh1':\n case 'dvhe': {\n const dvcCBox = findBox(sampleEntriesEnd, ['dvcC'])[0];\n const profile = (dvcCBox[2] >> 1) & 0x7f;\n const level = ((dvcCBox[2] << 5) & 0x20) | ((dvcCBox[3] >> 3) & 0x1f);\n codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level);\n break;\n }\n case 'vp09': {\n const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];\n const profile = vpcCBox[4];\n const level = vpcCBox[5];\n const bitDepth = (vpcCBox[6] >> 4) & 0x0f;\n codec +=\n '.' +\n addLeadingZero(profile) +\n '.' +\n addLeadingZero(level) +\n '.' +\n addLeadingZero(bitDepth);\n break;\n }\n case 'av01': {\n const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];\n const profile = av1CBox[1] >>> 5;\n const level = av1CBox[1] & 0x1f;\n const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';\n const highBitDepth = (av1CBox[2] & 0x40) >> 6;\n const twelveBit = (av1CBox[2] & 0x20) >> 5;\n const bitDepth =\n profile === 2 && highBitDepth\n ? twelveBit\n ? 12\n : 10\n : highBitDepth\n ? 10\n : 8;\n const monochrome = (av1CBox[2] & 0x10) >> 4;\n const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;\n const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;\n const chromaSamplePosition = av1CBox[2] & 0x03;\n // TODO: parse color_description_present_flag\n // default it to BT.709/limited range for now\n // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax\n const colorPrimaries = 1;\n const transferCharacteristics = 1;\n const matrixCoefficients = 1;\n const videoFullRangeFlag = 0;\n codec +=\n '.' +\n profile +\n '.' +\n addLeadingZero(level) +\n tierFlag +\n '.' +\n addLeadingZero(bitDepth) +\n '.' +\n monochrome +\n '.' +\n chromaSubsamplingX +\n chromaSubsamplingY +\n chromaSamplePosition +\n '.' +\n addLeadingZero(colorPrimaries) +\n '.' +\n addLeadingZero(transferCharacteristics) +\n '.' +\n addLeadingZero(matrixCoefficients) +\n '.' +\n videoFullRangeFlag;\n break;\n }\n case 'ac-3':\n case 'ec-3':\n case 'alac':\n case 'fLaC':\n case 'Opus':\n default:\n break;\n }\n return { codec, encrypted };\n}\n\nfunction skipBERInteger(bytes: Uint8Array, i: number): number {\n const limit = i + 5;\n while (bytes[i++] & 0x80 && i < limit) {}\n return i;\n}\n\nfunction toHex(x: number): string {\n return ('0' + x.toString(16).toUpperCase()).slice(-2);\n}\n\nfunction addLeadingZero(num: number): string {\n return (num < 10 ? '0' : '') + num;\n}\n\nexport function patchEncyptionData(\n initSegment: Uint8Array | undefined,\n decryptdata: DecryptData | null,\n): Uint8Array | undefined {\n if (!initSegment || !decryptdata) {\n return initSegment;\n }\n const keyId = decryptdata.keyId;\n if (keyId && decryptdata.isCommonEncryption) {\n const traks = findBox(initSegment, ['moov', 'trak']);\n traks.forEach((trak) => {\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n\n // skip the sample entry count\n const sampleEntries = stsd.subarray(8);\n let encBoxes = findBox(sampleEntries, ['enca']);\n const isAudio = encBoxes.length > 0;\n if (!isAudio) {\n encBoxes = findBox(sampleEntries, ['encv']);\n }\n encBoxes.forEach((enc) => {\n const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);\n const sinfBoxes = findBox(encBoxChildren, ['sinf']);\n sinfBoxes.forEach((sinf) => {\n const tenc = parseSinf(sinf);\n if (tenc) {\n // Look for default key id (keyID offset is always 8 within the tenc box):\n const tencKeyId = tenc.subarray(8, 24);\n if (!tencKeyId.some((b) => b !== 0)) {\n logger.log(\n `[eme] Patching keyId in 'enc${\n isAudio ? 'a' : 'v'\n }>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(\n keyId,\n )}`,\n );\n tenc.set(keyId, 8);\n }\n }\n });\n });\n });\n }\n\n return initSegment;\n}\n\nexport function parseSinf(sinf: Uint8Array): Uint8Array | null {\n const schm = findBox(sinf, ['schm'])[0];\n if (schm) {\n const scheme = bin2str(schm.subarray(4, 8));\n if (scheme === 'cbcs' || scheme === 'cenc') {\n return findBox(sinf, ['schi', 'tenc'])[0];\n }\n }\n return null;\n}\n\n/**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param initData - a hash of track type to timescale values\n * @param fmp4 - the bytes of the mp4 fragment\n * @returns the earliest base media decode start time for the\n * fragment, in seconds\n */\nexport function getStartDTS(\n initData: InitData,\n fmp4: Uint8Array,\n): number | null {\n // we need info from two children of each track fragment box\n return findBox(fmp4, ['moof', 'traf']).reduce(\n (result: number | null, traf) => {\n const tfdt = findBox(traf, ['tfdt'])[0];\n const version = tfdt[0];\n const start = findBox(traf, ['tfhd']).reduce(\n (result: number | null, tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (track) {\n let baseTime = readUint32(tfdt, 4);\n if (version === 1) {\n // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.\n // This prevents large values from being used for initPTS, which can cause playlist sync issues.\n // https://github.com/video-dev/hls.js/issues/5303\n if (baseTime === UINT32_MAX) {\n logger.warn(\n `[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`,\n );\n return result;\n }\n baseTime *= UINT32_MAX + 1;\n baseTime += readUint32(tfdt, 8);\n }\n // assume a 90kHz clock if no timescale was specified\n const scale = track.timescale || 90e3;\n // convert base time to seconds\n const startTime = baseTime / scale;\n if (\n Number.isFinite(startTime) &&\n (result === null || startTime < result)\n ) {\n return startTime;\n }\n }\n return result;\n },\n null,\n );\n if (\n start !== null &&\n Number.isFinite(start) &&\n (result === null || start < result)\n ) {\n return start;\n }\n return result;\n },\n null,\n );\n}\n\n/*\n For Reference:\n aligned(8) class TrackFragmentHeaderBox\n extends FullBox(tfhd, 0, tf_flags){\n unsigned int(32) track_ID;\n // all the following are optional fields\n unsigned int(64) base_data_offset;\n unsigned int(32) sample_description_index;\n unsigned int(32) default_sample_duration;\n unsigned int(32) default_sample_size;\n unsigned int(32) default_sample_flags\n }\n */\nexport function getDuration(data: Uint8Array, initData: InitData) {\n let rawDuration = 0;\n let videoDuration = 0;\n let audioDuration = 0;\n const trafs = findBox(data, ['moof', 'traf']);\n for (let i = 0; i < trafs.length; i++) {\n const traf = trafs[i];\n // There is only one tfhd & trun per traf\n // This is true for CMAF style content, and we should perhaps check the ftyp\n // and only look for a single trun then, but for ISOBMFF we should check\n // for multiple track runs.\n const tfhd = findBox(traf, ['tfhd'])[0];\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n continue;\n }\n const trackDefault = track.default;\n const tfhdFlags = readUint32(tfhd, 0) | trackDefault?.flags!;\n let sampleDuration: number | undefined = trackDefault?.duration;\n if (tfhdFlags & 0x000008) {\n // 0x000008 indicates the presence of the default_sample_duration field\n if (tfhdFlags & 0x000002) {\n // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration\n // If present, the default_sample_duration exists at byte offset 12\n sampleDuration = readUint32(tfhd, 12);\n } else {\n // Otherwise, the duration is at byte offset 8\n sampleDuration = readUint32(tfhd, 8);\n }\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n const truns = findBox(traf, ['trun']);\n for (let j = 0; j < truns.length; j++) {\n rawDuration = computeRawDurationFromSamples(truns[j]);\n if (!rawDuration && sampleDuration) {\n const sampleCount = readUint32(truns[j], 4);\n rawDuration = sampleDuration * sampleCount;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n videoDuration += rawDuration / timescale;\n } else if (track.type === ElementaryStreamTypes.AUDIO) {\n audioDuration += rawDuration / timescale;\n }\n }\n }\n if (videoDuration === 0 && audioDuration === 0) {\n // If duration samples are not available in the traf use sidx subsegment_duration\n let sidxMinStart = Infinity;\n let sidxMaxEnd = 0;\n let sidxDuration = 0;\n const sidxs = findBox(data, ['sidx']);\n for (let i = 0; i < sidxs.length; i++) {\n const sidx = parseSegmentIndex(sidxs[i]);\n if (sidx?.references) {\n sidxMinStart = Math.min(\n sidxMinStart,\n sidx.earliestPresentationTime / sidx.timescale,\n );\n const subSegmentDuration = sidx.references.reduce(\n (dur, ref) => dur + ref.info.duration || 0,\n 0,\n );\n sidxMaxEnd = Math.max(\n sidxMaxEnd,\n subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale,\n );\n sidxDuration = sidxMaxEnd - sidxMinStart;\n }\n }\n if (sidxDuration && Number.isFinite(sidxDuration)) {\n return sidxDuration;\n }\n }\n if (videoDuration) {\n return videoDuration;\n }\n return audioDuration;\n}\n\n/*\n For Reference:\n aligned(8) class TrackRunBox\n extends FullBox(trun, version, tr_flags) {\n unsigned int(32) sample_count;\n // the following are optional fields\n signed int(32) data_offset;\n unsigned int(32) first_sample_flags;\n // all fields in the following array are optional\n {\n unsigned int(32) sample_duration;\n unsigned int(32) sample_size;\n unsigned int(32) sample_flags\n if (version == 0)\n { unsigned int(32)\n else\n { signed int(32)\n }[ sample_count ]\n }\n */\nexport function computeRawDurationFromSamples(trun): number {\n const flags = readUint32(trun, 0);\n // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.\n // Each field is an int32, which is 4 bytes\n let offset = 8;\n // data-offset-present flag\n if (flags & 0x000001) {\n offset += 4;\n }\n // first-sample-flags-present flag\n if (flags & 0x000004) {\n offset += 4;\n }\n\n let duration = 0;\n const sampleCount = readUint32(trun, 4);\n for (let i = 0; i < sampleCount; i++) {\n // sample-duration-present flag\n if (flags & 0x000100) {\n const sampleDuration = readUint32(trun, offset);\n duration += sampleDuration;\n offset += 4;\n }\n // sample-size-present flag\n if (flags & 0x000200) {\n offset += 4;\n }\n // sample-flags-present flag\n if (flags & 0x000400) {\n offset += 4;\n }\n // sample-composition-time-offsets-present flag\n if (flags & 0x000800) {\n offset += 4;\n }\n }\n return duration;\n}\n\nexport function offsetStartDTS(\n initData: InitData,\n fmp4: Uint8Array,\n timeOffset: number,\n) {\n findBox(fmp4, ['moof', 'traf']).forEach((traf) => {\n findBox(traf, ['tfhd']).forEach((tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n return;\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n // get the base media decode time from the tfdt\n findBox(traf, ['tfdt']).forEach((tfdt) => {\n const version = tfdt[0];\n const offset = timeOffset * timescale;\n if (offset) {\n let baseMediaDecodeTime = readUint32(tfdt, 4);\n if (version === 0) {\n baseMediaDecodeTime -= offset;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n writeUint32(tfdt, 4, baseMediaDecodeTime);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += readUint32(tfdt, 8);\n baseMediaDecodeTime -= offset;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n writeUint32(tfdt, 4, upper);\n writeUint32(tfdt, 8, lower);\n }\n }\n });\n });\n });\n}\n\n// TODO: Check if the last moof+mdat pair is part of the valid range\nexport function segmentValidRange(data: Uint8Array): SegmentedRange {\n const segmentedRange: SegmentedRange = {\n valid: null,\n remainder: null,\n };\n\n const moofs = findBox(data, ['moof']);\n if (moofs.length < 2) {\n segmentedRange.remainder = data;\n return segmentedRange;\n }\n const last = moofs[moofs.length - 1];\n // Offset by 8 bytes; findBox offsets the start by as much\n segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);\n segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);\n return segmentedRange;\n}\n\nexport interface SegmentedRange {\n valid: Uint8Array | null;\n remainder: Uint8Array | null;\n}\n\nexport function appendUint8Array(\n data1: Uint8Array,\n data2: Uint8Array,\n): Uint8Array {\n const temp = new Uint8Array(data1.length + data2.length);\n temp.set(data1);\n temp.set(data2, data1.length);\n\n return temp;\n}\n\nexport interface IEmsgParsingData {\n schemeIdUri: string;\n value: string;\n timeScale: number;\n presentationTimeDelta?: number;\n presentationTime?: number;\n eventDuration: number;\n id: number;\n payload: Uint8Array;\n}\n\nexport function parseSamples(\n timeOffset: number,\n track: PassthroughTrack,\n): UserdataSample[] {\n const seiSamples = [] as UserdataSample[];\n const videoData = track.samples;\n const timescale = track.timescale;\n const trackId = track.id;\n let isHEVCFlavor = false;\n\n const moofs = findBox(videoData, ['moof']);\n moofs.map((moof) => {\n const moofOffset = moof.byteOffset - 8;\n const trafs = findBox(moof, ['traf']);\n trafs.map((traf) => {\n // get the base media decode time from the tfdt\n const baseTime = findBox(traf, ['tfdt']).map((tfdt) => {\n const version = tfdt[0];\n let result = readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n result += readUint32(tfdt, 8);\n }\n return result / timescale;\n })[0];\n\n if (baseTime !== undefined) {\n timeOffset = baseTime;\n }\n\n return findBox(traf, ['tfhd']).map((tfhd) => {\n const id = readUint32(tfhd, 4);\n const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;\n const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;\n const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;\n const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;\n let defaultSampleDuration = 0;\n const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;\n let defaultSampleSize = 0;\n const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;\n let tfhdOffset = 8;\n\n if (id === trackId) {\n if (baseDataOffsetPresent) {\n tfhdOffset += 8;\n }\n if (sampleDescriptionIndexPresent) {\n tfhdOffset += 4;\n }\n if (defaultSampleDurationPresent) {\n defaultSampleDuration = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleSizePresent) {\n defaultSampleSize = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleFlagsPresent) {\n tfhdOffset += 4;\n }\n if (track.type === 'video') {\n isHEVCFlavor = isHEVC(track.codec);\n }\n\n findBox(traf, ['trun']).map((trun) => {\n const version = trun[0];\n const flags = readUint32(trun, 0) & 0xffffff;\n const dataOffsetPresent = (flags & 0x000001) !== 0;\n let dataOffset = 0;\n const firstSampleFlagsPresent = (flags & 0x000004) !== 0;\n const sampleDurationPresent = (flags & 0x000100) !== 0;\n let sampleDuration = 0;\n const sampleSizePresent = (flags & 0x000200) !== 0;\n let sampleSize = 0;\n const sampleFlagsPresent = (flags & 0x000400) !== 0;\n const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;\n let compositionOffset = 0;\n const sampleCount = readUint32(trun, 4);\n let trunOffset = 8; // past version, flags, and sample count\n\n if (dataOffsetPresent) {\n dataOffset = readUint32(trun, trunOffset);\n trunOffset += 4;\n }\n if (firstSampleFlagsPresent) {\n trunOffset += 4;\n }\n\n let sampleOffset = dataOffset + moofOffset;\n\n for (let ix = 0; ix < sampleCount; ix++) {\n if (sampleDurationPresent) {\n sampleDuration = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleDuration = defaultSampleDuration;\n }\n if (sampleSizePresent) {\n sampleSize = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleSize = defaultSampleSize;\n }\n if (sampleFlagsPresent) {\n trunOffset += 4;\n }\n if (sampleCompositionOffsetsPresent) {\n if (version === 0) {\n compositionOffset = readUint32(trun, trunOffset);\n } else {\n compositionOffset = readSint32(trun, trunOffset);\n }\n trunOffset += 4;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n let naluTotalSize = 0;\n while (naluTotalSize < sampleSize) {\n const naluSize = readUint32(videoData, sampleOffset);\n sampleOffset += 4;\n if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {\n const data = videoData.subarray(\n sampleOffset,\n sampleOffset + naluSize,\n );\n parseSEIMessageFromNALu(\n data,\n isHEVCFlavor ? 2 : 1,\n timeOffset + compositionOffset / timescale,\n seiSamples,\n );\n }\n sampleOffset += naluSize;\n naluTotalSize += naluSize + 4;\n }\n }\n\n timeOffset += sampleDuration / timescale;\n }\n });\n }\n });\n });\n });\n return seiSamples;\n}\n\nfunction isHEVC(codec: string) {\n if (!codec) {\n return false;\n }\n const delimit = codec.indexOf('.');\n const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);\n return (\n baseCodec === 'hvc1' ||\n baseCodec === 'hev1' ||\n // Dolby Vision\n baseCodec === 'dvh1' ||\n baseCodec === 'dvhe'\n );\n}\n\nfunction isSEIMessage(isHEVCFlavor: boolean, naluHeader: number) {\n if (isHEVCFlavor) {\n const naluType = (naluHeader >> 1) & 0x3f;\n return naluType === 39 || naluType === 40;\n } else {\n const naluType = naluHeader & 0x1f;\n return naluType === 6;\n }\n}\n\nexport function parseSEIMessageFromNALu(\n unescapedData: Uint8Array,\n headerSize: number,\n pts: number,\n samples: UserdataSample[],\n) {\n const data = discardEPB(unescapedData);\n let seiPtr = 0;\n // skip nal header\n seiPtr += headerSize;\n let payloadType = 0;\n let payloadSize = 0;\n let b = 0;\n\n while (seiPtr < data.length) {\n payloadType = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadType += b;\n } while (b === 0xff);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadSize += b;\n } while (b === 0xff);\n\n const leftOver = data.length - seiPtr;\n // Create a variable to process the payload\n let payPtr = seiPtr;\n\n // Increment the seiPtr to the end of the payload\n if (payloadSize < leftOver) {\n seiPtr += payloadSize;\n } else if (payloadSize > leftOver) {\n // Some type of corruption has happened?\n logger.error(\n `Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`,\n );\n // We might be able to parse some data, but let's be safe and ignore it.\n break;\n }\n\n if (payloadType === 4) {\n const countryCode = data[payPtr++];\n if (countryCode === 181) {\n const providerCode = readUint16(data, payPtr);\n payPtr += 2;\n\n if (providerCode === 49) {\n const userStructure = readUint32(data, payPtr);\n payPtr += 4;\n\n if (userStructure === 0x47413934) {\n const userDataType = data[payPtr++];\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n const firstByte = data[payPtr++];\n const totalCCs = 0x1f & firstByte;\n const enabled = 0x40 & firstByte;\n const totalBytes = enabled ? 2 + totalCCs * 3 : 0;\n const byteArray = new Uint8Array(totalBytes);\n if (enabled) {\n byteArray[0] = firstByte;\n for (let i = 1; i < totalBytes; i++) {\n byteArray[i] = data[payPtr++];\n }\n }\n\n samples.push({\n type: userDataType,\n payloadType,\n pts,\n bytes: byteArray,\n });\n }\n }\n }\n }\n } else if (payloadType === 5) {\n if (payloadSize > 16) {\n const uuidStrArray: Array<string> = [];\n for (let i = 0; i < 16; i++) {\n const b = data[payPtr++].toString(16);\n uuidStrArray.push(b.length == 1 ? '0' + b : b);\n\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataBytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n userDataBytes[i] = data[payPtr++];\n }\n\n samples.push({\n payloadType,\n pts,\n uuid: uuidStrArray.join(''),\n userData: utf8ArrayToStr(userDataBytes),\n userDataBytes,\n });\n }\n }\n }\n}\n\n/**\n * remove Emulation Prevention bytes from a RBSP\n */\nexport function discardEPB(data: Uint8Array): Uint8Array {\n const length = data.byteLength;\n const EPBPositions = [] as Array<number>;\n let i = 1;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n const newLength = length - EPBPositions.length;\n const newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n}\n\nexport function parseEmsg(data: Uint8Array): IEmsgParsingData {\n const version = data[0];\n let schemeIdUri: string = '';\n let value: string = '';\n let timeScale: number = 0;\n let presentationTimeDelta: number = 0;\n let presentationTime: number = 0;\n let eventDuration: number = 0;\n let id: number = 0;\n let offset: number = 0;\n\n if (version === 0) {\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n timeScale = readUint32(data, 12);\n presentationTimeDelta = readUint32(data, 16);\n eventDuration = readUint32(data, 20);\n id = readUint32(data, 24);\n offset = 28;\n } else if (version === 1) {\n offset += 4;\n timeScale = readUint32(data, offset);\n offset += 4;\n const leftPresentationTime = readUint32(data, offset);\n offset += 4;\n const rightPresentationTime = readUint32(data, offset);\n offset += 4;\n presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;\n if (!Number.isSafeInteger(presentationTime)) {\n presentationTime = Number.MAX_SAFE_INTEGER;\n logger.warn(\n 'Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box',\n );\n }\n\n eventDuration = readUint32(data, offset);\n offset += 4;\n id = readUint32(data, offset);\n offset += 4;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n const payload = data.subarray(offset, data.byteLength);\n\n return {\n schemeIdUri,\n value,\n timeScale,\n presentationTime,\n presentationTimeDelta,\n eventDuration,\n id,\n payload,\n };\n}\n\nexport function mp4Box(type: ArrayLike<number>, ...payload: Uint8Array[]) {\n const len = payload.length;\n let size = 8;\n let i = len;\n while (i--) {\n size += payload[i].byteLength;\n }\n const result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n for (i = 0, size = 8; i < len; i++) {\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n}\n\nexport function mp4pssh(\n systemId: Uint8Array,\n keyids: Array<Uint8Array> | null,\n data: Uint8Array,\n) {\n if (systemId.byteLength !== 16) {\n throw new RangeError('Invalid system id');\n }\n let version;\n let kids;\n if (keyids) {\n version = 1;\n kids = new Uint8Array(keyids.length * 16);\n for (let ix = 0; ix < keyids.length; ix++) {\n const k = keyids[ix]; // uint8array\n if (k.byteLength !== 16) {\n throw new RangeError('Invalid key');\n }\n kids.set(k, ix * 16);\n }\n } else {\n version = 0;\n kids = new Uint8Array();\n }\n let kidCount;\n if (version > 0) {\n kidCount = new Uint8Array(4);\n if (keyids!.length > 0) {\n new DataView(kidCount.buffer).setUint32(0, keyids!.length, false);\n }\n } else {\n kidCount = new Uint8Array();\n }\n const dataSize = new Uint8Array(4);\n if (data && data.byteLength > 0) {\n new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);\n }\n return mp4Box(\n [112, 115, 115, 104],\n new Uint8Array([\n version,\n 0x00,\n 0x00,\n 0x00, // Flags\n ]),\n systemId, // 16 bytes\n kidCount,\n kids,\n dataSize,\n data || new Uint8Array(),\n );\n}\n\nexport type PsshData = {\n version: 0 | 1;\n systemId: KeySystemIds;\n kids: null | Uint8Array[];\n data: null | Uint8Array;\n offset: number;\n size: number;\n};\n\nexport type PsshInvalidResult = {\n systemId?: undefined;\n offset: number;\n size: number;\n};\n\nexport function parseMultiPssh(\n initData: ArrayBuffer,\n): (PsshData | PsshInvalidResult)[] {\n const results: (PsshData | PsshInvalidResult)[] = [];\n if (initData instanceof ArrayBuffer) {\n const length = initData.byteLength;\n let offset = 0;\n while (offset + 32 < length) {\n const view = new DataView(initData, offset);\n const pssh = parsePssh(view);\n results.push(pssh);\n offset += pssh.size;\n }\n }\n return results;\n}\n\nfunction parsePssh(view: DataView): PsshData | PsshInvalidResult {\n const size = view.getUint32(0);\n const offset = view.byteOffset;\n const length = view.byteLength;\n if (length < size) {\n return {\n offset,\n size: length,\n };\n }\n const type = view.getUint32(4);\n if (type !== 0x70737368) {\n return { offset, size };\n }\n const version = view.getUint32(8) >>> 24;\n if (version !== 0 && version !== 1) {\n return { offset, size };\n }\n const buffer = view.buffer;\n const systemId = Hex.hexDump(\n new Uint8Array(buffer, offset + 12, 16),\n ) as KeySystemIds;\n const dataSizeOrKidCount = view.getUint32(28);\n let kids: null | Uint8Array[] = null;\n let data: null | Uint8Array = null;\n if (version === 0) {\n if (size - 32 < dataSizeOrKidCount || dataSizeOrKidCount < 22) {\n return { offset, size };\n }\n data = new Uint8Array(buffer, offset + 32, dataSizeOrKidCount);\n } else if (version === 1) {\n if (\n !dataSizeOrKidCount ||\n length < offset + 32 + dataSizeOrKidCount * 16 + 16\n ) {\n return { offset, size };\n }\n kids = [];\n for (let i = 0; i < dataSizeOrKidCount; i++) {\n kids.push(new Uint8Array(buffer, offset + 32 + i * 16, 16));\n }\n }\n return {\n version,\n systemId,\n kids,\n data,\n offset,\n size,\n };\n}\n","import {\n changeEndianness,\n convertDataUriToArrayBytes,\n} from '../utils/keysystem-util';\nimport { KeySystemFormats } from '../utils/mediakeys-helper';\nimport { mp4pssh } from '../utils/mp4-tools';\nimport { logger } from '../utils/logger';\nimport { base64Decode } from '../utils/numeric-encoding-utils';\n\nlet keyUriToKeyIdMap: { [uri: string]: Uint8Array } = {};\n\nexport interface DecryptData {\n uri: string;\n method: string;\n keyFormat: string;\n keyFormatVersions: number[];\n iv: Uint8Array | null;\n key: Uint8Array | null;\n keyId: Uint8Array | null;\n pssh: Uint8Array | null;\n encrypted: boolean;\n isCommonEncryption: boolean;\n}\n\nexport class LevelKey implements DecryptData {\n public readonly uri: string;\n public readonly method: string;\n public readonly keyFormat: string;\n public readonly keyFormatVersions: number[];\n public readonly encrypted: boolean;\n public readonly isCommonEncryption: boolean;\n public iv: Uint8Array | null = null;\n public key: Uint8Array | null = null;\n public keyId: Uint8Array | null = null;\n public pssh: Uint8Array | null = null;\n\n static clearKeyUriToKeyIdMap() {\n keyUriToKeyIdMap = {};\n }\n\n constructor(\n method: string,\n uri: string,\n format: string,\n formatversions: number[] = [1],\n iv: Uint8Array | null = null,\n ) {\n this.method = method;\n this.uri = uri;\n this.keyFormat = format;\n this.keyFormatVersions = formatversions;\n this.iv = iv;\n this.encrypted = method ? method !== 'NONE' : false;\n this.isCommonEncryption = this.encrypted && method !== 'AES-128';\n }\n\n public isSupported(): boolean {\n // If it's Segment encryption or No encryption, just select that key system\n if (this.method) {\n if (this.method === 'AES-128' || this.method === 'NONE') {\n return true;\n }\n if (this.keyFormat === 'identity') {\n // Maintain support for clear SAMPLE-AES with MPEG-3 TS\n return this.method === 'SAMPLE-AES';\n } else if (__USE_EME_DRM__) {\n switch (this.keyFormat) {\n case KeySystemFormats.FAIRPLAY:\n case KeySystemFormats.WIDEVINE:\n case KeySystemFormats.PLAYREADY:\n case KeySystemFormats.CLEARKEY:\n return (\n [\n 'ISO-23001-7',\n 'SAMPLE-AES',\n 'SAMPLE-AES-CENC',\n 'SAMPLE-AES-CTR',\n ].indexOf(this.method) !== -1\n );\n }\n }\n }\n return false;\n }\n\n public getDecryptData(sn: number | 'initSegment'): LevelKey | null {\n if (!this.encrypted || !this.uri) {\n return null;\n }\n\n if (this.method === 'AES-128' && this.uri && !this.iv) {\n if (typeof sn !== 'number') {\n // We are fetching decryption data for a initialization segment\n // If the segment was encrypted with AES-128\n // It must have an IV defined. We cannot substitute the Segment Number in.\n if (this.method === 'AES-128' && !this.iv) {\n logger.warn(\n `missing IV for initialization segment with method=\"${this.method}\" - compliance issue`,\n );\n }\n // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n sn = 0;\n }\n const iv = createInitializationVector(sn);\n const decryptdata = new LevelKey(\n this.method,\n this.uri,\n 'identity',\n this.keyFormatVersions,\n iv,\n );\n return decryptdata;\n }\n\n if (!__USE_EME_DRM__) {\n return this;\n }\n\n // Initialize keyId if possible\n const keyBytes = convertDataUriToArrayBytes(this.uri);\n if (keyBytes) {\n switch (this.keyFormat) {\n case KeySystemFormats.WIDEVINE:\n this.pssh = keyBytes;\n // In case of widevine keyID is embedded in PSSH box. Read Key ID.\n if (keyBytes.length >= 22) {\n this.keyId = keyBytes.subarray(\n keyBytes.length - 22,\n keyBytes.length - 6,\n );\n }\n break;\n case KeySystemFormats.PLAYREADY: {\n const PlayReadyKeySystemUUID = new Uint8Array([\n 0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6,\n 0x5b, 0xe0, 0x88, 0x5f, 0x95,\n ]);\n\n this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);\n\n const keyBytesUtf16 = new Uint16Array(\n keyBytes.buffer,\n keyBytes.byteOffset,\n keyBytes.byteLength / 2,\n );\n const keyByteStr = String.fromCharCode.apply(\n null,\n Array.from(keyBytesUtf16),\n );\n\n // Parse Playready WRMHeader XML\n const xmlKeyBytes = keyByteStr.substring(\n keyByteStr.indexOf('<'),\n keyByteStr.length,\n );\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');\n const keyData = xmlDoc.getElementsByTagName('KID')[0];\n if (keyData) {\n const keyId = keyData.childNodes[0]\n ? keyData.childNodes[0].nodeValue\n : keyData.getAttribute('VALUE');\n if (keyId) {\n const keyIdArray = base64Decode(keyId).subarray(0, 16);\n // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID\n // KID value in tenc is a big endian UUID GUID interpretation of UUID\n changeEndianness(keyIdArray);\n this.keyId = keyIdArray;\n }\n }\n break;\n }\n default: {\n let keydata = keyBytes.subarray(0, 16);\n if (keydata.length !== 16) {\n const padded = new Uint8Array(16);\n padded.set(keydata, 16 - keydata.length);\n keydata = padded;\n }\n this.keyId = keydata;\n break;\n }\n }\n }\n\n // Default behavior: assign a new keyId for each uri\n if (!this.keyId || this.keyId.byteLength !== 16) {\n let keyId = keyUriToKeyIdMap[this.uri];\n if (!keyId) {\n const val =\n Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;\n keyId = new Uint8Array(16);\n const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes\n dv.setUint32(0, val);\n keyUriToKeyIdMap[this.uri] = keyId;\n }\n this.keyId = keyId;\n }\n\n return this;\n }\n}\n\nfunction createInitializationVector(segmentNumber: number): Uint8Array {\n const uint8View = new Uint8Array(16);\n for (let i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> (8 * (15 - i))) & 0xff;\n }\n return uint8View;\n}\n","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(\n preferManagedMediaSource = true,\n): typeof MediaSource | undefined {\n if (typeof self === 'undefined') return undefined;\n const mms =\n (preferManagedMediaSource || !self.MediaSource) &&\n ((self as any).ManagedMediaSource as undefined | typeof MediaSource);\n return (\n mms ||\n self.MediaSource ||\n ((self as any).WebKitMediaSource as typeof MediaSource)\n );\n}\n\nexport function isManagedMediaSource(source: typeof MediaSource | undefined) {\n return (\n typeof self !== 'undefined' && source === (self as any).ManagedMediaSource\n );\n}\n","import { getMediaSource } from './mediasource-helper';\n\n// from http://mp4ra.org/codecs.html\n// values indicate codec selection preference (lower is higher priority)\nconst sampleEntryCodesISO = {\n audio: {\n a3ds: 1,\n 'ac-3': 0.95,\n 'ac-4': 1,\n alac: 0.9,\n alaw: 1,\n dra1: 1,\n 'dts+': 1,\n 'dts-': 1,\n dtsc: 1,\n dtse: 1,\n dtsh: 1,\n 'ec-3': 0.9,\n enca: 1,\n fLaC: 0.9, // MP4-RA listed codec entry for FLAC\n flac: 0.9, // legacy browser codec name for FLAC\n FLAC: 0.9, // some manifests may list \"FLAC\" with Apple's tools\n g719: 1,\n g726: 1,\n m4ae: 1,\n mha1: 1,\n mha2: 1,\n mhm1: 1,\n mhm2: 1,\n mlpa: 1,\n mp4a: 1,\n 'raw ': 1,\n Opus: 1,\n opus: 1, // browsers expect this to be lowercase despite MP4RA says 'Opus'\n samr: 1,\n sawb: 1,\n sawp: 1,\n sevc: 1,\n sqcp: 1,\n ssmv: 1,\n twos: 1,\n ulaw: 1,\n },\n video: {\n avc1: 1,\n avc2: 1,\n avc3: 1,\n avc4: 1,\n avcp: 1,\n av01: 0.8,\n drac: 1,\n dva1: 1,\n dvav: 1,\n dvh1: 0.7,\n dvhe: 0.7,\n encv: 1,\n hev1: 0.75,\n hvc1: 0.75,\n mjp2: 1,\n mp4v: 1,\n mvc1: 1,\n mvc2: 1,\n mvc3: 1,\n mvc4: 1,\n resv: 1,\n rv60: 1,\n s263: 1,\n svc1: 1,\n svc2: 1,\n 'vc-1': 1,\n vp08: 1,\n vp09: 0.9,\n },\n text: {\n stpp: 1,\n wvtt: 1,\n },\n} as const;\n\nexport type CodecType = 'audio' | 'video';\n\nexport function isCodecType(codec: string, type: CodecType): boolean {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && !!typeCodes[codec.slice(0, 4)];\n}\n\nexport function areCodecsMediaSourceSupported(\n codecs: string,\n type: CodecType,\n preferManagedMediaSource = true,\n): boolean {\n return !codecs\n .split(',')\n .some(\n (codec) =>\n !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource),\n );\n}\n\nfunction isCodecMediaSourceSupported(\n codec: string,\n type: CodecType,\n preferManagedMediaSource = true,\n): boolean {\n const MediaSource = getMediaSource(preferManagedMediaSource);\n return MediaSource?.isTypeSupported(mimeTypeForCodec(codec, type)) ?? false;\n}\n\nexport function mimeTypeForCodec(codec: string, type: CodecType): string {\n return `${type}/mp4;codecs=\"${codec}\"`;\n}\n\nexport function videoCodecPreferenceValue(\n videoCodec: string | undefined,\n): number {\n if (videoCodec) {\n const fourCC = videoCodec.substring(0, 4);\n return sampleEntryCodesISO.video[fourCC];\n }\n return 2;\n}\n\nexport function codecsSetSelectionPreferenceValue(codecSet: string): number {\n return codecSet.split(',').reduce((num, fourCC) => {\n const preferenceValue = sampleEntryCodesISO.video[fourCC];\n if (preferenceValue) {\n return (preferenceValue * 2 + num) / (num ? 3 : 2);\n }\n return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);\n }, 0);\n}\n\ninterface CodecNameCache {\n flac?: string;\n opus?: string;\n}\n\nconst CODEC_COMPATIBLE_NAMES: CodecNameCache = {};\n\ntype LowerCaseCodecType = 'flac' | 'opus';\n\nfunction getCodecCompatibleNameLower(\n lowerCaseCodec: LowerCaseCodecType,\n preferManagedMediaSource = true,\n): string {\n if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {\n return CODEC_COMPATIBLE_NAMES[lowerCaseCodec]!;\n }\n\n // Idealy fLaC and Opus would be first (spec-compliant) but\n // some browsers will report that fLaC is supported then fail.\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728\n const codecsToCheck = {\n flac: ['flac', 'fLaC', 'FLAC'],\n opus: ['opus', 'Opus'],\n }[lowerCaseCodec];\n\n for (let i = 0; i < codecsToCheck.length; i++) {\n if (\n isCodecMediaSourceSupported(\n codecsToCheck[i],\n 'audio',\n preferManagedMediaSource,\n )\n ) {\n CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];\n return codecsToCheck[i];\n }\n }\n\n return lowerCaseCodec;\n}\n\nconst AUDIO_CODEC_REGEXP = /flac|opus/i;\nexport function getCodecCompatibleName(\n codec: string,\n preferManagedMediaSource = true,\n): string {\n return codec.replace(AUDIO_CODEC_REGEXP, (m) =>\n getCodecCompatibleNameLower(\n m.toLowerCase() as LowerCaseCodecType,\n preferManagedMediaSource,\n ),\n );\n}\n\nexport function pickMostCompleteCodecName(\n parsedCodec: string,\n levelCodec: string | undefined,\n): string | undefined {\n // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a\n // so use level codec is parsed codec is unavailable or incomplete\n if (parsedCodec && parsedCodec !== 'mp4a') {\n return parsedCodec;\n }\n return levelCodec ? levelCodec.split(',')[0] : levelCodec;\n}\n\nexport function convertAVC1ToAVCOTI(codec: string) {\n // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported\n // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.\n const codecs = codec.split(',');\n for (let i = 0; i < codecs.length; i++) {\n const avcdata = codecs[i].split('.');\n if (avcdata.length > 2) {\n let result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift() as string).toString(16);\n result += (\n '000' + parseInt(avcdata.shift() as string).toString(16)\n ).slice(-4);\n codecs[i] = result;\n }\n }\n return codecs.join(',');\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport { DateRange } from './date-range';\nimport { Fragment, Part } from './fragment';\nimport { LevelDetails } from './level-details';\nimport { LevelKey } from './level-key';\nimport { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport {\n addVariableDefinition,\n hasVariableReferences,\n importVariableDefinition,\n substituteVariables,\n substituteVariablesInAttributes,\n} from '../utils/variable-substitution';\nimport { isCodecType } from '../utils/codecs';\nimport type { CodecType } from '../utils/codecs';\nimport type { MediaPlaylist, MediaAttributes } from '../types/media-playlist';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { LevelAttributes, LevelParsed, VariableMap } from '../types/level';\nimport type { ContentSteeringOptions } from '../types/events';\n\ntype M3U8ParserFragments = Array<Fragment | null>;\n\nexport type ParsedMultivariantPlaylist = {\n contentSteering: ContentSteeringOptions | null;\n levels: LevelParsed[];\n playlistParsingError: Error | null;\n sessionData: Record<string, AttrList> | null;\n sessionKeys: LevelKey[] | null;\n startTimeOffset: number | null;\n variableList: VariableMap | null;\n hasVariableRefs: boolean;\n};\n\ntype ParsedMultivariantMediaOptions = {\n AUDIO?: MediaPlaylist[];\n SUBTITLES?: MediaPlaylist[];\n 'CLOSED-CAPTIONS'?: MediaPlaylist[];\n};\n\nconst MASTER_PLAYLIST_REGEX =\n /#EXT-X-STREAM-INF:([^\\r\\n]*)(?:[\\r\\n](?:#[^\\r\\n]*)?)*([^\\r\\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\\r\\n]*)[\\r\\n]+/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp(\n [\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /(?!#) *(\\S[^\\r\\n]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /#.*/.source, // All other non-segment oriented tags will match with all groups empty\n ].join('|'),\n 'g',\n);\n\nconst LEVEL_PLAYLIST_REGEX_SLOW = new RegExp(\n [\n /#(EXTM3U)/.source,\n /#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/\n .source,\n /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)/\n .source,\n /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,\n /(#)([^:]*):(.*)/.source,\n /(#)(.*)(?:.*)\\r?\\n?/.source,\n ].join('|'),\n);\n\nexport default class M3U8Parser {\n static findGroup(\n groups: (\n | { id?: string; audioCodec?: string }\n | { id?: string; textCodec?: string }\n )[],\n mediaGroupId: string,\n ):\n | { id?: string; audioCodec?: string }\n | { id?: string; textCodec?: string }\n | undefined {\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n return group;\n }\n }\n }\n\n static resolve(url, baseUrl) {\n return buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static isMediaPlaylist(str: string): boolean {\n return IS_MEDIA_PLAYLIST.test(str);\n }\n\n static parseMasterPlaylist(\n string: string,\n baseurl: string,\n ): ParsedMultivariantPlaylist {\n const hasVariableRefs = __USE_VARIABLE_SUBSTITUTION__\n ? hasVariableReferences(string)\n : false;\n const parsed: ParsedMultivariantPlaylist = {\n contentSteering: null,\n levels: [],\n playlistParsingError: null,\n sessionData: null,\n sessionKeys: null,\n startTimeOffset: null,\n variableList: null,\n hasVariableRefs,\n };\n const levelsWithKnownCodecs: LevelParsed[] = [];\n\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n let result: RegExpExecArray | null;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n if (result[1]) {\n // '#EXT-X-STREAM-INF' is found, parse level tag in group 1\n const attrs = new AttrList(result[1]) as LevelAttributes;\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, attrs, [\n 'CODECS',\n 'SUPPLEMENTAL-CODECS',\n 'ALLOWED-CPC',\n 'PATHWAY-ID',\n 'STABLE-VARIANT-ID',\n 'AUDIO',\n 'VIDEO',\n 'SUBTITLES',\n 'CLOSED-CAPTIONS',\n 'NAME',\n ]);\n }\n const uri = __USE_VARIABLE_SUBSTITUTION__\n ? substituteVariables(parsed, result[2])\n : result[2];\n const level: LevelParsed = {\n attrs,\n bitrate:\n attrs.decimalInteger('BANDWIDTH') ||\n attrs.decimalInteger('AVERAGE-BANDWIDTH'),\n name: attrs.NAME,\n url: M3U8Parser.resolve(uri, baseurl),\n };\n\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n\n setCodecs(attrs.CODECS, level);\n\n if (!level.unknownCodecs?.length) {\n levelsWithKnownCodecs.push(level);\n }\n\n parsed.levels.push(level);\n } else if (result[3]) {\n const tag = result[3];\n const attributes = result[4];\n switch (tag) {\n case 'SESSION-DATA': {\n // #EXT-X-SESSION-DATA\n const sessionAttrs = new AttrList(attributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, sessionAttrs, [\n 'DATA-ID',\n 'LANGUAGE',\n 'VALUE',\n 'URI',\n ]);\n }\n const dataId = sessionAttrs['DATA-ID'];\n if (dataId) {\n if (parsed.sessionData === null) {\n parsed.sessionData = {};\n }\n parsed.sessionData[dataId] = sessionAttrs;\n }\n break;\n }\n case 'SESSION-KEY': {\n // #EXT-X-SESSION-KEY\n const sessionKey = parseKey(attributes, baseurl, parsed);\n if (sessionKey.encrypted && sessionKey.isSupported()) {\n if (parsed.sessionKeys === null) {\n parsed.sessionKeys = [];\n }\n parsed.sessionKeys.push(sessionKey);\n } else {\n logger.warn(\n `[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"${attributes}\"`,\n );\n }\n break;\n }\n case 'DEFINE': {\n // #EXT-X-DEFINE\n if (__USE_VARIABLE_SUBSTITUTION__) {\n const variableAttributes = new AttrList(attributes);\n substituteVariablesInAttributes(parsed, variableAttributes, [\n 'NAME',\n 'VALUE',\n 'QUERYPARAM',\n ]);\n addVariableDefinition(parsed, variableAttributes, baseurl);\n }\n break;\n }\n case 'CONTENT-STEERING': {\n // #EXT-X-CONTENT-STEERING\n const contentSteeringAttributes = new AttrList(attributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(\n parsed,\n contentSteeringAttributes,\n ['SERVER-URI', 'PATHWAY-ID'],\n );\n }\n parsed.contentSteering = {\n uri: M3U8Parser.resolve(\n contentSteeringAttributes['SERVER-URI'],\n baseurl,\n ),\n pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.',\n };\n break;\n }\n case 'START': {\n // #EXT-X-START\n parsed.startTimeOffset = parseStartTimeOffset(attributes);\n break;\n }\n default:\n break;\n }\n }\n }\n // Filter out levels with unknown codecs if it does not remove all levels\n const stripUnknownCodecLevels =\n levelsWithKnownCodecs.length > 0 &&\n levelsWithKnownCodecs.length < parsed.levels.length;\n\n parsed.levels = stripUnknownCodecLevels\n ? levelsWithKnownCodecs\n : parsed.levels;\n if (parsed.levels.length === 0) {\n parsed.playlistParsingError = new Error('no levels found in manifest');\n }\n\n return parsed;\n }\n\n static parseMasterPlaylistMedia(\n string: string,\n baseurl: string,\n parsed: ParsedMultivariantPlaylist,\n ): ParsedMultivariantMediaOptions {\n let result: RegExpExecArray | null;\n const results: ParsedMultivariantMediaOptions = {};\n const levels = parsed.levels;\n const groupsByType = {\n AUDIO: levels.map((level: LevelParsed) => ({\n id: level.attrs.AUDIO,\n audioCodec: level.audioCodec,\n })),\n SUBTITLES: levels.map((level: LevelParsed) => ({\n id: level.attrs.SUBTITLES,\n textCodec: level.textCodec,\n })),\n 'CLOSED-CAPTIONS': [],\n };\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const attrs = new AttrList(result[1]) as MediaAttributes;\n const type = attrs.TYPE;\n if (type) {\n const groups: (typeof groupsByType)[keyof typeof groupsByType] =\n groupsByType[type];\n const medias: MediaPlaylist[] = results[type] || [];\n results[type] = medias;\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, attrs, [\n 'URI',\n 'GROUP-ID',\n 'LANGUAGE',\n 'ASSOC-LANGUAGE',\n 'STABLE-RENDITION-ID',\n 'NAME',\n 'INSTREAM-ID',\n 'CHARACTERISTICS',\n 'CHANNELS',\n ]);\n }\n const lang = attrs.LANGUAGE;\n const assocLang = attrs['ASSOC-LANGUAGE'];\n const channels = attrs.CHANNELS;\n const characteristics = attrs.CHARACTERISTICS;\n const instreamId = attrs['INSTREAM-ID'];\n const media: MediaPlaylist = {\n attrs,\n bitrate: 0,\n id: id++,\n groupId: attrs['GROUP-ID'] || '',\n name: attrs.NAME || lang || '',\n type,\n default: attrs.bool('DEFAULT'),\n autoselect: attrs.bool('AUTOSELECT'),\n forced: attrs.bool('FORCED'),\n lang,\n url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : '',\n };\n if (assocLang) {\n media.assocLang = assocLang;\n }\n if (channels) {\n media.channels = channels;\n }\n if (characteristics) {\n media.characteristics = characteristics;\n }\n if (instreamId) {\n media.instreamId = instreamId;\n }\n\n if (groups?.length) {\n // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n const groupCodec =\n M3U8Parser.findGroup(groups, media.groupId as string) || groups[0];\n assignCodec(media, groupCodec, 'audioCodec');\n assignCodec(media, groupCodec, 'textCodec');\n }\n\n medias.push(media);\n }\n }\n return results;\n }\n\n static parseLevelPlaylist(\n string: string,\n baseurl: string,\n id: number,\n type: PlaylistLevelType,\n levelUrlId: number,\n multivariantVariableList: VariableMap | null,\n ): LevelDetails {\n const level = new LevelDetails(baseurl);\n const fragments: M3U8ParserFragments = level.fragments;\n // The most recent init segment seen (applies to all subsequent segments)\n let currentInitSegment: Fragment | null = null;\n let currentSN = 0;\n let currentPart = 0;\n let totalduration = 0;\n let discontinuityCounter = 0;\n let prevFrag: Fragment | null = null;\n let frag: Fragment = new Fragment(type, baseurl);\n let result: RegExpExecArray | RegExpMatchArray | null;\n let i: number;\n let levelkeys: { [key: string]: LevelKey } | undefined;\n let firstPdtIndex = -1;\n let createNextFrag = false;\n let nextByteRange: string | null = null;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n level.m3u8 = string;\n level.hasVariableRefs = __USE_VARIABLE_SUBSTITUTION__\n ? hasVariableReferences(string)\n : false;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n if (createNextFrag) {\n createNextFrag = false;\n frag = new Fragment(type, baseurl);\n // setup the next fragment for part loading\n frag.start = totalduration;\n frag.sn = currentSN;\n frag.cc = discontinuityCounter;\n frag.level = id;\n if (currentInitSegment) {\n frag.initSegment = currentInitSegment;\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n currentInitSegment.rawProgramDateTime = null;\n if (nextByteRange) {\n frag.setByteRange(nextByteRange);\n nextByteRange = null;\n }\n }\n }\n\n const duration = result[1];\n if (duration) {\n // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n } else if (result[3]) {\n // url\n if (Number.isFinite(frag.duration)) {\n frag.start = totalduration;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n frag.sn = currentSN;\n frag.level = id;\n frag.cc = discontinuityCounter;\n fragments.push(frag);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const uri = (' ' + result[3]).slice(1);\n frag.relurl = __USE_VARIABLE_SUBSTITUTION__\n ? substituteVariables(level, uri)\n : uri;\n assignProgramDateTime(frag, prevFrag);\n prevFrag = frag;\n totalduration += frag.duration;\n currentSN++;\n currentPart = 0;\n createNextFrag = true;\n }\n } else if (result[4]) {\n // X-BYTERANGE\n const data = (' ' + result[4]).slice(1);\n if (prevFrag) {\n frag.setByteRange(data, prevFrag);\n } else {\n frag.setByteRange(data);\n }\n } else if (result[5]) {\n // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n if (firstPdtIndex === -1) {\n firstPdtIndex = fragments.length;\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n if (!result) {\n logger.warn('No matches on slow regex match for level playlist!');\n continue;\n }\n for (i = 1; i < result.length; i++) {\n if (typeof result[i] !== 'undefined') {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const tag = (' ' + result[i]).slice(1);\n const value1 = (' ' + result[i + 1]).slice(1);\n const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';\n\n switch (tag) {\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'SKIP': {\n const skipAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, skipAttrs, [\n 'RECENTLY-REMOVED-DATERANGES',\n ]);\n }\n const skippedSegments =\n skipAttrs.decimalInteger('SKIPPED-SEGMENTS');\n if (Number.isFinite(skippedSegments)) {\n level.skippedSegments = skippedSegments;\n // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`\n for (let i = skippedSegments; i--; ) {\n fragments.unshift(null);\n }\n currentSN += skippedSegments;\n }\n const recentlyRemovedDateranges = skipAttrs.enumeratedString(\n 'RECENTLY-REMOVED-DATERANGES',\n );\n if (recentlyRemovedDateranges) {\n level.recentlyRemovedDateranges =\n recentlyRemovedDateranges.split('\\t');\n }\n break;\n }\n case 'TARGETDURATION':\n level.targetduration = Math.max(parseInt(value1), 1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'INDEPENDENT-SEGMENTS':\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case '#':\n if (value1 || value2) {\n frag.tagList.push(value2 ? [value1, value2] : [value1]);\n }\n break;\n case 'DISCONTINUITY':\n discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'GAP':\n frag.gap = true;\n frag.tagList.push([tag]);\n break;\n case 'BITRATE':\n frag.tagList.push([tag, value1]);\n break;\n case 'DATERANGE': {\n const dateRangeAttr = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, dateRangeAttr, [\n 'ID',\n 'CLASS',\n 'START-DATE',\n 'END-DATE',\n 'SCTE35-CMD',\n 'SCTE35-OUT',\n 'SCTE35-IN',\n ]);\n substituteVariablesInAttributes(\n level,\n dateRangeAttr,\n dateRangeAttr.clientAttrs,\n );\n }\n const dateRange = new DateRange(\n dateRangeAttr,\n level.dateRanges[dateRangeAttr.ID],\n );\n if (dateRange.isValid || level.skippedSegments) {\n level.dateRanges[dateRange.id] = dateRange;\n } else {\n logger.warn(`Ignoring invalid DATERANGE tag: \"${value1}\"`);\n }\n // Add to fragment tag list for backwards compatibility (< v1.2.0)\n frag.tagList.push(['EXT-X-DATERANGE', value1]);\n break;\n }\n case 'DEFINE': {\n if (__USE_VARIABLE_SUBSTITUTION__) {\n const variableAttributes = new AttrList(value1);\n substituteVariablesInAttributes(level, variableAttributes, [\n 'NAME',\n 'VALUE',\n 'IMPORT',\n 'QUERYPARAM',\n ]);\n if ('IMPORT' in variableAttributes) {\n importVariableDefinition(\n level,\n variableAttributes,\n multivariantVariableList,\n );\n } else {\n addVariableDefinition(level, variableAttributes, baseurl);\n }\n }\n break;\n }\n\n case 'DISCONTINUITY-SEQUENCE':\n discontinuityCounter = parseInt(value1);\n break;\n case 'KEY': {\n const levelKey = parseKey(value1, baseurl, level);\n if (levelKey.isSupported()) {\n if (levelKey.method === 'NONE') {\n levelkeys = undefined;\n break;\n }\n if (!levelkeys) {\n levelkeys = {};\n }\n if (levelkeys[levelKey.keyFormat]) {\n levelkeys = Object.assign({}, levelkeys);\n }\n levelkeys[levelKey.keyFormat] = levelKey;\n } else {\n logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: \"${value1}\"`);\n }\n break;\n }\n case 'START':\n level.startTimeOffset = parseStartTimeOffset(value1);\n break;\n case 'MAP': {\n const mapAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, mapAttrs, [\n 'BYTERANGE',\n 'URI',\n ]);\n }\n if (frag.duration) {\n // Initial segment tag is after segment duration tag.\n // #EXTINF: 6.0\n // #EXT-X-MAP:URI=\"init.mp4\n const init = new Fragment(type, baseurl);\n setInitSegment(init, mapAttrs, id, levelkeys);\n currentInitSegment = init;\n frag.initSegment = currentInitSegment;\n if (\n currentInitSegment.rawProgramDateTime &&\n !frag.rawProgramDateTime\n ) {\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n }\n } else {\n // Initial segment tag is before segment duration tag\n // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE\n const end = frag.byteRangeEndOffset;\n if (end) {\n const start = frag.byteRangeStartOffset as number;\n nextByteRange = `${end - start}@${start}`;\n } else {\n nextByteRange = null;\n }\n setInitSegment(frag, mapAttrs, id, levelkeys);\n currentInitSegment = frag;\n createNextFrag = true;\n }\n break;\n }\n case 'SERVER-CONTROL': {\n const serverControlAttrs = new AttrList(value1);\n level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');\n level.canSkipUntil = serverControlAttrs.optionalFloat(\n 'CAN-SKIP-UNTIL',\n 0,\n );\n level.canSkipDateRanges =\n level.canSkipUntil > 0 &&\n serverControlAttrs.bool('CAN-SKIP-DATERANGES');\n level.partHoldBack = serverControlAttrs.optionalFloat(\n 'PART-HOLD-BACK',\n 0,\n );\n level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);\n break;\n }\n case 'PART-INF': {\n const partInfAttrs = new AttrList(value1);\n level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');\n break;\n }\n case 'PART': {\n let partList = level.partList;\n if (!partList) {\n partList = level.partList = [];\n }\n const previousFragmentPart =\n currentPart > 0 ? partList[partList.length - 1] : undefined;\n const index = currentPart++;\n const partAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, partAttrs, [\n 'BYTERANGE',\n 'URI',\n ]);\n }\n const part = new Part(\n partAttrs,\n frag,\n baseurl,\n index,\n previousFragmentPart,\n );\n partList.push(part);\n frag.duration += part.duration;\n break;\n }\n case 'PRELOAD-HINT': {\n const preloadHintAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, preloadHintAttrs, ['URI']);\n }\n level.preloadHint = preloadHintAttrs;\n break;\n }\n case 'RENDITION-REPORT': {\n const renditionReportAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, renditionReportAttrs, [\n 'URI',\n ]);\n }\n level.renditionReports = level.renditionReports || [];\n level.renditionReports.push(renditionReportAttrs);\n break;\n }\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n if (prevFrag && !prevFrag.relurl) {\n fragments.pop();\n totalduration -= prevFrag.duration;\n if (level.partList) {\n level.fragmentHint = prevFrag;\n }\n } else if (level.partList) {\n assignProgramDateTime(frag, prevFrag);\n frag.cc = discontinuityCounter;\n level.fragmentHint = frag;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n }\n const fragmentLength = fragments.length;\n const firstFragment = fragments[0];\n const lastFragment = fragments[fragmentLength - 1];\n totalduration += level.skippedSegments * level.targetduration;\n if (totalduration > 0 && fragmentLength && lastFragment) {\n level.averagetargetduration = totalduration / fragmentLength;\n const lastSn = lastFragment.sn;\n level.endSN = lastSn !== 'initSegment' ? lastSn : 0;\n if (!level.live) {\n lastFragment.endList = true;\n }\n if (firstFragment) {\n level.startCC = firstFragment.cc;\n }\n } else {\n level.endSN = 0;\n level.startCC = 0;\n }\n if (level.fragmentHint) {\n totalduration += level.fragmentHint.duration;\n }\n level.totalduration = totalduration;\n level.endCC = discontinuityCounter;\n\n /**\n * Backfill any missing PDT values\n * \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n * one or more Media Segment URIs, the client SHOULD extrapolate\n * backward from that tag (using EXTINF durations and/or media\n * timestamps) to associate dates with those segments.\"\n * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n * computed.\n */\n if (firstPdtIndex > 0) {\n backfillProgramDateTimes(fragments, firstPdtIndex);\n }\n\n return level;\n }\n}\n\nfunction parseKey(\n keyTagAttributes: string,\n baseurl: string,\n parsed: ParsedMultivariantPlaylist | LevelDetails,\n): LevelKey {\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const keyAttrs = new AttrList(keyTagAttributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, keyAttrs, [\n 'KEYFORMAT',\n 'KEYFORMATVERSIONS',\n 'URI',\n 'IV',\n 'URI',\n ]);\n }\n const decryptmethod = keyAttrs.METHOD ?? '';\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat = keyAttrs.KEYFORMAT ?? 'identity';\n\n if (decrypturi && keyAttrs.IV && !decryptiv) {\n logger.error(`Invalid IV: ${keyAttrs.IV}`);\n }\n // If decrypturi is a URI with a scheme, then baseurl will be ignored\n // No uri is allowed when METHOD is NONE\n const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';\n const keyFormatVersions = (\n decryptkeyformatversions ? decryptkeyformatversions : '1'\n )\n .split('/')\n .map(Number)\n .filter(Number.isFinite);\n\n return new LevelKey(\n decryptmethod,\n resolvedUri,\n decryptkeyformat,\n keyFormatVersions,\n decryptiv,\n );\n}\n\nfunction parseStartTimeOffset(startAttributes: string): number | null {\n const startAttrs = new AttrList(startAttributes);\n const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n if (Number.isFinite(startTimeOffset)) {\n return startTimeOffset;\n }\n return null;\n}\n\nfunction setCodecs(\n codecsAttributeValue: string | undefined,\n level: LevelParsed,\n) {\n let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter((c) => c);\n ['video', 'audio', 'text'].forEach((type: CodecType) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n // Comma separated list of all codecs for type\n level[`${type}Codec`] = filtered.join(',');\n // Remove known codecs so that only unknownCodecs are left after iterating through each type\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n level.unknownCodecs = codecs;\n}\n\nfunction assignCodec(\n media: MediaPlaylist,\n groupItem: { audioCodec?: string; textCodec?: string },\n codecProperty: 'audioCodec' | 'textCodec',\n) {\n const codecValue = groupItem[codecProperty];\n if (codecValue) {\n media[codecProperty] = codecValue;\n }\n}\n\nfunction backfillProgramDateTimes(\n fragments: M3U8ParserFragments,\n firstPdtIndex: number,\n) {\n let fragPrev = fragments[firstPdtIndex] as Fragment;\n for (let i = firstPdtIndex; i--; ) {\n const frag = fragments[i];\n // Exit on delta-playlist skipped segments\n if (!frag) {\n return;\n }\n frag.programDateTime =\n (fragPrev.programDateTime as number) - frag.duration * 1000;\n fragPrev = frag;\n }\n}\n\nfunction assignProgramDateTime(frag, prevFrag) {\n if (frag.rawProgramDateTime) {\n frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n } else if (prevFrag?.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n\n if (!Number.isFinite(frag.programDateTime)) {\n frag.programDateTime = null;\n frag.rawProgramDateTime = null;\n }\n}\n\nfunction setInitSegment(\n frag: Fragment,\n mapAttrs: AttrList,\n id: number,\n levelkeys: { [key: string]: LevelKey } | undefined,\n) {\n frag.relurl = mapAttrs.URI;\n if (mapAttrs.BYTERANGE) {\n frag.setByteRange(mapAttrs.BYTERANGE);\n }\n frag.level = id;\n frag.sn = 'initSegment';\n if (levelkeys) {\n frag.levelkeys = levelkeys;\n }\n frag.initSegment = null;\n}\n\nfunction setFragLevelKeys(\n frag: Fragment,\n levelkeys: { [key: string]: LevelKey },\n level: LevelDetails,\n) {\n frag.levelkeys = levelkeys;\n const { encryptedFragments } = level;\n if (\n (!encryptedFragments.length ||\n encryptedFragments[encryptedFragments.length - 1].levelkeys !==\n levelkeys) &&\n Object.keys(levelkeys).some(\n (format) => levelkeys![format].isCommonEncryption,\n )\n ) {\n encryptedFragments.push(frag);\n }\n}\n","import type { LoaderConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { KeyLoaderInfo } from '../loader/key-loader';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { HlsUrlParameters } from './level';\n\nexport interface LoaderContext {\n // target URL\n url: string;\n // loader response type (arraybuffer or default response type for playlist)\n responseType: string;\n // headers\n headers?: Record<string, string>;\n // start byte range offset\n rangeStart?: number;\n // end byte range offset\n rangeEnd?: number;\n // true if onProgress should report partial chunk of loaded content\n progressData?: boolean;\n}\n\nexport interface FragmentLoaderContext extends LoaderContext {\n frag: Fragment;\n part: Part | null;\n resetIV?: boolean;\n}\n\nexport interface KeyLoaderContext extends LoaderContext {\n keyInfo: KeyLoaderInfo;\n frag: Fragment;\n}\n\nexport interface LoaderConfiguration {\n // LoaderConfig policy that overrides required settings\n loadPolicy: LoaderConfig;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry maxNumRetry\n */\n // Max number of load retries\n maxRetry: number;\n /**\n * @deprecated use LoaderConfig maxTimeToFirstByteMs and maxLoadTimeMs\n */\n // Timeout after which `onTimeOut` callback will be triggered\n // when loading has not finished after that delay\n timeout: number;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry retryDelayMs\n */\n // Delay between an I/O error and following connection retry (ms).\n // This to avoid spamming the server\n retryDelay: number;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry maxRetryDelayMs\n */\n // max connection retry delay (ms)\n maxRetryDelay: number;\n // When streaming progressively, this is the minimum chunk size required to emit a PROGRESS event\n highWaterMark?: number;\n}\n\nexport interface LoaderResponse {\n url: string;\n data?: string | ArrayBuffer | Object;\n // Errors can include HTTP status code and error message\n // Successful responses should include status code 200\n code?: number;\n text?: string;\n}\n\nexport interface LoaderStats {\n aborted: boolean;\n loaded: number;\n retry: number;\n total: number;\n chunkCount: number;\n bwEstimate: number;\n loading: HlsProgressivePerformanceTiming;\n parsing: HlsPerformanceTiming;\n buffering: HlsProgressivePerformanceTiming;\n}\n\nexport interface HlsPerformanceTiming {\n start: number;\n end: number;\n}\n\nexport interface HlsChunkPerformanceTiming extends HlsPerformanceTiming {\n executeStart: number;\n executeEnd: number;\n}\n\nexport interface HlsProgressivePerformanceTiming extends HlsPerformanceTiming {\n first: number;\n}\n\nexport type LoaderOnSuccess<T extends LoaderContext> = (\n response: LoaderResponse,\n stats: LoaderStats,\n context: T,\n networkDetails: any,\n) => void;\n\nexport type LoaderOnProgress<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n data: string | ArrayBuffer,\n networkDetails: any,\n) => void;\n\nexport type LoaderOnError<T extends LoaderContext> = (\n error: {\n // error status code\n code: number;\n // error description\n text: string;\n },\n context: T,\n networkDetails: any,\n stats: LoaderStats,\n) => void;\n\nexport type LoaderOnTimeout<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any,\n) => void;\n\nexport type LoaderOnAbort<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any,\n) => void;\n\nexport interface LoaderCallbacks<T extends LoaderContext> {\n onSuccess: LoaderOnSuccess<T>;\n onError: LoaderOnError<T>;\n onTimeout: LoaderOnTimeout<T>;\n onAbort?: LoaderOnAbort<T>;\n onProgress?: LoaderOnProgress<T>;\n}\n\nexport interface Loader<T extends LoaderContext> {\n destroy(): void;\n abort(): void;\n load(\n context: T,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<T>,\n ): void;\n /**\n * `getCacheAge()` is called by hls.js to get the duration that a given object\n * has been sitting in a cache proxy when playing live. If implemented,\n * this should return a value in seconds.\n *\n * For HTTP based loaders, this should return the contents of the \"age\" header.\n *\n * @returns time object being lodaded\n */\n getCacheAge?: () => number | null;\n getResponseHeader?: (name: string) => string | null;\n context: T | null;\n stats: LoaderStats;\n}\n\nexport const enum PlaylistContextType {\n MANIFEST = 'manifest',\n LEVEL = 'level',\n AUDIO_TRACK = 'audioTrack',\n SUBTITLE_TRACK = 'subtitleTrack',\n}\n\nexport const enum PlaylistLevelType {\n MAIN = 'main',\n AUDIO = 'audio',\n SUBTITLE = 'subtitle',\n}\n\nexport interface PlaylistLoaderContext extends LoaderContext {\n type: PlaylistContextType;\n // the level index to load\n level: number | null;\n // level or track id from LevelLoadingData / TrackLoadingData\n id: number | null;\n // Media Playlist Group ID\n groupId?: string;\n // Content Steering Pathway ID (or undefined for default Pathway \".\")\n pathwayId?: string;\n // internal representation of a parsed m3u8 level playlist\n levelDetails?: LevelDetails;\n // Blocking playlist request delivery directives (or null id none were added to playlist url\n deliveryDirectives: HlsUrlParameters | null;\n}\n","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n */\n\nimport { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { logger } from '../utils/logger';\nimport M3U8Parser from './m3u8-parser';\nimport type { LevelParsed, VariableMap } from '../types/level';\nimport type {\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n LoaderResponse,\n LoaderStats,\n PlaylistLoaderContext,\n} from '../types/loader';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { LevelDetails } from './level-details';\nimport { AttrList } from '../utils/attr-list';\nimport type Hls from '../hls';\nimport type {\n ErrorData,\n LevelLoadingData,\n ManifestLoadingData,\n TrackLoadingData,\n} from '../types/events';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { MediaAttributes } from '../types/media-playlist';\nimport type { LoaderConfig, RetryConfig } from '../config';\n\nfunction mapContextToLevelType(\n context: PlaylistLoaderContext,\n): PlaylistLevelType {\n const { type } = context;\n\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n return PlaylistLevelType.AUDIO;\n case PlaylistContextType.SUBTITLE_TRACK:\n return PlaylistLevelType.SUBTITLE;\n default:\n return PlaylistLevelType.MAIN;\n }\n}\n\nfunction getResponseUrl(\n response: LoaderResponse,\n context: PlaylistLoaderContext,\n): string {\n let url = response.url;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n return url;\n}\n\nclass PlaylistLoader implements NetworkComponentAPI {\n private readonly hls: Hls;\n private readonly loaders: {\n [key: string]: Loader<LoaderContext>;\n } = Object.create(null);\n private variableList: VariableMap | null = null;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.registerListeners();\n }\n\n public startLoad(startPosition: number): void {}\n\n public stopLoad(): void {\n this.destroyInternalLoaders();\n }\n\n private registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n }\n\n private unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n */\n private createInternalLoader(\n context: PlaylistLoaderContext,\n ): Loader<LoaderContext> {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n const loader = new InternalLoader(config) as Loader<PlaylistLoaderContext>;\n\n this.loaders[context.type] = loader;\n return loader;\n }\n\n private getInternalLoader(\n context: PlaylistLoaderContext,\n ): Loader<LoaderContext> | undefined {\n return this.loaders[context.type];\n }\n\n private resetInternalLoader(contextType): void {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n private destroyInternalLoaders(): void {\n for (const contextType in this.loaders) {\n const loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n public destroy(): void {\n this.variableList = null;\n this.unregisterListeners();\n this.destroyInternalLoaders();\n }\n\n private onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) {\n const { url } = data;\n this.variableList = null;\n this.load({\n id: null,\n level: 0,\n responseType: 'text',\n type: PlaylistContextType.MANIFEST,\n url,\n deliveryDirectives: null,\n });\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { id, level, pathwayId, url, deliveryDirectives } = data;\n this.load({\n id,\n level,\n pathwayId,\n responseType: 'text',\n type: PlaylistContextType.LEVEL,\n url,\n deliveryDirectives,\n });\n }\n\n private onAudioTrackLoading(\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData,\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.AUDIO_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private onSubtitleTrackLoading(\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData,\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.SUBTITLE_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private load(context: PlaylistLoaderContext): void {\n const config = this.hls.config;\n\n // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context as PlaylistLoaderContext;\n if (\n loaderContext &&\n loaderContext.url === context.url &&\n loaderContext.level === context.level\n ) {\n // same URL can't overlap\n logger.trace('[playlist-loader]: playlist request ongoing');\n return;\n }\n logger.log(\n `[playlist-loader]: aborting previous loader for type: ${context.type}`,\n );\n loader.abort();\n }\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n let loadPolicy: LoaderConfig;\n if (context.type === PlaylistContextType.MANIFEST) {\n loadPolicy = config.manifestLoadPolicy.default;\n } else {\n loadPolicy = Object.assign({}, config.playlistLoadPolicy.default, {\n timeoutRetry: null,\n errorRetry: null,\n });\n }\n loader = this.createInternalLoader(context);\n\n // Override level/track timeout for LL-HLS requests\n // (the default of 10000ms is counter productive to blocking playlist reload requests)\n if (Number.isFinite(context.deliveryDirectives?.part)) {\n let levelDetails: LevelDetails | undefined;\n if (\n context.type === PlaylistContextType.LEVEL &&\n context.level !== null\n ) {\n levelDetails = this.hls.levels[context.level].details;\n } else if (\n context.type === PlaylistContextType.AUDIO_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.audioTracks[context.id].details;\n } else if (\n context.type === PlaylistContextType.SUBTITLE_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.subtitleTracks[context.id].details;\n }\n if (levelDetails) {\n const partTarget = levelDetails.partTarget;\n const targetDuration = levelDetails.targetduration;\n if (partTarget && targetDuration) {\n const maxLowLatencyPlaylistRefresh =\n Math.max(partTarget * 3, targetDuration * 0.8) * 1000;\n loadPolicy = Object.assign({}, loadPolicy, {\n maxTimeToFirstByteMs: Math.min(\n maxLowLatencyPlaylistRefresh,\n loadPolicy.maxTimeToFirstByteMs,\n ),\n maxLoadTimeMs: Math.min(\n maxLowLatencyPlaylistRefresh,\n loadPolicy.maxTimeToFirstByteMs,\n ),\n });\n }\n }\n }\n\n const legacyRetryCompatibility: RetryConfig | Record<string, void> =\n loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0,\n };\n\n const loaderCallbacks: LoaderCallbacks<PlaylistLoaderContext> = {\n onSuccess: (response, stats, context, networkDetails) => {\n const loader = this.getInternalLoader(context) as\n | Loader<PlaylistLoaderContext>\n | undefined;\n this.resetInternalLoader(context.type);\n\n const string = response.data as string;\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this.handleManifestParsingError(\n response,\n context,\n new Error('no EXTM3U delimiter'),\n networkDetails || null,\n stats,\n );\n return;\n }\n\n stats.parsing.start = performance.now();\n if (M3U8Parser.isMediaPlaylist(string)) {\n this.handleTrackOrLevelPlaylist(\n response,\n stats,\n context,\n networkDetails || null,\n loader,\n );\n } else {\n this.handleMasterPlaylist(response, stats, context, networkDetails);\n }\n },\n onError: (response, context, networkDetails, stats) => {\n this.handleNetworkError(\n context,\n networkDetails,\n false,\n response,\n stats,\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.handleNetworkError(\n context,\n networkDetails,\n true,\n undefined,\n stats,\n );\n },\n };\n\n // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n }\n\n private handleMasterPlaylist(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n ): void {\n const hls = this.hls;\n const string = response.data as string;\n\n const url = getResponseUrl(response, context);\n\n const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);\n\n if (parsedResult.playlistParsingError) {\n this.handleManifestParsingError(\n response,\n context,\n parsedResult.playlistParsingError,\n networkDetails,\n stats,\n );\n return;\n }\n\n const {\n contentSteering,\n levels,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList,\n } = parsedResult;\n\n this.variableList = variableList;\n\n const {\n AUDIO: audioTracks = [],\n SUBTITLES: subtitles,\n 'CLOSED-CAPTIONS': captions,\n } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n const embeddedAudioFound: boolean = audioTracks.some(\n (audioTrack) => !audioTrack.url,\n );\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (\n !embeddedAudioFound &&\n levels[0].audioCodec &&\n !levels[0].attrs.AUDIO\n ) {\n logger.log(\n '[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one',\n );\n audioTracks.unshift({\n type: 'main',\n name: 'main',\n groupId: 'main',\n default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: new AttrList({}) as MediaAttributes,\n bitrate: 0,\n url: '',\n });\n }\n }\n\n hls.trigger(Events.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n contentSteering,\n url,\n stats,\n networkDetails,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList,\n });\n }\n\n private handleTrackOrLevelPlaylist(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n loader: Loader<PlaylistLoaderContext> | undefined,\n ): void {\n const hls = this.hls;\n const { id, level, type } = context;\n\n const url = getResponseUrl(response, context);\n const levelUrlId = 0;\n const levelId = Number.isFinite(level as number)\n ? (level as number)\n : Number.isFinite(id as number)\n ? (id as number)\n : 0;\n const levelType = mapContextToLevelType(context);\n const levelDetails: LevelDetails = M3U8Parser.parseLevelPlaylist(\n response.data as string,\n url,\n levelId,\n levelType,\n levelUrlId,\n this.variableList,\n );\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === PlaylistContextType.MANIFEST) {\n const singleLevel: LevelParsed = {\n attrs: new AttrList({}),\n bitrate: 0,\n details: levelDetails,\n name: '',\n url,\n };\n\n hls.trigger(Events.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails,\n sessionData: null,\n sessionKeys: null,\n contentSteering: null,\n startTimeOffset: null,\n variableList: null,\n });\n }\n\n // save parsing time\n stats.parsing.end = performance.now();\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this.handlePlaylistLoaded(\n levelDetails,\n response,\n stats,\n context,\n networkDetails,\n loader,\n );\n }\n\n private handleManifestParsingError(\n response: LoaderResponse,\n context: PlaylistLoaderContext,\n error: Error,\n networkDetails: any,\n stats: LoaderStats,\n ): void {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: context.type === PlaylistContextType.MANIFEST,\n url: response.url,\n err: error,\n error,\n reason: error.message,\n response,\n context,\n networkDetails,\n stats,\n });\n }\n\n private handleNetworkError(\n context: PlaylistLoaderContext,\n networkDetails: any,\n timeout = false,\n response: { code: number; text: string } | undefined,\n stats: LoaderStats,\n ): void {\n let message = `A network ${\n timeout\n ? 'timeout'\n : 'error' + (response ? ' (status ' + response.code + ')' : '')\n } occurred while loading ${context.type}`;\n if (context.type === PlaylistContextType.LEVEL) {\n message += `: ${context.level} id: ${context.id}`;\n } else if (\n context.type === PlaylistContextType.AUDIO_TRACK ||\n context.type === PlaylistContextType.SUBTITLE_TRACK\n ) {\n message += ` id: ${context.id} group-id: \"${context.groupId}\"`;\n }\n const error = new Error(message);\n logger.warn(`[playlist-loader]: ${message}`);\n let details = ErrorDetails.UNKNOWN;\n let fatal = false;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n details = timeout\n ? ErrorDetails.MANIFEST_LOAD_TIMEOUT\n : ErrorDetails.MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case PlaylistContextType.LEVEL:\n details = timeout\n ? ErrorDetails.LEVEL_LOAD_TIMEOUT\n : ErrorDetails.LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.AUDIO_TRACK:\n details = timeout\n ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT\n : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n details = timeout\n ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT\n : ErrorDetails.SUBTITLE_LOAD_ERROR;\n fatal = false;\n break;\n }\n\n if (loader) {\n this.resetInternalLoader(context.type);\n }\n\n const errorData: ErrorData = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: context.url,\n loader,\n context,\n error,\n networkDetails,\n stats,\n };\n\n if (response) {\n const url = networkDetails?.url || context.url;\n errorData.response = { url, data: undefined as any, ...response };\n }\n\n this.hls.trigger(Events.ERROR, errorData);\n }\n\n private handlePlaylistLoaded(\n levelDetails: LevelDetails,\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n loader: Loader<PlaylistLoaderContext> | undefined,\n ): void {\n const hls = this.hls;\n const { type, level, id, groupId, deliveryDirectives } = context;\n const url = getResponseUrl(response, context);\n const parent = mapContextToLevelType(context);\n const levelIndex =\n typeof context.level === 'number' && parent === PlaylistLevelType.MAIN\n ? (level as number)\n : undefined;\n if (!levelDetails.fragments.length) {\n const error = new Error('No Segments found in Playlist');\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url,\n error,\n reason: error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats,\n });\n return;\n }\n if (!levelDetails.targetduration) {\n levelDetails.playlistParsingError = new Error('Missing Target Duration');\n }\n const error = levelDetails.playlistParsingError;\n if (error) {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_PARSING_ERROR,\n fatal: false,\n url,\n error,\n reason: error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats,\n });\n return;\n }\n\n if (levelDetails.live && loader) {\n if (loader.getCacheAge) {\n levelDetails.ageHeader = loader.getCacheAge() || 0;\n }\n if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {\n levelDetails.ageHeader = 0;\n }\n }\n\n switch (type) {\n case PlaylistContextType.MANIFEST:\n case PlaylistContextType.LEVEL:\n hls.trigger(Events.LEVEL_LOADED, {\n details: levelDetails,\n level: levelIndex || 0,\n id: id || 0,\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n case PlaylistContextType.AUDIO_TRACK:\n hls.trigger(Events.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n hls.trigger(Events.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n }\n }\n}\n\nexport default PlaylistLoader;\n","import { logger } from './logger';\n\nexport function sendAddTrackEvent(track: TextTrack, videoEl: HTMLMediaElement) {\n let event: Event;\n try {\n event = new Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n (event as any).track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function addCueToTrack(track: TextTrack, cue: VTTCue) {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues && !track.cues.getCueById(cue.id)) {\n try {\n track.addCue(cue);\n if (!track.cues.getCueById(cue.id)) {\n throw new Error(`addCue is failed for: ${cue}`);\n }\n } catch (err) {\n logger.debug(`[texttrack-utils]: ${err}`);\n try {\n const textTrackCue = new (self.TextTrackCue as any)(\n cue.startTime,\n cue.endTime,\n cue.text,\n );\n textTrackCue.id = cue.id;\n track.addCue(textTrackCue);\n } catch (err2) {\n logger.debug(\n `[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`,\n );\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\nexport function clearCurrentCues(track: TextTrack) {\n // When track.mode is disabled, track.cues will be null.\n // To guarantee the removal of cues, we need to temporarily\n // change the mode to hidden\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues) {\n for (let i = track.cues.length; i--; ) {\n track.removeCue(track.cues[i]);\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\nexport function removeCuesInRange(\n track: TextTrack,\n start: number,\n end: number,\n predicate?: (cue: TextTrackCue) => boolean,\n) {\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n\n if (track.cues && track.cues.length > 0) {\n const cues = getCuesInRange(track.cues, start, end);\n for (let i = 0; i < cues.length; i++) {\n if (!predicate || predicate(cues[i])) {\n track.removeCue(cues[i]);\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\n// Find first cue starting after given time.\n// Modified version of binary search O(log(n)).\nfunction getFirstCueIndexAfterTime(\n cues: TextTrackCueList | TextTrackCue[],\n time: number,\n): number {\n // If first cue starts after time, start there\n if (time < cues[0].startTime) {\n return 0;\n }\n // If the last cue ends before time there is no overlap\n const len = cues.length - 1;\n if (time > cues[len].endTime) {\n return -1;\n }\n\n let left = 0;\n let right = len;\n\n while (left <= right) {\n const mid = Math.floor((right + left) / 2);\n\n if (time < cues[mid].startTime) {\n right = mid - 1;\n } else if (time > cues[mid].startTime && left < len) {\n left = mid + 1;\n } else {\n // If it's not lower or higher, it must be equal.\n return mid;\n }\n }\n // At this point, left and right have swapped.\n // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n return cues[left].startTime - time < time - cues[right].startTime\n ? left\n : right;\n}\n\nexport function getCuesInRange(\n cues: TextTrackCueList | TextTrackCue[],\n start: number,\n end: number,\n): TextTrackCue[] {\n const cuesFound: TextTrackCue[] = [];\n const firstCueInRange = getFirstCueIndexAfterTime(cues, start);\n if (firstCueInRange > -1) {\n for (let i = firstCueInRange, len = cues.length; i < len; i++) {\n const cue = cues[i];\n if (cue.startTime >= start && cue.endTime <= end) {\n cuesFound.push(cue);\n } else if (cue.startTime > end) {\n return cuesFound;\n }\n }\n }\n return cuesFound;\n}\n\nexport function filterSubtitleTracks(\n textTrackList: TextTrackList,\n): TextTrack[] {\n const tracks: TextTrack[] = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if (\n (track.kind === 'subtitles' || track.kind === 'captions') &&\n track.label\n ) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n","import type { RationalTimestamp } from '../utils/timescale-conversion';\n\nexport interface Demuxer {\n demux(\n data: Uint8Array,\n timeOffset: number,\n isSampleAes?: boolean,\n flush?: boolean,\n ): DemuxerResult;\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult>;\n flush(timeOffset?: number): DemuxerResult | Promise<DemuxerResult>;\n destroy(): void;\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n );\n resetTimeStamp(defaultInitPTS?: RationalTimestamp | null): void;\n resetContiguity(): void;\n}\n\nexport interface DemuxerResult {\n audioTrack: DemuxedAudioTrack;\n videoTrack: DemuxedVideoTrackBase;\n id3Track: DemuxedMetadataTrack;\n textTrack: DemuxedUserdataTrack;\n}\n\nexport interface DemuxedTrack {\n type: string;\n id: number;\n pid: number;\n inputTimeScale: number;\n sequenceNumber: number;\n samples:\n | AudioSample[]\n | VideoSample[]\n | MetadataSample[]\n | UserdataSample[]\n | Uint8Array;\n timescale?: number;\n container?: string;\n dropped: number;\n duration?: number;\n pesData?: ElementaryStreamData | null;\n codec?: string;\n}\n\nexport interface PassthroughTrack extends DemuxedTrack {\n sampleDuration: number;\n samples: Uint8Array;\n timescale: number;\n duration: number;\n codec: string;\n}\nexport interface DemuxedAudioTrack extends DemuxedTrack {\n config?: number[] | Uint8Array;\n samplerate?: number;\n segmentCodec?: string;\n channelCount?: number;\n manifestCodec?: string;\n samples: AudioSample[];\n}\n\nexport interface DemuxedVideoTrackBase extends DemuxedTrack {\n width?: number;\n height?: number;\n pixelRatio?: [number, number];\n audFound?: boolean;\n pps?: Uint8Array[];\n sps?: Uint8Array[];\n naluState?: number;\n segmentCodec?: string;\n manifestCodec?: string;\n samples: VideoSample[] | Uint8Array;\n}\n\nexport interface DemuxedVideoTrack extends DemuxedVideoTrackBase {\n samples: VideoSample[];\n}\n\nexport interface DemuxedMetadataTrack extends DemuxedTrack {\n samples: MetadataSample[];\n}\n\nexport interface DemuxedUserdataTrack extends DemuxedTrack {\n samples: UserdataSample[];\n}\n\nexport const enum MetadataSchema {\n audioId3 = 'org.id3',\n dateRange = 'com.apple.quicktime.HLS',\n emsg = 'https://aomedia.org/emsg/ID3',\n}\nexport interface MetadataSample {\n pts: number;\n dts: number;\n duration: number;\n len?: number;\n data: Uint8Array;\n type: MetadataSchema;\n}\n\nexport interface UserdataSample {\n pts: number;\n bytes?: Uint8Array;\n type?: number;\n payloadType?: number;\n uuid?: string;\n userData?: string;\n userDataBytes?: Uint8Array;\n}\n\nexport interface VideoSample {\n dts: number;\n pts: number;\n key: boolean;\n frame: boolean;\n units: VideoSampleUnit[];\n debug: string;\n length: number;\n}\n\nexport interface VideoSampleUnit {\n data: Uint8Array;\n type: number;\n state?: number;\n}\n\nexport type AudioSample = {\n unit: Uint8Array;\n pts: number;\n};\n\nexport type AudioFrame = {\n sample: AudioSample;\n length: number;\n missing: number;\n};\n\nexport interface ElementaryStreamData {\n data: Uint8Array[];\n size: number;\n}\n\nexport interface KeyData {\n method: string;\n key: Uint8Array;\n iv: Uint8Array;\n}\n","import { Events } from '../events';\nimport {\n sendAddTrackEvent,\n clearCurrentCues,\n removeCuesInRange,\n} from '../utils/texttrack-utils';\nimport * as ID3 from '../demux/id3';\nimport {\n DateRange,\n isDateRangeCueAttribute,\n isSCTE35Attribute,\n} from '../loader/date-range';\nimport { MetadataSchema } from '../types/demuxer';\nimport type {\n BufferFlushingData,\n FragParsingMetadataData,\n LevelUpdatedData,\n MediaAttachedData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\n\ndeclare global {\n interface Window {\n WebKitDataCue: VTTCue | void;\n }\n}\n\nconst MIN_CUE_DURATION = 0.25;\n\nfunction getCueClass(): typeof VTTCue | typeof TextTrackCue | undefined {\n if (typeof self === 'undefined') return undefined;\n return self.VTTCue || self.TextTrackCue;\n}\n\nfunction createCueWithDataFields(\n Cue: typeof VTTCue | typeof TextTrackCue,\n startTime: number,\n endTime: number,\n data: Object,\n type?: string,\n): VTTCue | TextTrackCue | undefined {\n let cue = new Cue(startTime, endTime, '');\n try {\n (cue as any).value = data;\n if (type) {\n (cue as any).type = type;\n }\n } catch (e) {\n cue = new Cue(\n startTime,\n endTime,\n JSON.stringify(type ? { type, ...data } : data),\n );\n }\n return cue;\n}\n\n// VTTCue latest draft allows an infinite duration, fallback\n// to MAX_VALUE if necessary\nconst MAX_CUE_ENDTIME = (() => {\n const Cue = getCueClass();\n try {\n Cue && new Cue(0, Number.POSITIVE_INFINITY, '');\n } catch (e) {\n return Number.MAX_VALUE;\n }\n return Number.POSITIVE_INFINITY;\n})();\n\nfunction dateRangeDateToTimelineSeconds(date: Date, offset: number): number {\n return date.getTime() / 1000 - offset;\n}\n\nfunction hexToArrayBuffer(str): ArrayBuffer {\n return Uint8Array.from(\n str\n .replace(/^0x/, '')\n .replace(/([\\da-fA-F]{2}) ?/g, '0x$1 ')\n .replace(/ +$/, '')\n .split(' '),\n ).buffer;\n}\nclass ID3TrackController implements ComponentAPI {\n private hls: Hls;\n private id3Track: TextTrack | null = null;\n private media: HTMLMediaElement | null = null;\n private dateRangeCuesAppended: Record<\n string,\n {\n cues: Record<string, VTTCue | TextTrackCue>;\n dateRange: DateRange;\n durationKnown: boolean;\n }\n > = {};\n\n constructor(hls) {\n this.hls = hls;\n this._registerListeners();\n }\n\n destroy() {\n this._unregisterListeners();\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n // @ts-ignore\n this.hls = null;\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n // Add ID3 metatadata text track.\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ): void {\n this.media = data.media;\n }\n\n protected onMediaDetaching(): void {\n if (!this.id3Track) {\n return;\n }\n clearCurrentCues(this.id3Track);\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n }\n\n private onManifestLoading() {\n this.dateRangeCuesAppended = {};\n }\n\n createTrack(media: HTMLMediaElement): TextTrack {\n const track = this.getID3Track(media.textTracks) as TextTrack;\n track.mode = 'hidden';\n return track;\n }\n\n getID3Track(textTracks: TextTrackList): TextTrack | void {\n if (!this.media) {\n return;\n }\n for (let i = 0; i < textTracks.length; i++) {\n const textTrack: TextTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n }\n\n onFragParsingMetadata(\n event: Events.FRAG_PARSING_METADATA,\n data: FragParsingMetadataData,\n ) {\n if (!this.media) {\n return;\n }\n\n const {\n hls: {\n config: { enableEmsgMetadataCues, enableID3MetadataCues },\n },\n } = this;\n if (!enableEmsgMetadataCues && !enableID3MetadataCues) {\n return;\n }\n\n const { samples } = data;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const Cue = getCueClass();\n if (!Cue) {\n return;\n }\n\n for (let i = 0; i < samples.length; i++) {\n const type = samples[i].type;\n if (\n (type === MetadataSchema.emsg && !enableEmsgMetadataCues) ||\n !enableID3MetadataCues\n ) {\n continue;\n }\n\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n const startTime = samples[i].pts;\n let endTime: number = startTime + samples[i].duration;\n\n if (endTime > MAX_CUE_ENDTIME) {\n endTime = MAX_CUE_ENDTIME;\n }\n\n const timeDiff = endTime - startTime;\n if (timeDiff <= 0) {\n endTime = startTime + MIN_CUE_DURATION;\n }\n\n for (let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n // add a bounds to any unbounded cues\n this.updateId3CueEnds(startTime, type);\n const cue = createCueWithDataFields(\n Cue,\n startTime,\n endTime,\n frame,\n type,\n );\n if (cue) {\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n }\n\n updateId3CueEnds(startTime: number, type: MetadataSchema) {\n const cues = this.id3Track?.cues;\n if (cues) {\n for (let i = cues.length; i--; ) {\n const cue = cues[i] as any;\n if (\n cue.type === type &&\n cue.startTime < startTime &&\n cue.endTime === MAX_CUE_ENDTIME\n ) {\n cue.endTime = startTime;\n }\n }\n }\n }\n\n onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { startOffset, endOffset, type }: BufferFlushingData,\n ) {\n const { id3Track, hls } = this;\n if (!hls) {\n return;\n }\n\n const {\n config: { enableEmsgMetadataCues, enableID3MetadataCues },\n } = hls;\n if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {\n let predicate;\n\n if (type === 'audio') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues;\n } else if (type === 'video') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues;\n } else {\n predicate = (cue) =>\n ((cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues) ||\n ((cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues);\n }\n removeCuesInRange(id3Track, startOffset, endOffset, predicate);\n }\n }\n\n onLevelUpdated(event: Events.LEVEL_UPDATED, { details }: LevelUpdatedData) {\n if (\n !this.media ||\n !details.hasProgramDateTime ||\n !this.hls.config.enableDateRangeMetadataCues\n ) {\n return;\n }\n const { dateRangeCuesAppended, id3Track } = this;\n const { dateRanges } = details;\n const ids = Object.keys(dateRanges);\n // Remove cues from track not found in details.dateRanges\n if (id3Track) {\n const idsToRemove = Object.keys(dateRangeCuesAppended).filter(\n (id) => !ids.includes(id),\n );\n for (let i = idsToRemove.length; i--; ) {\n const id = idsToRemove[i];\n Object.keys(dateRangeCuesAppended[id].cues).forEach((key) => {\n id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);\n });\n delete dateRangeCuesAppended[id];\n }\n }\n // Exit if the playlist does not have Date Ranges or does not have Program Date Time\n const lastFragment = details.fragments[details.fragments.length - 1];\n if (ids.length === 0 || !Number.isFinite(lastFragment?.programDateTime)) {\n return;\n }\n\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const dateTimeOffset =\n (lastFragment.programDateTime as number) / 1000 - lastFragment.start;\n const Cue = getCueClass();\n\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i];\n const dateRange = dateRanges[id];\n const startTime = dateRangeDateToTimelineSeconds(\n dateRange.startDate,\n dateTimeOffset,\n );\n\n // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)\n const appendedDateRangeCues = dateRangeCuesAppended[id];\n const cues = appendedDateRangeCues?.cues || {};\n let durationKnown = appendedDateRangeCues?.durationKnown || false;\n let endTime = MAX_CUE_ENDTIME;\n const endDate = dateRange.endDate;\n if (endDate) {\n endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);\n durationKnown = true;\n } else if (dateRange.endOnNext && !durationKnown) {\n const nextDateRangeWithSameClass = ids.reduce(\n (candidateDateRange: DateRange | null, id) => {\n if (id !== dateRange.id) {\n const otherDateRange = dateRanges[id];\n if (\n otherDateRange.class === dateRange.class &&\n otherDateRange.startDate > dateRange.startDate &&\n (!candidateDateRange ||\n dateRange.startDate < candidateDateRange.startDate)\n ) {\n return otherDateRange;\n }\n }\n return candidateDateRange;\n },\n null,\n );\n if (nextDateRangeWithSameClass) {\n endTime = dateRangeDateToTimelineSeconds(\n nextDateRangeWithSameClass.startDate,\n dateTimeOffset,\n );\n durationKnown = true;\n }\n }\n\n // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)\n // This is to emulate Safari HLS playback handling of DateRange tags\n const attributes = Object.keys(dateRange.attr);\n for (let j = 0; j < attributes.length; j++) {\n const key = attributes[j];\n if (!isDateRangeCueAttribute(key)) {\n continue;\n }\n const cue = cues[key];\n if (cue) {\n if (durationKnown && !appendedDateRangeCues.durationKnown) {\n cue.endTime = endTime;\n }\n } else if (Cue) {\n let data = dateRange.attr[key];\n if (isSCTE35Attribute(key)) {\n data = hexToArrayBuffer(data);\n }\n const cue = createCueWithDataFields(\n Cue,\n startTime,\n endTime,\n { key, data },\n MetadataSchema.dateRange,\n );\n if (cue) {\n cue.id = id;\n this.id3Track.addCue(cue);\n cues[key] = cue;\n }\n }\n }\n\n // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes\n dateRangeCuesAppended[id] = {\n cues,\n dateRange,\n durationKnown,\n };\n }\n }\n}\n\nexport default ID3TrackController;\n","import { LevelDetails } from '../loader/level-details';\nimport { ErrorDetails } from '../errors';\nimport { Events } from '../events';\nimport type {\n ErrorData,\n LevelUpdatedData,\n MediaAttachingData,\n} from '../types/events';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\n\nexport default class LatencyController implements ComponentAPI {\n private hls: Hls;\n private readonly config: HlsConfig;\n private media: HTMLMediaElement | null = null;\n private levelDetails: LevelDetails | null = null;\n private currentTime: number = 0;\n private stallCount: number = 0;\n private _latency: number | null = null;\n private timeupdateHandler = () => this.timeupdate();\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n\n get latency(): number {\n return this._latency || 0;\n }\n\n get maxLatency(): number {\n const { config, levelDetails } = this;\n if (config.liveMaxLatencyDuration !== undefined) {\n return config.liveMaxLatencyDuration;\n }\n return levelDetails\n ? config.liveMaxLatencyDurationCount * levelDetails.targetduration\n : 0;\n }\n\n get targetLatency(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n const { holdBack, partHoldBack, targetduration } = levelDetails;\n const { liveSyncDuration, liveSyncDurationCount, lowLatencyMode } =\n this.config;\n const userConfig = this.hls.userConfig;\n let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;\n if (\n userConfig.liveSyncDuration ||\n userConfig.liveSyncDurationCount ||\n targetLatency === 0\n ) {\n targetLatency =\n liveSyncDuration !== undefined\n ? liveSyncDuration\n : liveSyncDurationCount * targetduration;\n }\n const maxLiveSyncOnStallIncrease = targetduration;\n const liveSyncOnStallIncrease = 1.0;\n return (\n targetLatency +\n Math.min(\n this.stallCount * liveSyncOnStallIncrease,\n maxLiveSyncOnStallIncrease,\n )\n );\n }\n\n get liveSyncPosition(): number | null {\n const liveEdge = this.estimateLiveEdge();\n const targetLatency = this.targetLatency;\n const levelDetails = this.levelDetails;\n if (liveEdge === null || targetLatency === null || levelDetails === null) {\n return null;\n }\n const edge = levelDetails.edge;\n const syncPosition = liveEdge - targetLatency - this.edgeStalled;\n const min = edge - levelDetails.totalduration;\n const max =\n edge -\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration);\n return Math.min(Math.max(min, syncPosition), max);\n }\n\n get drift(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 1;\n }\n return levelDetails.drift;\n }\n\n get edgeStalled(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 0;\n }\n const maxLevelUpdateAge =\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration) * 3;\n return Math.max(levelDetails.age - maxLevelUpdateAge, 0);\n }\n\n private get forwardBufferLength(): number {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return 0;\n }\n const bufferedRanges = media.buffered.length;\n return (\n (bufferedRanges\n ? media.buffered.end(bufferedRanges - 1)\n : levelDetails.edge) - this.currentTime\n );\n }\n\n public destroy(): void {\n this.unregisterListeners();\n this.onMediaDetaching();\n this.levelDetails = null;\n // @ts-ignore\n this.hls = this.timeupdateHandler = null;\n }\n\n private registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n this.hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n this.hls.off(Events.ERROR, this.onError, this);\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachingData,\n ) {\n this.media = data.media;\n this.media.addEventListener('timeupdate', this.timeupdateHandler);\n }\n\n private onMediaDetaching() {\n if (this.media) {\n this.media.removeEventListener('timeupdate', this.timeupdateHandler);\n this.media = null;\n }\n }\n\n private onManifestLoading() {\n this.levelDetails = null;\n this._latency = null;\n this.stallCount = 0;\n }\n\n private onLevelUpdated(\n event: Events.LEVEL_UPDATED,\n { details }: LevelUpdatedData,\n ) {\n this.levelDetails = details;\n if (details.advanced) {\n this.timeupdate();\n }\n if (!details.live && this.media) {\n this.media.removeEventListener('timeupdate', this.timeupdateHandler);\n }\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {\n return;\n }\n this.stallCount++;\n if (this.levelDetails?.live) {\n logger.warn(\n '[playback-rate-controller]: Stall detected, adjusting target latency',\n );\n }\n }\n\n private timeupdate() {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return;\n }\n this.currentTime = media.currentTime;\n\n const latency = this.computeLatency();\n if (latency === null) {\n return;\n }\n this._latency = latency;\n\n // Adapt playbackRate to meet target latency in low-latency mode\n const { lowLatencyMode, maxLiveSyncPlaybackRate } = this.config;\n if (\n !lowLatencyMode ||\n maxLiveSyncPlaybackRate === 1 ||\n !levelDetails.live\n ) {\n return;\n }\n const targetLatency = this.targetLatency;\n if (targetLatency === null) {\n return;\n }\n const distanceFromTarget = latency - targetLatency;\n // Only adjust playbackRate when within one target duration of targetLatency\n // and more than one second from under-buffering.\n // Playback further than one target duration from target can be considered DVR playback.\n const liveMinLatencyDuration = Math.min(\n this.maxLatency,\n targetLatency + levelDetails.targetduration,\n );\n const inLiveRange = distanceFromTarget < liveMinLatencyDuration;\n\n if (\n inLiveRange &&\n distanceFromTarget > 0.05 &&\n this.forwardBufferLength > 1\n ) {\n const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));\n const rate =\n Math.round(\n (2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled))) *\n 20,\n ) / 20;\n media.playbackRate = Math.min(max, Math.max(1, rate));\n } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {\n media.playbackRate = 1;\n }\n }\n\n private estimateLiveEdge(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n return levelDetails.edge + levelDetails.age;\n }\n\n private computeLatency(): number | null {\n const liveEdge = this.estimateLiveEdge();\n if (liveEdge === null) {\n return null;\n }\n return liveEdge - this.currentTime;\n }\n}\n","import type { MediaPlaylist } from './media-playlist';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { AttrList } from '../utils/attr-list';\nimport type { MediaDecodingInfo } from '../utils/mediacapabilities-helper';\n\nexport interface LevelParsed {\n attrs: LevelAttributes;\n audioCodec?: string;\n bitrate: number;\n details?: LevelDetails;\n height?: number;\n id?: number;\n name: string;\n textCodec?: string;\n unknownCodecs?: string[];\n url: string;\n videoCodec?: string;\n width?: number;\n}\n\nexport interface LevelAttributes extends AttrList {\n 'ALLOWED-CPC'?: string;\n AUDIO?: string;\n 'AVERAGE-BANDWIDTH'?: string;\n BANDWIDTH?: string;\n 'CLOSED-CAPTIONS'?: string;\n CODECS?: string;\n 'FRAME-RATE'?: string;\n 'HDCP-LEVEL'?: 'TYPE-0' | 'TYPE-1' | 'NONE';\n 'PATHWAY-ID'?: string;\n RESOLUTION?: string;\n SCORE?: string;\n 'STABLE-VARIANT-ID'?: string;\n SUBTITLES?: string;\n 'SUPPLEMENTAL-CODECS'?: string;\n VIDEO?: string;\n 'VIDEO-RANGE'?: VideoRange;\n}\n\nexport const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null] as const;\nexport type HdcpLevel = (typeof HdcpLevels)[number];\n\nexport function isHdcpLevel(value: any): value is HdcpLevel {\n return HdcpLevels.indexOf(value) > -1;\n}\n\nexport const VideoRangeValues = ['SDR', 'PQ', 'HLG'] as const;\nexport type VideoRange = (typeof VideoRangeValues)[number];\n\nexport function isVideoRange(value: any): value is VideoRange {\n return !!value && VideoRangeValues.indexOf(value) > -1;\n}\n\nexport type VariableMap = Record<string, string>;\n\nexport const enum HlsSkip {\n No = '',\n Yes = 'YES',\n v2 = 'v2',\n}\n\nexport function getSkipValue(details: LevelDetails): HlsSkip {\n const { canSkipUntil, canSkipDateRanges, age } = details;\n // A Client SHOULD NOT request a Playlist Delta Update unless it already\n // has a version of the Playlist that is no older than one-half of the Skip Boundary.\n // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7\n const playlistRecentEnough = age < canSkipUntil / 2;\n if (canSkipUntil && playlistRecentEnough) {\n if (canSkipDateRanges) {\n return HlsSkip.v2;\n }\n return HlsSkip.Yes;\n }\n return HlsSkip.No;\n}\n\nexport class HlsUrlParameters {\n msn?: number;\n part?: number;\n skip?: HlsSkip;\n\n constructor(msn?: number, part?: number, skip?: HlsSkip) {\n this.msn = msn;\n this.part = part;\n this.skip = skip;\n }\n\n addDirectives(uri: string): string | never {\n const url: URL = new self.URL(uri);\n if (this.msn !== undefined) {\n url.searchParams.set('_HLS_msn', this.msn.toString());\n }\n if (this.part !== undefined) {\n url.searchParams.set('_HLS_part', this.part.toString());\n }\n if (this.skip) {\n url.searchParams.set('_HLS_skip', this.skip);\n }\n return url.href;\n }\n}\n\nexport class Level {\n public readonly _attrs: LevelAttributes[];\n public readonly audioCodec: string | undefined;\n public readonly bitrate: number;\n public readonly codecSet: string;\n public readonly url: string[];\n public readonly frameRate: number;\n public readonly height: number;\n public readonly id: number;\n public readonly name: string;\n public readonly videoCodec: string | undefined;\n public readonly width: number;\n public details?: LevelDetails;\n public fragmentError: number = 0;\n public loadError: number = 0;\n public loaded?: { bytes: number; duration: number };\n public realBitrate: number = 0;\n public supportedPromise?: Promise<MediaDecodingInfo>;\n public supportedResult?: MediaDecodingInfo;\n private _avgBitrate: number = 0;\n private _audioGroups?: (string | undefined)[];\n private _subtitleGroups?: (string | undefined)[];\n // Deprecated (retained for backwards compatibility)\n private readonly _urlId: number = 0;\n\n constructor(data: LevelParsed | MediaPlaylist) {\n this.url = [data.url];\n this._attrs = [data.attrs];\n this.bitrate = data.bitrate;\n if (data.details) {\n this.details = data.details;\n }\n this.id = data.id || 0;\n this.name = data.name;\n this.width = data.width || 0;\n this.height = data.height || 0;\n this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);\n this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');\n this.audioCodec = data.audioCodec;\n this.videoCodec = data.videoCodec;\n this.codecSet = [data.videoCodec, data.audioCodec]\n .filter((c) => !!c)\n .map((s: string) => s.substring(0, 4))\n .join(',');\n this.addGroupId('audio', data.attrs.AUDIO);\n this.addGroupId('text', data.attrs.SUBTITLES);\n }\n\n get maxBitrate(): number {\n return Math.max(this.realBitrate, this.bitrate);\n }\n\n get averageBitrate(): number {\n return this._avgBitrate || this.realBitrate || this.bitrate;\n }\n\n get attrs(): LevelAttributes {\n return this._attrs[0];\n }\n\n get codecs(): string {\n return this.attrs.CODECS || '';\n }\n\n get pathwayId(): string {\n return this.attrs['PATHWAY-ID'] || '.';\n }\n\n get videoRange(): VideoRange {\n return this.attrs['VIDEO-RANGE'] || 'SDR';\n }\n\n get score(): number {\n return this.attrs.optionalFloat('SCORE', 0);\n }\n\n get uri(): string {\n return this.url[0] || '';\n }\n\n hasAudioGroup(groupId: string | undefined): boolean {\n return hasGroup(this._audioGroups, groupId);\n }\n\n hasSubtitleGroup(groupId: string | undefined): boolean {\n return hasGroup(this._subtitleGroups, groupId);\n }\n\n get audioGroups(): (string | undefined)[] | undefined {\n return this._audioGroups;\n }\n\n get subtitleGroups(): (string | undefined)[] | undefined {\n return this._subtitleGroups;\n }\n\n addGroupId(type: string, groupId: string | undefined) {\n if (!groupId) {\n return;\n }\n if (type === 'audio') {\n let audioGroups = this._audioGroups;\n if (!audioGroups) {\n audioGroups = this._audioGroups = [];\n }\n if (audioGroups.indexOf(groupId) === -1) {\n audioGroups.push(groupId);\n }\n } else if (type === 'text') {\n let subtitleGroups = this._subtitleGroups;\n if (!subtitleGroups) {\n subtitleGroups = this._subtitleGroups = [];\n }\n if (subtitleGroups.indexOf(groupId) === -1) {\n subtitleGroups.push(groupId);\n }\n }\n }\n\n // Deprecated methods (retained for backwards compatibility)\n get urlId(): number {\n return 0;\n }\n\n set urlId(value: number) {}\n\n get audioGroupIds(): (string | undefined)[] | undefined {\n return this.audioGroups ? [this.audioGroupId] : undefined;\n }\n\n get textGroupIds(): (string | undefined)[] | undefined {\n return this.subtitleGroups ? [this.textGroupId] : undefined;\n }\n\n get audioGroupId(): string | undefined {\n return this.audioGroups?.[0];\n }\n\n get textGroupId(): string | undefined {\n return this.subtitleGroups?.[0];\n }\n\n addFallback() {}\n}\n\nfunction hasGroup(\n groups: (string | undefined)[] | undefined,\n groupId: string | undefined,\n): boolean {\n if (!groupId || !groups) {\n return false;\n }\n return groups.indexOf(groupId) !== -1;\n}\n","/**\n * Provides methods dealing with playlist sliding and drift\n */\n\nimport { logger } from './logger';\nimport { Fragment, Part } from '../loader/fragment';\nimport { LevelDetails } from '../loader/level-details';\nimport type { Level } from '../types/level';\nimport { DateRange } from '../loader/date-range';\n\ntype FragmentIntersection = (oldFrag: Fragment, newFrag: Fragment) => void;\ntype PartIntersection = (oldPart: Part, newPart: Part) => void;\n\nexport function updatePTS(\n fragments: Fragment[],\n fromIdx: number,\n toIdx: number,\n): void {\n const fragFrom = fragments[fromIdx];\n const fragTo = fragments[toIdx];\n updateFromToPTS(fragFrom, fragTo);\n}\n\nfunction updateFromToPTS(fragFrom: Fragment, fragTo: Fragment) {\n const fragToPTS = fragTo.startPTS as number;\n // if we know startPTS[toIdx]\n if (Number.isFinite(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n let duration: number = 0;\n let frag: Fragment;\n if (fragTo.sn > fragFrom.sn) {\n duration = fragToPTS - fragFrom.start;\n frag = fragFrom;\n } else {\n duration = fragFrom.start - fragToPTS;\n frag = fragTo;\n }\n if (frag.duration !== duration) {\n frag.duration = duration;\n }\n // we dont know startPTS[toIdx]\n } else if (fragTo.sn > fragFrom.sn) {\n const contiguous = fragFrom.cc === fragTo.cc;\n // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS\n if (contiguous && fragFrom.minEndPTS) {\n fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);\n } else {\n fragTo.start = fragFrom.start + fragFrom.duration;\n }\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n}\n\nexport function updateFragPTSDTS(\n details: LevelDetails | undefined,\n frag: Fragment,\n startPTS: number,\n endPTS: number,\n startDTS: number,\n endDTS: number,\n): number {\n const parsedMediaDuration = endPTS - startPTS;\n if (parsedMediaDuration <= 0) {\n logger.warn('Fragment should have a positive duration', frag);\n endPTS = startPTS + frag.duration;\n endDTS = startDTS + frag.duration;\n }\n let maxStartPTS = startPTS;\n let minEndPTS = endPTS;\n const fragStartPts = frag.startPTS as number;\n const fragEndPts = frag.endPTS as number;\n if (Number.isFinite(fragStartPts)) {\n // delta PTS between audio and video\n const deltaPTS = Math.abs(fragStartPts - startPTS);\n if (!Number.isFinite(frag.deltaPTS as number)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS as number);\n }\n\n maxStartPTS = Math.max(startPTS, fragStartPts);\n startPTS = Math.min(startPTS, fragStartPts);\n startDTS = Math.min(startDTS, frag.startDTS);\n\n minEndPTS = Math.min(endPTS, fragEndPts);\n endPTS = Math.max(endPTS, fragEndPts);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n if (frag.start !== 0) {\n frag.start = startPTS;\n }\n frag.duration = endPTS - frag.start;\n frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.startDTS = startDTS;\n frag.endPTS = endPTS;\n frag.minEndPTS = minEndPTS;\n frag.endDTS = endDTS;\n\n const sn = frag.sn as number; // 'initSegment'\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n let i;\n const fragIdx = sn - details.startSN;\n const fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updateFromToPTS(fragments[i], fragments[i - 1]);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updateFromToPTS(fragments[i], fragments[i + 1]);\n }\n if (details.fragmentHint) {\n updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);\n }\n\n details.PTSKnown = details.alignedSliding = true;\n return drift;\n}\n\nexport function mergeDetails(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n): void {\n // Track the last initSegment processed. Initialize it to the last one on the timeline.\n let currentInitSegment: Fragment | null = null;\n const oldFragments = oldDetails.fragments;\n for (let i = oldFragments.length - 1; i >= 0; i--) {\n const oldInit = oldFragments[i].initSegment;\n if (oldInit) {\n currentInitSegment = oldInit;\n break;\n }\n }\n\n if (oldDetails.fragmentHint) {\n // prevent PTS and duration from being adjusted on the next hint\n delete oldDetails.fragmentHint.endPTS;\n }\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n let ccOffset = 0;\n let PTSFrag;\n mapFragmentIntersection(\n oldDetails,\n newDetails,\n (oldFrag: Fragment, newFrag: Fragment) => {\n if (oldFrag.relurl) {\n // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.\n // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end\n // of the playlist.\n ccOffset = oldFrag.cc - newFrag.cc;\n }\n if (\n Number.isFinite(oldFrag.startPTS) &&\n Number.isFinite(oldFrag.endPTS)\n ) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS as number;\n newFrag.startDTS = oldFrag.startDTS;\n newFrag.maxStartPTS = oldFrag.maxStartPTS;\n\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.endDTS = oldFrag.endDTS;\n newFrag.minEndPTS = oldFrag.minEndPTS;\n newFrag.duration =\n (oldFrag.endPTS as number) - (oldFrag.startPTS as number);\n\n if (newFrag.duration) {\n PTSFrag = newFrag;\n }\n\n // PTS is known when any segment has startPTS and endPTS\n newDetails.PTSKnown = newDetails.alignedSliding = true;\n }\n newFrag.elementaryStreams = oldFrag.elementaryStreams;\n newFrag.loader = oldFrag.loader;\n newFrag.stats = oldFrag.stats;\n if (oldFrag.initSegment) {\n newFrag.initSegment = oldFrag.initSegment;\n currentInitSegment = oldFrag.initSegment;\n }\n },\n );\n\n if (currentInitSegment) {\n const fragmentsToCheck = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n fragmentsToCheck.forEach((frag) => {\n if (\n frag &&\n (!frag.initSegment ||\n frag.initSegment.relurl === currentInitSegment?.relurl)\n ) {\n frag.initSegment = currentInitSegment;\n }\n });\n }\n\n if (newDetails.skippedSegments) {\n newDetails.deltaUpdateFailed = newDetails.fragments.some((frag) => !frag);\n if (newDetails.deltaUpdateFailed) {\n logger.warn(\n '[level-helper] Previous playlist missing segments skipped in delta playlist',\n );\n for (let i = newDetails.skippedSegments; i--; ) {\n newDetails.fragments.shift();\n }\n newDetails.startSN = newDetails.fragments[0].sn as number;\n newDetails.startCC = newDetails.fragments[0].cc;\n } else if (newDetails.canSkipDateRanges) {\n newDetails.dateRanges = mergeDateRanges(\n oldDetails.dateRanges,\n newDetails.dateRanges,\n newDetails.recentlyRemovedDateranges,\n );\n }\n }\n\n const newFragments = newDetails.fragments;\n if (ccOffset) {\n logger.warn('discontinuity sliding from playlist, take drift into account');\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n if (newDetails.skippedSegments) {\n newDetails.startCC = newDetails.fragments[0].cc;\n }\n\n // Merge parts\n mapPartIntersection(\n oldDetails.partList,\n newDetails.partList,\n (oldPart: Part, newPart: Part) => {\n newPart.elementaryStreams = oldPart.elementaryStreams;\n newPart.stats = oldPart.stats;\n },\n );\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(\n newDetails,\n PTSFrag,\n PTSFrag.startPTS,\n PTSFrag.endPTS,\n PTSFrag.startDTS,\n PTSFrag.endDTS,\n );\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n\n if (newFragments.length) {\n newDetails.totalduration = newDetails.edge - newFragments[0].start;\n }\n\n newDetails.driftStartTime = oldDetails.driftStartTime;\n newDetails.driftStart = oldDetails.driftStart;\n const advancedDateTime = newDetails.advancedDateTime;\n if (newDetails.advanced && advancedDateTime) {\n const edge = newDetails.edge;\n if (!newDetails.driftStart) {\n newDetails.driftStartTime = advancedDateTime;\n newDetails.driftStart = edge;\n }\n newDetails.driftEndTime = advancedDateTime;\n newDetails.driftEnd = edge;\n } else {\n newDetails.driftEndTime = oldDetails.driftEndTime;\n newDetails.driftEnd = oldDetails.driftEnd;\n newDetails.advancedDateTime = oldDetails.advancedDateTime;\n }\n}\n\nfunction mergeDateRanges(\n oldDateRanges: Record<string, DateRange>,\n deltaDateRanges: Record<string, DateRange>,\n recentlyRemovedDateranges: string[] | undefined,\n): Record<string, DateRange> {\n const dateRanges = Object.assign({}, oldDateRanges);\n if (recentlyRemovedDateranges) {\n recentlyRemovedDateranges.forEach((id) => {\n delete dateRanges[id];\n });\n }\n Object.keys(deltaDateRanges).forEach((id) => {\n const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);\n if (dateRange.isValid) {\n dateRanges[id] = dateRange;\n } else {\n logger.warn(\n `Ignoring invalid Playlist Delta Update DATERANGE tag: \"${JSON.stringify(\n deltaDateRanges[id].attr,\n )}\"`,\n );\n }\n });\n return dateRanges;\n}\n\nexport function mapPartIntersection(\n oldParts: Part[] | null,\n newParts: Part[] | null,\n intersectionFn: PartIntersection,\n) {\n if (oldParts && newParts) {\n let delta = 0;\n for (let i = 0, len = oldParts.length; i <= len; i++) {\n const oldPart = oldParts[i];\n const newPart = newParts[i + delta];\n if (\n oldPart &&\n newPart &&\n oldPart.index === newPart.index &&\n oldPart.fragment.sn === newPart.fragment.sn\n ) {\n intersectionFn(oldPart, newPart);\n } else {\n delta--;\n }\n }\n }\n}\n\nexport function mapFragmentIntersection(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n intersectionFn: FragmentIntersection,\n): void {\n const skippedSegments = newDetails.skippedSegments;\n const start =\n Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;\n const end =\n (oldDetails.fragmentHint ? 1 : 0) +\n (skippedSegments\n ? newDetails.endSN\n : Math.min(oldDetails.endSN, newDetails.endSN)) -\n newDetails.startSN;\n const delta = newDetails.startSN - oldDetails.startSN;\n const newFrags = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n const oldFrags = oldDetails.fragmentHint\n ? oldDetails.fragments.concat(oldDetails.fragmentHint)\n : oldDetails.fragments;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldFrags[delta + i];\n let newFrag = newFrags[i];\n if (skippedSegments && !newFrag && i < skippedSegments) {\n // Fill in skipped segments in delta playlist\n newFrag = newDetails.fragments[i] = oldFrag;\n }\n if (oldFrag && newFrag) {\n intersectionFn(oldFrag, newFrag);\n }\n }\n}\n\nexport function adjustSliding(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n): void {\n const delta =\n newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;\n const oldFragments = oldDetails.fragments;\n if (delta < 0 || delta >= oldFragments.length) {\n return;\n }\n addSliding(newDetails, oldFragments[delta].start);\n}\n\nexport function addSliding(details: LevelDetails, start: number) {\n if (start) {\n const fragments = details.fragments;\n for (let i = details.skippedSegments; i < fragments.length; i++) {\n fragments[i].start += start;\n }\n if (details.fragmentHint) {\n details.fragmentHint.start += start;\n }\n }\n}\n\nexport function computeReloadInterval(\n newDetails: LevelDetails,\n distanceToLiveEdgeMs: number = Infinity,\n): number {\n let reloadInterval = 1000 * newDetails.targetduration;\n\n if (newDetails.updated) {\n // Use last segment duration when shorter than target duration and near live edge\n const fragments = newDetails.fragments;\n const liveEdgeMaxTargetDurations = 4;\n if (\n fragments.length &&\n reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs\n ) {\n const lastSegmentDuration =\n fragments[fragments.length - 1].duration * 1000;\n if (lastSegmentDuration < reloadInterval) {\n reloadInterval = lastSegmentDuration;\n }\n }\n } else {\n // estimate = 'miss half average';\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval /= 2;\n }\n\n return Math.round(reloadInterval);\n}\n\nexport function getFragmentWithSN(\n level: Level,\n sn: number,\n fragCurrent: Fragment | null,\n): Fragment | null {\n if (!level?.details) {\n return null;\n }\n const levelDetails = level.details;\n let fragment: Fragment | undefined =\n levelDetails.fragments[sn - levelDetails.startSN];\n if (fragment) {\n return fragment;\n }\n fragment = levelDetails.fragmentHint;\n if (fragment && fragment.sn === sn) {\n return fragment;\n }\n if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {\n return fragCurrent;\n }\n return null;\n}\n\nexport function getPartWith(\n level: Level,\n sn: number,\n partIndex: number,\n): Part | null {\n if (!level?.details) {\n return null;\n }\n return findPart(level.details?.partList, sn, partIndex);\n}\n\nexport function findPart(\n partList: Part[] | null | undefined,\n sn: number,\n partIndex: number,\n): Part | null {\n if (partList) {\n for (let i = partList.length; i--; ) {\n const part = partList[i];\n if (part.index === partIndex && part.fragment.sn === sn) {\n return part;\n }\n }\n }\n return null;\n}\n\nexport function reassignFragmentLevelIndexes(levels: Level[]) {\n levels.forEach((level, index) => {\n const { details } = level;\n if (details?.fragments) {\n details.fragments.forEach((fragment) => {\n fragment.level = index;\n });\n }\n });\n}\n","import { ErrorDetails } from '../errors';\nimport type { LoadPolicy, LoaderConfig, RetryConfig } from '../config';\nimport type { ErrorData } from '../types/events';\nimport type { LoaderResponse } from '../types/loader';\n\nexport function isTimeoutError(error: ErrorData): boolean {\n switch (error.details) {\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.MANIFEST_LOAD_TIMEOUT:\n return true;\n }\n return false;\n}\n\nexport function getRetryConfig(\n loadPolicy: LoadPolicy,\n error: ErrorData,\n): RetryConfig | null {\n const isTimeout = isTimeoutError(error);\n return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];\n}\n\nexport function getRetryDelay(\n retryConfig: RetryConfig,\n retryCount: number,\n): number {\n // exponential backoff capped to max retry delay\n const backoffFactor =\n retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);\n return Math.min(\n backoffFactor * retryConfig.retryDelayMs,\n retryConfig.maxRetryDelayMs,\n );\n}\n\nexport function getLoaderConfigWithoutReties(\n loderConfig: LoaderConfig,\n): LoaderConfig {\n return {\n ...loderConfig,\n ...{\n errorRetry: null,\n timeoutRetry: null,\n },\n };\n}\n\nexport function shouldRetry(\n retryConfig: RetryConfig | null | undefined,\n retryCount: number,\n isTimeout: boolean,\n loaderResponse?: LoaderResponse | undefined,\n): retryConfig is RetryConfig & boolean {\n if (!retryConfig) {\n return false;\n }\n const httpStatus = loaderResponse?.code;\n const retry =\n retryCount < retryConfig.maxNumRetry &&\n (retryForHttpStatus(httpStatus) || !!isTimeout);\n return retryConfig.shouldRetry\n ? retryConfig.shouldRetry(\n retryConfig,\n retryCount,\n isTimeout,\n loaderResponse,\n retry,\n )\n : retry;\n}\n\nexport function retryForHttpStatus(httpStatus: number | undefined) {\n // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)\n return (\n (httpStatus === 0 && navigator.onLine === false) ||\n (!!httpStatus && (httpStatus < 400 || httpStatus > 499))\n );\n}\n","type BinarySearchComparison<T> = (candidate: T) => -1 | 0 | 1;\n\nconst BinarySearch = {\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param list The array to search.\n * @param comparisonFn\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @returns the object if found, otherwise returns null\n */\n search: function <T>(\n list: T[],\n comparisonFn: BinarySearchComparison<T>,\n ): T | null {\n let minIndex: number = 0;\n let maxIndex: number = list.length - 1;\n let currentIndex: number | null = null;\n let currentElement: T | null = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = ((minIndex + maxIndex) / 2) | 0;\n currentElement = list[currentIndex];\n\n const comparisonResult = comparisonFn(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n },\n};\n\nexport default BinarySearch;\n","import BinarySearch from '../utils/binary-search';\nimport { Fragment } from '../loader/fragment';\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT, or null.\n * @param fragments - The array of candidate fragments\n * @param PDTValue - The PDT value which must be exceeded\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n */\nexport function findFragmentByPDT(\n fragments: Array<Fragment>,\n PDTValue: number | null,\n maxFragLookUpTolerance: number,\n): Fragment | null {\n if (\n PDTValue === null ||\n !Array.isArray(fragments) ||\n !fragments.length ||\n !Number.isFinite(PDTValue)\n ) {\n return null;\n }\n\n // if less than start\n const startPDT = fragments[0].programDateTime;\n if (PDTValue < (startPDT || 0)) {\n return null;\n }\n\n const endPDT = fragments[fragments.length - 1].endProgramDateTime;\n if (PDTValue >= (endPDT || 0)) {\n return null;\n }\n\n maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n for (let seg = 0; seg < fragments.length; ++seg) {\n const frag = fragments[seg];\n if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n return frag;\n }\n }\n\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param fragPrevious - The last frag successfully appended\n * @param fragments - The array of candidate fragments\n * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns a matching fragment or null\n */\nexport function findFragmentByPTS(\n fragPrevious: Fragment | null,\n fragments: Array<Fragment>,\n bufferEnd: number = 0,\n maxFragLookUpTolerance: number = 0,\n nextFragLookupTolerance: number = 0.005,\n): Fragment | null {\n let fragNext: Fragment | null = null;\n if (fragPrevious) {\n fragNext =\n fragments[\n (fragPrevious.sn as number) - (fragments[0].sn as number) + 1\n ] || null;\n // check for buffer-end rounding error\n const bufferEdgeError = fragPrevious.endDTS - bufferEnd;\n if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {\n bufferEnd += 0.0000015;\n }\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (\n fragNext &&\n (((!fragPrevious || fragPrevious.level === fragNext.level) &&\n fragmentWithinToleranceTest(\n bufferEnd,\n maxFragLookUpTolerance,\n fragNext,\n ) === 0) ||\n fragmentWithinFastStartSwitch(\n fragNext,\n fragPrevious,\n Math.min(nextFragLookupTolerance, maxFragLookUpTolerance),\n ))\n ) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(\n fragments,\n fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance),\n );\n if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\n}\n\nfunction fragmentWithinFastStartSwitch(\n fragNext: Fragment,\n fragPrevious: Fragment | null,\n nextFragLookupTolerance: number,\n): boolean {\n if (\n fragPrevious &&\n fragPrevious.start === 0 &&\n fragPrevious.level < fragNext.level &&\n (fragPrevious.endPTS || 0) > 0\n ) {\n const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {\n if (tag[0] === 'INF') {\n duration += parseFloat(tag[1]);\n }\n return duration;\n }, nextFragLookupTolerance);\n return fragNext.start <= firstDuration;\n }\n return false;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param candidate - The fragment to test\n * @param bufferEnd - The end of the current buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest(\n bufferEnd = 0,\n maxFragLookUpTolerance = 0,\n candidate: Fragment,\n) {\n // eagerly accept an accurate match (no tolerance)\n if (\n candidate.start <= bufferEnd &&\n candidate.start + candidate.duration > bufferEnd\n ) {\n return 0;\n }\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n const candidateLookupTolerance = Math.min(\n maxFragLookUpTolerance,\n candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0),\n );\n if (\n candidate.start + candidate.duration - candidateLookupTolerance <=\n bufferEnd\n ) {\n return 1;\n } else if (\n candidate.start - candidateLookupTolerance > bufferEnd &&\n candidate.start\n ) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/**\n * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n * This function tests the candidate's program date time values, as represented in Unix time\n * @param candidate - The fragment to test\n * @param pdtBufferEnd - The Unix time representing the end of the current buffered range\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns true if contiguous, false otherwise\n */\nexport function pdtWithinToleranceTest(\n pdtBufferEnd: number,\n maxFragLookUpTolerance: number,\n candidate: Fragment,\n): boolean {\n const candidateLookupTolerance =\n Math.min(\n maxFragLookUpTolerance,\n candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0),\n ) * 1000;\n\n // endProgramDateTime can be null, default to zero\n const endProgramDateTime = candidate.endProgramDateTime || 0;\n return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\n\nexport function findFragWithCC(\n fragments: Fragment[],\n cc: number,\n): Fragment | null {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < cc) {\n return 1;\n } else if (candidate.cc > cc) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n","import { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport {\n getRetryConfig,\n isTimeoutError,\n shouldRetry,\n} from '../utils/error-helper';\nimport { findFragmentByPTS } from './fragment-finders';\nimport { HdcpLevel, HdcpLevels } from '../types/level';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { RetryConfig } from '../config';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { ErrorData } from '../types/events';\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../loader/level-details';\n\nexport const enum NetworkErrorAction {\n DoNothing = 0,\n SendEndCallback = 1, // Reserved for future use\n SendAlternateToPenaltyBox = 2,\n RemoveAlternatePermanently = 3, // Reserved for future use\n InsertDiscontinuity = 4, // Reserved for future use\n RetryRequest = 5,\n}\n\nexport const enum ErrorActionFlags {\n None = 0,\n MoveAllAlternatesMatchingHost = 1,\n MoveAllAlternatesMatchingHDCP = 1 << 1,\n SwitchToSDR = 1 << 2, // Reserved for future use\n}\n\nexport type IErrorAction = {\n action: NetworkErrorAction;\n flags: ErrorActionFlags;\n retryCount?: number;\n retryConfig?: RetryConfig;\n hdcpLevel?: HdcpLevel;\n nextAutoLevel?: number;\n resolved?: boolean;\n};\n\ntype PenalizedRendition = {\n lastErrorPerfMs: number;\n errors: ErrorData[];\n details?: LevelDetails;\n};\n\ntype PenalizedRenditions = { [key: number]: PenalizedRendition };\n\nexport default class ErrorController implements NetworkComponentAPI {\n private readonly hls: Hls;\n private playlistError: number = 0;\n private penalizedRenditions: PenalizedRenditions = {};\n private log: (msg: any) => void;\n private warn: (msg: any) => void;\n private error: (msg: any) => void;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.log = logger.log.bind(logger, `[info]:`);\n this.warn = logger.warn.bind(logger, `[warning]:`);\n this.error = logger.error.bind(logger, `[error]:`);\n this.registerListeners();\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.ERROR, this.onErrorOut, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n destroy() {\n this.unregisterListeners();\n // @ts-ignore\n this.hls = null;\n this.penalizedRenditions = {};\n }\n\n startLoad(startPosition: number): void {}\n\n stopLoad(): void {\n this.playlistError = 0;\n }\n\n private getVariantLevelIndex(frag: Fragment | undefined): number {\n return frag?.type === PlaylistLevelType.MAIN\n ? frag.level\n : this.hls.loadLevel;\n }\n\n private onManifestLoading() {\n this.playlistError = 0;\n this.penalizedRenditions = {};\n }\n\n private onLevelUpdated() {\n this.playlistError = 0;\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n return;\n }\n const hls = this.hls;\n const context = data.context;\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n return;\n case ErrorDetails.FRAG_PARSING_ERROR:\n // ignore empty segment errors marked as gap\n if (data.frag?.gap) {\n data.errorAction = {\n action: NetworkErrorAction.DoNothing,\n flags: ErrorActionFlags.None,\n };\n return;\n }\n // falls through\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_DECRYPT_ERROR: {\n // Switch level if possible, otherwise allow retry count to reach max error retries\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;\n return;\n }\n case ErrorDetails.LEVEL_EMPTY_ERROR:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n {\n // Only retry when empty and live\n const levelIndex =\n data.parent === PlaylistLevelType.MAIN\n ? (data.level as number)\n : hls.loadLevel;\n if (\n data.details === ErrorDetails.LEVEL_EMPTY_ERROR &&\n !!data.context?.levelDetails?.live\n ) {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n levelIndex,\n );\n } else {\n // Escalate to fatal if not retrying or switching\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n }\n }\n return;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (typeof context?.level === 'number') {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n context.level,\n );\n }\n return;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.SUBTITLE_LOAD_ERROR:\n case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:\n if (context) {\n const level = hls.levels[hls.loadLevel];\n if (\n level &&\n ((context.type === PlaylistContextType.AUDIO_TRACK &&\n level.hasAudioGroup(context.groupId)) ||\n (context.type === PlaylistContextType.SUBTITLE_TRACK &&\n level.hasSubtitleGroup(context.groupId)))\n ) {\n // Perform Pathway switch or Redundant failover if possible for fastest recovery\n // otherwise allow playlist retry count to reach max error retries\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n hls.loadLevel,\n );\n data.errorAction.action =\n NetworkErrorAction.SendAlternateToPenaltyBox;\n data.errorAction.flags =\n ErrorActionFlags.MoveAllAlternatesMatchingHost;\n return;\n }\n }\n return;\n case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:\n {\n const level = hls.levels[hls.loadLevel];\n const restrictedHdcpLevel = level?.attrs['HDCP-LEVEL'];\n if (restrictedHdcpLevel) {\n data.errorAction = {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,\n hdcpLevel: restrictedHdcpLevel,\n };\n } else {\n this.keySystemError(data);\n }\n }\n return;\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.REMUX_ALLOC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n data.errorAction = this.getLevelSwitchAction(\n data,\n data.level ?? hls.loadLevel,\n );\n return;\n case ErrorDetails.INTERNAL_EXCEPTION:\n case ErrorDetails.BUFFER_APPENDING_ERROR:\n case ErrorDetails.BUFFER_FULL_ERROR:\n case ErrorDetails.LEVEL_SWITCH_ERROR:\n case ErrorDetails.BUFFER_STALLED_ERROR:\n case ErrorDetails.BUFFER_SEEK_OVER_HOLE:\n case ErrorDetails.BUFFER_NUDGE_ON_STALL:\n data.errorAction = {\n action: NetworkErrorAction.DoNothing,\n flags: ErrorActionFlags.None,\n };\n return;\n }\n\n if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {\n this.keySystemError(data);\n }\n }\n\n private keySystemError(data: ErrorData) {\n const levelIndex = this.getVariantLevelIndex(data.frag);\n // Do not retry level. Escalate to fatal if switching levels fails.\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n }\n\n private getPlaylistRetryOrSwitchAction(\n data: ErrorData,\n levelIndex: number | null | undefined,\n ): IErrorAction {\n const hls = this.hls;\n const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);\n const retryCount = this.playlistError++;\n const retry = shouldRetry(\n retryConfig,\n retryCount,\n isTimeoutError(data),\n data.response,\n );\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount,\n };\n }\n const errorAction = this.getLevelSwitchAction(data, levelIndex);\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = retryCount;\n }\n return errorAction;\n }\n\n private getFragRetryOrSwitchAction(data: ErrorData): IErrorAction {\n const hls = this.hls;\n // Share fragment error count accross media options (main, audio, subs)\n // This allows for level based rendition switching when media option assets fail\n const variantLevelIndex = this.getVariantLevelIndex(data.frag);\n const level = hls.levels[variantLevelIndex];\n const { fragLoadPolicy, keyLoadPolicy } = hls.config;\n const retryConfig = getRetryConfig(\n data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy,\n data,\n );\n const fragmentErrors = hls.levels.reduce(\n (acc, level) => acc + level.fragmentError,\n 0,\n );\n // Switch levels when out of retried or level index out of bounds\n if (level) {\n if (data.details !== ErrorDetails.FRAG_GAP) {\n level.fragmentError++;\n }\n const retry = shouldRetry(\n retryConfig,\n fragmentErrors,\n isTimeoutError(data),\n data.response,\n );\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount: fragmentErrors,\n };\n }\n }\n // Reach max retry count, or Missing level reference\n // Switch to valid index\n const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);\n // Add retry details to allow skipping of FRAG_PARSING_ERROR\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = fragmentErrors;\n }\n return errorAction;\n }\n\n private getLevelSwitchAction(\n data: ErrorData,\n levelIndex: number | null | undefined,\n ): IErrorAction {\n const hls = this.hls;\n if (levelIndex === null || levelIndex === undefined) {\n levelIndex = hls.loadLevel;\n }\n const level = this.hls.levels[levelIndex];\n if (level) {\n const errorDetails = data.details;\n level.loadError++;\n if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {\n level.fragmentError++;\n }\n // Search for next level to retry\n let nextLevel = -1;\n const { levels, loadLevel, minAutoLevel, maxAutoLevel } = hls;\n if (!hls.autoLevelEnabled) {\n hls.loadLevel = -1;\n }\n const fragErrorType = data.frag?.type;\n // Find alternate audio codec if available on audio codec error\n const isAudioCodecError =\n (fragErrorType === PlaylistLevelType.AUDIO &&\n errorDetails === ErrorDetails.FRAG_PARSING_ERROR) ||\n (data.sourceBufferName === 'audio' &&\n (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR ||\n errorDetails === ErrorDetails.BUFFER_APPEND_ERROR));\n const findAudioCodecAlternate =\n isAudioCodecError &&\n levels.some(({ audioCodec }) => level.audioCodec !== audioCodec);\n // Find alternate video codec if available on video codec error\n const isVideoCodecError =\n data.sourceBufferName === 'video' &&\n (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR ||\n errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);\n const findVideoCodecAlternate =\n isVideoCodecError &&\n levels.some(\n ({ codecSet, audioCodec }) =>\n level.codecSet !== codecSet && level.audioCodec === audioCodec,\n );\n const { type: playlistErrorType, groupId: playlistErrorGroupId } =\n data.context ?? {};\n for (let i = levels.length; i--; ) {\n const candidate = (i + loadLevel) % levels.length;\n if (\n candidate !== loadLevel &&\n candidate >= minAutoLevel &&\n candidate <= maxAutoLevel &&\n levels[candidate].loadError === 0\n ) {\n const levelCandidate = levels[candidate];\n // Skip level switch if GAP tag is found in next level at same position\n if (\n errorDetails === ErrorDetails.FRAG_GAP &&\n fragErrorType === PlaylistLevelType.MAIN &&\n data.frag\n ) {\n const levelDetails = levels[candidate].details;\n if (levelDetails) {\n const fragCandidate = findFragmentByPTS(\n data.frag,\n levelDetails.fragments,\n data.frag.start,\n );\n if (fragCandidate?.gap) {\n continue;\n }\n }\n } else if (\n (playlistErrorType === PlaylistContextType.AUDIO_TRACK &&\n levelCandidate.hasAudioGroup(playlistErrorGroupId)) ||\n (playlistErrorType === PlaylistContextType.SUBTITLE_TRACK &&\n levelCandidate.hasSubtitleGroup(playlistErrorGroupId))\n ) {\n // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over\n continue;\n } else if (\n (fragErrorType === PlaylistLevelType.AUDIO &&\n level.audioGroups?.some((groupId) =>\n levelCandidate.hasAudioGroup(groupId),\n )) ||\n (fragErrorType === PlaylistLevelType.SUBTITLE &&\n level.subtitleGroups?.some((groupId) =>\n levelCandidate.hasSubtitleGroup(groupId),\n )) ||\n (findAudioCodecAlternate &&\n level.audioCodec === levelCandidate.audioCodec) ||\n (!findAudioCodecAlternate &&\n level.audioCodec !== levelCandidate.audioCodec) ||\n (findVideoCodecAlternate &&\n level.codecSet === levelCandidate.codecSet)\n ) {\n // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over\n continue;\n }\n nextLevel = candidate;\n break;\n }\n }\n if (nextLevel > -1 && hls.loadLevel !== nextLevel) {\n data.levelRetry = true;\n this.playlistError = 0;\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.None,\n nextAutoLevel: nextLevel,\n };\n }\n }\n // No levels to switch / Manual level selection / Level not found\n // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHost,\n };\n }\n\n public onErrorOut(event: Events.ERROR, data: ErrorData) {\n switch (data.errorAction?.action) {\n case NetworkErrorAction.DoNothing:\n break;\n case NetworkErrorAction.SendAlternateToPenaltyBox:\n this.sendAlternateToPenaltyBox(data);\n if (\n !data.errorAction.resolved &&\n data.details !== ErrorDetails.FRAG_GAP\n ) {\n data.fatal = true;\n } else if (/MediaSource readyState: ended/.test(data.error.message)) {\n this.warn(\n `MediaSource ended after \"${data.sourceBufferName}\" sourceBuffer append error. Attempting to recover from media error.`,\n );\n this.hls.recoverMediaError();\n }\n break;\n case NetworkErrorAction.RetryRequest:\n // handled by stream and playlist/level controllers\n break;\n }\n\n if (data.fatal) {\n this.hls.stopLoad();\n return;\n }\n }\n\n private sendAlternateToPenaltyBox(data: ErrorData) {\n const hls = this.hls;\n const errorAction = data.errorAction;\n if (!errorAction) {\n return;\n }\n const { flags, hdcpLevel, nextAutoLevel } = errorAction;\n\n switch (flags) {\n case ErrorActionFlags.None:\n this.switchLevel(data, nextAutoLevel);\n break;\n case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:\n if (hdcpLevel) {\n hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];\n errorAction.resolved = true;\n }\n this.warn(\n `Restricting playback to HDCP-LEVEL of \"${hls.maxHdcpLevel}\" or lower`,\n );\n break;\n }\n // If not resolved by previous actions try to switch to next level\n if (!errorAction.resolved) {\n this.switchLevel(data, nextAutoLevel);\n }\n }\n\n private switchLevel(data: ErrorData, levelIndex: number | undefined) {\n if (levelIndex !== undefined && data.errorAction) {\n this.warn(`switching to level ${levelIndex} after ${data.details}`);\n this.hls.nextAutoLevel = levelIndex;\n data.errorAction.resolved = true;\n // Stream controller is responsible for this but won't switch on false start\n this.hls.nextLoadLevel = this.hls.nextAutoLevel;\n }\n }\n}\n","import type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport { getSkipValue, HlsSkip, HlsUrlParameters, Level } from '../types/level';\nimport { computeReloadInterval, mergeDetails } from '../utils/level-helper';\nimport { ErrorData } from '../types/events';\nimport { getRetryDelay, isTimeoutError } from '../utils/error-helper';\nimport { NetworkErrorAction } from './error-controller';\nimport { logger } from '../utils/logger';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport type {\n AudioTrackLoadedData,\n LevelLoadedData,\n TrackLoadedData,\n} from '../types/events';\n\nexport default class BasePlaylistController implements NetworkComponentAPI {\n protected hls: Hls;\n protected timer: number = -1;\n protected requestScheduled: number = -1;\n protected canLoad: boolean = false;\n protected log: (msg: any) => void;\n protected warn: (msg: any) => void;\n\n constructor(hls: Hls, logPrefix: string) {\n this.log = logger.log.bind(logger, `${logPrefix}:`);\n this.warn = logger.warn.bind(logger, `${logPrefix}:`);\n this.hls = hls;\n }\n\n public destroy(): void {\n this.clearTimer();\n // @ts-ignore\n this.hls = this.log = this.warn = null;\n }\n\n protected clearTimer(): void {\n if (this.timer !== -1) {\n self.clearTimeout(this.timer);\n this.timer = -1;\n }\n }\n\n public startLoad(): void {\n this.canLoad = true;\n this.requestScheduled = -1;\n this.loadPlaylist();\n }\n\n public stopLoad(): void {\n this.canLoad = false;\n this.clearTimer();\n }\n\n protected switchParams(\n playlistUri: string,\n previous: LevelDetails | undefined,\n current: LevelDetails | undefined,\n ): HlsUrlParameters | undefined {\n const renditionReports = previous?.renditionReports;\n if (renditionReports) {\n let foundIndex = -1;\n for (let i = 0; i < renditionReports.length; i++) {\n const attr = renditionReports[i];\n let uri: string;\n try {\n uri = new self.URL(attr.URI, previous.url).href;\n } catch (error) {\n logger.warn(\n `Could not construct new URL for Rendition Report: ${error}`,\n );\n uri = attr.URI || '';\n }\n // Use exact match. Otherwise, the last partial match, if any, will be used\n // (Playlist URI includes a query string that the Rendition Report does not)\n if (uri === playlistUri) {\n foundIndex = i;\n break;\n } else if (uri === playlistUri.substring(0, uri.length)) {\n foundIndex = i;\n }\n }\n if (foundIndex !== -1) {\n const attr = renditionReports[foundIndex];\n const msn = parseInt(attr['LAST-MSN']) || previous?.lastPartSn;\n let part = parseInt(attr['LAST-PART']) || previous?.lastPartIndex;\n if (this.hls.config.lowLatencyMode) {\n const currentGoal = Math.min(\n previous.age - previous.partTarget,\n previous.targetduration,\n );\n if (part >= 0 && currentGoal > previous.partTarget) {\n part += 1;\n }\n }\n const skip = current && getSkipValue(current);\n return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);\n }\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n if (this.requestScheduled === -1) {\n this.requestScheduled = self.performance.now();\n }\n // Loading is handled by the subclasses\n }\n\n protected shouldLoadPlaylist(\n playlist: Level | MediaPlaylist | null | undefined,\n ): boolean {\n return (\n this.canLoad &&\n !!playlist &&\n !!playlist.url &&\n (!playlist.details || playlist.details.live)\n );\n }\n\n protected shouldReloadPlaylist(\n playlist: Level | MediaPlaylist | null | undefined,\n ): boolean {\n return (\n this.timer === -1 &&\n this.requestScheduled === -1 &&\n this.shouldLoadPlaylist(playlist)\n );\n }\n\n protected playlistLoaded(\n index: number,\n data: LevelLoadedData | AudioTrackLoadedData | TrackLoadedData,\n previousDetails?: LevelDetails,\n ) {\n const { details, stats } = data;\n\n // Set last updated date-time\n const now = self.performance.now();\n const elapsed = stats.loading.first\n ? Math.max(0, now - stats.loading.first)\n : 0;\n details.advancedDateTime = Date.now() - elapsed;\n\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live || previousDetails?.live) {\n details.reloaded(previousDetails);\n if (previousDetails) {\n this.log(\n `live playlist ${index} ${\n details.advanced\n ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex\n : details.updated\n ? 'UPDATED'\n : 'MISSED'\n }`,\n );\n }\n // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments\n if (previousDetails && details.fragments.length > 0) {\n mergeDetails(previousDetails, details);\n }\n if (!this.canLoad || !details.live) {\n return;\n }\n let deliveryDirectives: HlsUrlParameters | undefined;\n let msn: number | undefined = undefined;\n let part: number | undefined = undefined;\n if (details.canBlockReload && details.endSN && details.advanced) {\n // Load level with LL-HLS delivery directives\n const lowLatencyMode = this.hls.config.lowLatencyMode;\n const lastPartSn = details.lastPartSn;\n const endSn = details.endSN;\n const lastPartIndex = details.lastPartIndex;\n const hasParts = lastPartIndex !== -1;\n const lastPart = lastPartSn === endSn;\n // When low latency mode is disabled, we'll skip part requests once the last part index is found\n const nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;\n if (hasParts) {\n msn = lastPart ? endSn + 1 : lastPartSn;\n part = lastPart ? nextSnStartIndex : lastPartIndex + 1;\n } else {\n msn = endSn + 1;\n }\n // Low-Latency CDN Tune-in: \"age\" header and time since load indicates we're behind by more than one part\n // Update directives to obtain the Playlist that has the estimated additional duration of media\n const lastAdvanced = details.age;\n const cdnAge = lastAdvanced + details.ageHeader;\n let currentGoal = Math.min(\n cdnAge - details.partTarget,\n details.targetduration * 1.5,\n );\n if (currentGoal > 0) {\n if (previousDetails && currentGoal > previousDetails.tuneInGoal) {\n // If we attempted to get the next or latest playlist update, but currentGoal increased,\n // then we either can't catchup, or the \"age\" header cannot be trusted.\n this.warn(\n `CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`,\n );\n currentGoal = 0;\n } else {\n const segments = Math.floor(currentGoal / details.targetduration);\n msn += segments;\n if (part !== undefined) {\n const parts = Math.round(\n (currentGoal % details.targetduration) / details.partTarget,\n );\n part += parts;\n }\n this.log(\n `CDN Tune-in age: ${\n details.ageHeader\n }s last advanced ${lastAdvanced.toFixed(\n 2,\n )}s goal: ${currentGoal} skip sn ${segments} to part ${part}`,\n );\n }\n details.tuneInGoal = currentGoal;\n }\n deliveryDirectives = this.getDeliveryDirectives(\n details,\n data.deliveryDirectives,\n msn,\n part,\n );\n if (lowLatencyMode || !lastPart) {\n this.loadPlaylist(deliveryDirectives);\n return;\n }\n } else if (details.canBlockReload || details.canSkipUntil) {\n deliveryDirectives = this.getDeliveryDirectives(\n details,\n data.deliveryDirectives,\n msn,\n part,\n );\n }\n const bufferInfo = this.hls.mainForwardBufferInfo;\n const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;\n const distanceToLiveEdgeMs = (details.edge - position) * 1000;\n const reloadInterval = computeReloadInterval(\n details,\n distanceToLiveEdgeMs,\n );\n if (details.updated && now > this.requestScheduled + reloadInterval) {\n this.requestScheduled = stats.loading.start;\n }\n\n if (msn !== undefined && details.canBlockReload) {\n this.requestScheduled =\n stats.loading.first +\n reloadInterval -\n (details.partTarget * 1000 || 1000);\n } else if (\n this.requestScheduled === -1 ||\n this.requestScheduled + reloadInterval < now\n ) {\n this.requestScheduled = now;\n } else if (this.requestScheduled - now <= 0) {\n this.requestScheduled += reloadInterval;\n }\n let estimatedTimeUntilUpdate = this.requestScheduled - now;\n estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);\n this.log(\n `reload live playlist ${index} in ${Math.round(\n estimatedTimeUntilUpdate,\n )} ms`,\n );\n // this.log(\n // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}\n // reload in ${estimatedTimeUntilUpdate / 1000}\n // round trip ${(stats.loading.end - stats.loading.start) / 1000}\n // diff ${\n // (reloadInterval -\n // (estimatedTimeUntilUpdate +\n // stats.loading.end -\n // stats.loading.start)) /\n // 1000\n // }\n // reload interval ${reloadInterval / 1000}\n // target duration ${details.targetduration}\n // distance to edge ${distanceToLiveEdgeMs / 1000}`\n // );\n\n this.timer = self.setTimeout(\n () => this.loadPlaylist(deliveryDirectives),\n estimatedTimeUntilUpdate,\n );\n } else {\n this.clearTimer();\n }\n }\n\n private getDeliveryDirectives(\n details: LevelDetails,\n previousDeliveryDirectives: HlsUrlParameters | null,\n msn?: number,\n part?: number,\n ): HlsUrlParameters {\n let skip = getSkipValue(details);\n if (previousDeliveryDirectives?.skip && details.deltaUpdateFailed) {\n msn = previousDeliveryDirectives.msn;\n part = previousDeliveryDirectives.part;\n skip = HlsSkip.No;\n }\n return new HlsUrlParameters(msn, part, skip);\n }\n\n protected checkRetry(errorEvent: ErrorData): boolean {\n const errorDetails = errorEvent.details;\n const isTimeout = isTimeoutError(errorEvent);\n const errorAction = errorEvent.errorAction;\n const { action, retryCount = 0, retryConfig } = errorAction || {};\n const retry =\n !!errorAction &&\n !!retryConfig &&\n (action === NetworkErrorAction.RetryRequest ||\n (!errorAction.resolved &&\n action === NetworkErrorAction.SendAlternateToPenaltyBox));\n if (retry) {\n this.requestScheduled = -1;\n if (retryCount >= retryConfig.maxNumRetry) {\n return false;\n }\n if (isTimeout && errorEvent.context?.deliveryDirectives) {\n // The LL-HLS request already timed out so retry immediately\n this.warn(\n `Retrying playlist loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } after \"${errorDetails}\" without delivery-directives`,\n );\n this.loadPlaylist();\n } else {\n const delay = getRetryDelay(retryConfig, retryCount);\n // Schedule level/track reload\n this.timer = self.setTimeout(() => this.loadPlaylist(), delay);\n this.warn(\n `Retrying playlist loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } after \"${errorDetails}\" in ${delay}ms`,\n );\n }\n // `levelRetry = true` used to inform other controllers that a retry is happening\n errorEvent.levelRetry = true;\n errorAction.resolved = true;\n }\n return retry;\n }\n}\n","/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n public readonly halfLife: number;\n private alpha_: number;\n private estimate_: number;\n private totalWeight_: number;\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor(halfLife: number, estimate: number = 0, weight: number = 0) {\n this.halfLife = halfLife;\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = estimate;\n this.totalWeight_ = weight;\n }\n\n sample(weight: number, value: number) {\n const adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight(): number {\n return this.totalWeight_;\n }\n\n getEstimate(): number {\n if (this.alpha_) {\n const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n if (zeroFactor) {\n return this.estimate_ / zeroFactor;\n }\n }\n return this.estimate_;\n }\n}\n\nexport default EWMA;\n","/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\nclass EwmaBandWidthEstimator {\n private defaultEstimate_: number;\n private minWeight_: number;\n private minDelayMs_: number;\n private slow_: EWMA;\n private fast_: EWMA;\n private defaultTTFB_: number;\n private ttfb_: EWMA;\n\n constructor(\n slow: number,\n fast: number,\n defaultEstimate: number,\n defaultTTFB: number = 100,\n ) {\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n this.defaultTTFB_ = defaultTTFB;\n this.ttfb_ = new EWMA(slow);\n }\n\n update(slow: number, fast: number) {\n const { slow_, fast_, ttfb_ } = this;\n if (slow_.halfLife !== slow) {\n this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());\n }\n if (fast_.halfLife !== fast) {\n this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());\n }\n if (ttfb_.halfLife !== slow) {\n this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());\n }\n }\n\n sample(durationMs: number, numBytes: number) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n const numBits = 8 * numBytes;\n // weight is duration in seconds\n const durationS = durationMs / 1000;\n // value is bandwidth in bits/s\n const bandwidthInBps = numBits / durationS;\n this.fast_.sample(durationS, bandwidthInBps);\n this.slow_.sample(durationS, bandwidthInBps);\n }\n\n sampleTTFB(ttfb: number) {\n // weight is frequency curve applied to TTFB in seconds\n // (longer times have less weight with expected input under 1 second)\n const seconds = ttfb / 1000;\n const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);\n this.ttfb_.sample(weight, Math.max(ttfb, 5));\n }\n\n canEstimate(): boolean {\n return this.fast_.getTotalWeight() >= this.minWeight_;\n }\n\n getEstimate(): number {\n if (this.canEstimate()) {\n // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n getEstimateTTFB(): number {\n if (this.ttfb_.getTotalWeight() >= this.minWeight_) {\n return this.ttfb_.getEstimate();\n } else {\n return this.defaultTTFB_;\n }\n }\n\n destroy() {}\n}\nexport default EwmaBandWidthEstimator;\n","import { mimeTypeForCodec } from './codecs';\nimport type { Level, VideoRange } from '../types/level';\nimport type { AudioSelectionOption } from '../types/media-playlist';\nimport type { AudioTracksByGroup } from './rendition-helper';\n\nexport type MediaDecodingInfo = {\n supported: boolean;\n configurations: readonly MediaDecodingConfiguration[];\n decodingInfoResults: readonly MediaCapabilitiesDecodingInfo[];\n error?: Error;\n};\n\ntype BaseVideoConfiguration = Omit<VideoConfiguration, 'contentType'>;\n\nexport const SUPPORTED_INFO_DEFAULT: MediaDecodingInfo = {\n supported: true,\n configurations: [] as MediaDecodingConfiguration[],\n decodingInfoResults: [\n {\n supported: true,\n powerEfficient: true,\n smooth: true,\n },\n ],\n} as const;\n\nexport const SUPPORTED_INFO_CACHE: Record<\n string,\n Promise<MediaCapabilitiesDecodingInfo>\n> = {};\n\nexport function requiresMediaCapabilitiesDecodingInfo(\n level: Level,\n audioTracksByGroup: AudioTracksByGroup,\n currentVideoRange: VideoRange | undefined,\n currentFrameRate: number,\n currentBw: number,\n audioPreference: AudioSelectionOption | undefined,\n): boolean {\n // Only test support when configuration is exceeds minimum options\n const audioGroups = level.audioCodec ? level.audioGroups : null;\n const audioCodecPreference = audioPreference?.audioCodec;\n const channelsPreference = audioPreference?.channels;\n const maxChannels = channelsPreference\n ? parseInt(channelsPreference)\n : audioCodecPreference\n ? Infinity\n : 2;\n let audioChannels: Record<string, number> | null = null;\n if (audioGroups?.length) {\n try {\n if (audioGroups.length === 1 && audioGroups[0]) {\n audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;\n } else {\n audioChannels = audioGroups.reduce(\n (acc, groupId) => {\n if (groupId) {\n const audioTrackGroup = audioTracksByGroup.groups[groupId];\n if (!audioTrackGroup) {\n throw new Error(`Audio track group ${groupId} not found`);\n }\n // Sum all channel key values\n Object.keys(audioTrackGroup.channels).forEach((key) => {\n acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];\n });\n }\n return acc;\n },\n { 2: 0 },\n );\n }\n } catch (error) {\n return true;\n }\n }\n return (\n (level.videoCodec !== undefined &&\n ((level.width > 1920 && level.height > 1088) ||\n (level.height > 1920 && level.width > 1088) ||\n level.frameRate > Math.max(currentFrameRate, 30) ||\n (level.videoRange !== 'SDR' &&\n level.videoRange !== currentVideoRange) ||\n level.bitrate > Math.max(currentBw, 8e6))) ||\n (!!audioChannels &&\n Number.isFinite(maxChannels) &&\n Object.keys(audioChannels).some(\n (channels) => parseInt(channels) > maxChannels,\n ))\n );\n}\n\nexport function getMediaDecodingInfoPromise(\n level: Level,\n audioTracksByGroup: AudioTracksByGroup,\n mediaCapabilities: MediaCapabilities | undefined,\n): Promise<MediaDecodingInfo> {\n const videoCodecs = level.videoCodec;\n const audioCodecs = level.audioCodec;\n if (!videoCodecs || !audioCodecs || !mediaCapabilities) {\n return Promise.resolve(SUPPORTED_INFO_DEFAULT);\n }\n\n const baseVideoConfiguration: BaseVideoConfiguration = {\n width: level.width,\n height: level.height,\n bitrate: Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate)),\n // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.\n framerate: level.frameRate || 30,\n };\n\n const videoRange = level.videoRange;\n if (videoRange !== 'SDR') {\n baseVideoConfiguration.transferFunction =\n videoRange.toLowerCase() as TransferFunction;\n }\n\n const configurations: MediaDecodingConfiguration[] = videoCodecs\n .split(',')\n .map((videoCodec) => ({\n type: 'media-source',\n video: {\n ...baseVideoConfiguration,\n contentType: mimeTypeForCodec(videoCodec, 'video'),\n },\n }));\n\n if (audioCodecs && level.audioGroups) {\n level.audioGroups.forEach((audioGroupId) => {\n if (!audioGroupId) {\n return;\n }\n audioTracksByGroup.groups[audioGroupId]?.tracks.forEach((audioTrack) => {\n if (audioTrack.groupId === audioGroupId) {\n const channels = audioTrack.channels || '';\n const channelsNumber = parseFloat(channels);\n if (Number.isFinite(channelsNumber) && channelsNumber > 2) {\n configurations.push.apply(\n configurations,\n audioCodecs.split(',').map((audioCodec) => ({\n type: 'media-source',\n audio: {\n contentType: mimeTypeForCodec(audioCodec, 'audio'),\n channels: '' + channelsNumber,\n // spatialRendering:\n // audioCodec === 'ec-3' && channels.indexOf('JOC'),\n },\n })),\n );\n }\n }\n });\n });\n }\n\n return Promise.all(\n configurations.map((configuration) => {\n // Cache MediaCapabilities promises\n const decodingInfoKey = getMediaDecodingInfoKey(configuration);\n return (\n SUPPORTED_INFO_CACHE[decodingInfoKey] ||\n (SUPPORTED_INFO_CACHE[decodingInfoKey] =\n mediaCapabilities.decodingInfo(configuration))\n );\n }),\n )\n .then((decodingInfoResults) => ({\n supported: !decodingInfoResults.some((info) => !info.supported),\n configurations,\n decodingInfoResults,\n }))\n .catch((error) => ({\n supported: false,\n configurations,\n decodingInfoResults: [] as MediaCapabilitiesDecodingInfo[],\n error,\n }));\n}\n\nfunction getMediaDecodingInfoKey(config: MediaDecodingConfiguration): string {\n const { audio, video } = config;\n const mediaConfig = video || audio;\n if (mediaConfig) {\n const codec = mediaConfig.contentType.split('\"')[1];\n if (video) {\n return `r${video.height}x${video.width}f${Math.ceil(video.framerate)}${\n video.transferFunction || 'sd'\n }_${codec}_${Math.ceil(video.bitrate / 1e5)}`;\n }\n if (audio) {\n return `c${audio.channels}${audio.spatialRendering ? 's' : 'n'}_${codec}`;\n }\n }\n return '';\n}\n","import { type VideoRange, VideoRangeValues } from '../types/level';\nimport type { VideoSelectionOption } from '../types/media-playlist';\n\n/**\n * @returns Whether we can detect and validate HDR capability within the window context\n */\nexport function isHdrSupported() {\n if (typeof matchMedia === 'function') {\n const mediaQueryList = matchMedia('(dynamic-range: high)');\n const badQuery = matchMedia('bad query');\n if (mediaQueryList.media !== badQuery.media) {\n return mediaQueryList.matches === true;\n }\n }\n return false;\n}\n\n/**\n * Sanitizes inputs to return the active video selection options for HDR/SDR.\n * When both inputs are null:\n *\n * `{ preferHDR: false, allowedVideoRanges: [] }`\n *\n * When `currentVideoRange` non-null, maintain the active range:\n *\n * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`\n *\n * When VideoSelectionOption non-null:\n *\n * - Allow all video ranges if `allowedVideoRanges` unspecified.\n * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.\n * - Else check window for HDR support and set `preferHDR` to the result.\n *\n * @param currentVideoRange\n * @param videoPreference\n */\nexport function getVideoSelectionOptions(\n currentVideoRange: VideoRange | undefined,\n videoPreference: VideoSelectionOption | undefined,\n) {\n let preferHDR = false;\n let allowedVideoRanges: Array<VideoRange> = [];\n\n if (currentVideoRange) {\n preferHDR = currentVideoRange !== 'SDR';\n allowedVideoRanges = [currentVideoRange];\n }\n\n if (videoPreference) {\n allowedVideoRanges =\n videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);\n preferHDR =\n videoPreference.preferHDR !== undefined\n ? videoPreference.preferHDR\n : isHdrSupported();\n\n if (preferHDR) {\n allowedVideoRanges = allowedVideoRanges.filter(\n (range: VideoRange) => range !== 'SDR',\n );\n } else {\n allowedVideoRanges = ['SDR'];\n }\n }\n\n return {\n preferHDR,\n allowedVideoRanges,\n };\n}\n","import { codecsSetSelectionPreferenceValue } from './codecs';\nimport { getVideoSelectionOptions } from './hdr';\nimport { logger } from './logger';\nimport type { Level, VideoRange } from '../types/level';\nimport type {\n AudioSelectionOption,\n MediaPlaylist,\n SubtitleSelectionOption,\n VideoSelectionOption,\n} from '../types/media-playlist';\n\nexport type CodecSetTier = {\n minBitrate: number;\n minHeight: number;\n minFramerate: number;\n maxScore: number;\n videoRanges: Record<string, number>;\n channels: Record<string, number>;\n hasDefaultAudio: boolean;\n fragmentError: number;\n};\n\ntype AudioTrackGroup = {\n tracks: MediaPlaylist[];\n channels: Record<string, number>;\n hasDefault: boolean;\n hasAutoSelect: boolean;\n};\ntype StartParameters = {\n codecSet: string | undefined;\n videoRanges: Array<VideoRange>;\n preferHDR: boolean;\n minFramerate: number;\n minBitrate: number;\n};\n\nexport function getStartCodecTier(\n codecTiers: Record<string, CodecSetTier>,\n currentVideoRange: VideoRange | undefined,\n currentBw: number,\n audioPreference: AudioSelectionOption | undefined,\n videoPreference: VideoSelectionOption | undefined,\n): StartParameters {\n const codecSets = Object.keys(codecTiers);\n const channelsPreference = audioPreference?.channels;\n const audioCodecPreference = audioPreference?.audioCodec;\n const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;\n // Use first level set to determine stereo, and minimum resolution and framerate\n let hasStereo = true;\n let hasCurrentVideoRange = false;\n let minHeight = Infinity;\n let minFramerate = Infinity;\n let minBitrate = Infinity;\n let selectedScore = 0;\n let videoRanges: Array<VideoRange> = [];\n\n const { preferHDR, allowedVideoRanges } = getVideoSelectionOptions(\n currentVideoRange,\n videoPreference,\n );\n\n for (let i = codecSets.length; i--; ) {\n const tier = codecTiers[codecSets[i]];\n hasStereo = tier.channels[2] > 0;\n minHeight = Math.min(minHeight, tier.minHeight);\n minFramerate = Math.min(minFramerate, tier.minFramerate);\n minBitrate = Math.min(minBitrate, tier.minBitrate);\n const matchingVideoRanges = allowedVideoRanges.filter(\n (range) => tier.videoRanges[range] > 0,\n );\n if (matchingVideoRanges.length > 0) {\n hasCurrentVideoRange = true;\n videoRanges = matchingVideoRanges;\n }\n }\n minHeight = Number.isFinite(minHeight) ? minHeight : 0;\n minFramerate = Number.isFinite(minFramerate) ? minFramerate : 0;\n const maxHeight = Math.max(1080, minHeight);\n const maxFramerate = Math.max(30, minFramerate);\n minBitrate = Number.isFinite(minBitrate) ? minBitrate : currentBw;\n currentBw = Math.max(minBitrate, currentBw);\n // If there are no variants with matching preference, set currentVideoRange to undefined\n if (!hasCurrentVideoRange) {\n currentVideoRange = undefined;\n videoRanges = [];\n }\n const codecSet = codecSets.reduce(\n (selected: string | undefined, candidate: string) => {\n // Remove candiates which do not meet bitrate, default audio, stereo or channels preference, 1080p or lower, 30fps or lower, or SDR/HDR selection if present\n const candidateTier = codecTiers[candidate];\n if (candidate === selected) {\n return selected;\n }\n if (candidateTier.minBitrate > currentBw) {\n logStartCodecCandidateIgnored(\n candidate,\n `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`,\n );\n return selected;\n }\n if (!candidateTier.hasDefaultAudio) {\n logStartCodecCandidateIgnored(\n candidate,\n `no renditions with default or auto-select sound found`,\n );\n return selected;\n }\n if (\n audioCodecPreference &&\n candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0\n ) {\n logStartCodecCandidateIgnored(\n candidate,\n `audio codec preference \"${audioCodecPreference}\" not found`,\n );\n return selected;\n }\n if (channelsPreference && !preferStereo) {\n if (!candidateTier.channels[channelsPreference]) {\n logStartCodecCandidateIgnored(\n candidate,\n `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(\n candidateTier.channels,\n )})`,\n );\n return selected;\n }\n } else if (\n (!audioCodecPreference || preferStereo) &&\n hasStereo &&\n candidateTier.channels['2'] === 0\n ) {\n logStartCodecCandidateIgnored(\n candidate,\n `no renditions with stereo sound found`,\n );\n return selected;\n }\n if (candidateTier.minHeight > maxHeight) {\n logStartCodecCandidateIgnored(\n candidate,\n `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`,\n );\n return selected;\n }\n if (candidateTier.minFramerate > maxFramerate) {\n logStartCodecCandidateIgnored(\n candidate,\n `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`,\n );\n return selected;\n }\n if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) {\n logStartCodecCandidateIgnored(\n candidate,\n `no variants with VIDEO-RANGE of ${JSON.stringify(\n videoRanges,\n )} found`,\n );\n return selected;\n }\n if (candidateTier.maxScore < selectedScore) {\n logStartCodecCandidateIgnored(\n candidate,\n `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`,\n );\n return selected;\n }\n // Remove candiates with less preferred codecs or more errors\n if (\n selected &&\n (codecsSetSelectionPreferenceValue(candidate) >=\n codecsSetSelectionPreferenceValue(selected) ||\n candidateTier.fragmentError > codecTiers[selected].fragmentError)\n ) {\n return selected;\n }\n selectedScore = candidateTier.maxScore;\n return candidate;\n },\n undefined,\n );\n return {\n codecSet,\n videoRanges,\n preferHDR,\n minFramerate,\n minBitrate,\n };\n}\n\nfunction logStartCodecCandidateIgnored(codeSet: string, reason: string) {\n logger.log(\n `[abr] start candidates with \"${codeSet}\" ignored because ${reason}`,\n );\n}\n\nexport type AudioTracksByGroup = {\n hasDefaultAudio: boolean;\n hasAutoSelectAudio: boolean;\n groups: Record<string, AudioTrackGroup>;\n};\n\nexport function getAudioTracksByGroup(allAudioTracks: MediaPlaylist[]) {\n return allAudioTracks.reduce(\n (audioTracksByGroup: AudioTracksByGroup, track) => {\n let trackGroup = audioTracksByGroup.groups[track.groupId];\n if (!trackGroup) {\n trackGroup = audioTracksByGroup.groups[track.groupId] = {\n tracks: [],\n channels: { 2: 0 },\n hasDefault: false,\n hasAutoSelect: false,\n };\n }\n trackGroup.tracks.push(track);\n const channelsKey = track.channels || '2';\n trackGroup.channels[channelsKey] =\n (trackGroup.channels[channelsKey] || 0) + 1;\n trackGroup.hasDefault = trackGroup.hasDefault || track.default;\n trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;\n if (trackGroup.hasDefault) {\n audioTracksByGroup.hasDefaultAudio = true;\n }\n if (trackGroup.hasAutoSelect) {\n audioTracksByGroup.hasAutoSelectAudio = true;\n }\n return audioTracksByGroup;\n },\n {\n hasDefaultAudio: false,\n hasAutoSelectAudio: false,\n groups: {},\n },\n );\n}\n\nexport function getCodecTiers(\n levels: Level[],\n audioTracksByGroup: AudioTracksByGroup,\n minAutoLevel: number,\n maxAutoLevel: number,\n): Record<string, CodecSetTier> {\n return levels\n .slice(minAutoLevel, maxAutoLevel + 1)\n .reduce((tiers: Record<string, CodecSetTier>, level) => {\n if (!level.codecSet) {\n return tiers;\n }\n const audioGroups = level.audioGroups;\n let tier = tiers[level.codecSet];\n if (!tier) {\n tiers[level.codecSet] = tier = {\n minBitrate: Infinity,\n minHeight: Infinity,\n minFramerate: Infinity,\n maxScore: 0,\n videoRanges: { SDR: 0 },\n channels: { '2': 0 },\n hasDefaultAudio: !audioGroups,\n fragmentError: 0,\n };\n }\n tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);\n const lesserWidthOrHeight = Math.min(level.height, level.width);\n tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);\n tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);\n tier.maxScore = Math.max(tier.maxScore, level.score);\n tier.fragmentError += level.fragmentError;\n tier.videoRanges[level.videoRange] =\n (tier.videoRanges[level.videoRange] || 0) + 1;\n if (__USE_ALT_AUDIO__ && audioGroups) {\n audioGroups.forEach((audioGroupId) => {\n if (!audioGroupId) {\n return;\n }\n const audioGroup = audioTracksByGroup.groups[audioGroupId];\n if (!audioGroup) {\n return;\n }\n // Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants\n tier.hasDefaultAudio =\n tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio\n ? audioGroup.hasDefault\n : audioGroup.hasAutoSelect ||\n (!audioTracksByGroup.hasDefaultAudio &&\n !audioTracksByGroup.hasAutoSelectAudio);\n Object.keys(audioGroup.channels).forEach((channels) => {\n tier.channels[channels] =\n (tier.channels[channels] || 0) + audioGroup.channels[channels];\n });\n });\n }\n return tiers;\n }, {});\n}\n\nexport function findMatchingOption(\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n tracks: MediaPlaylist[],\n matchPredicate?: (\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n track: MediaPlaylist,\n ) => boolean,\n): number {\n if ('attrs' in option) {\n const index = tracks.indexOf(option);\n if (index !== -1) {\n return index;\n }\n }\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (matchesOption(option, track, matchPredicate)) {\n return i;\n }\n }\n return -1;\n}\n\nexport function matchesOption(\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n track: MediaPlaylist,\n matchPredicate?: (\n option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,\n track: MediaPlaylist,\n ) => boolean,\n): boolean {\n const {\n groupId,\n name,\n lang,\n assocLang,\n characteristics,\n default: isDefault,\n } = option;\n const forced = (option as SubtitleSelectionOption).forced;\n return (\n (groupId === undefined || track.groupId === groupId) &&\n (name === undefined || track.name === name) &&\n (lang === undefined || track.lang === lang) &&\n (lang === undefined || track.assocLang === assocLang) &&\n (isDefault === undefined || track.default === isDefault) &&\n (forced === undefined || track.forced === forced) &&\n (characteristics === undefined ||\n characteristicsMatch(characteristics, track.characteristics)) &&\n (matchPredicate === undefined || matchPredicate(option, track))\n );\n}\n\nfunction characteristicsMatch(\n characteristicsA: string,\n characteristicsB: string = '',\n): boolean {\n const arrA = characteristicsA.split(',');\n const arrB = characteristicsB.split(',');\n // Expects each item to be unique:\n return (\n arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1)\n );\n}\n\nexport function audioMatchPredicate(\n option: MediaPlaylist | AudioSelectionOption,\n track: MediaPlaylist,\n) {\n const { audioCodec, channels } = option;\n return (\n (audioCodec === undefined ||\n (track.audioCodec || '').substring(0, 4) ===\n audioCodec.substring(0, 4)) &&\n (channels === undefined || channels === (track.channels || '2'))\n );\n}\n\nexport function findClosestLevelWithAudioGroup(\n option: MediaPlaylist | AudioSelectionOption,\n levels: Level[],\n allAudioTracks: MediaPlaylist[],\n searchIndex: number,\n matchPredicate: (\n option: MediaPlaylist | AudioSelectionOption,\n track: MediaPlaylist,\n ) => boolean,\n): number {\n const currentLevel = levels[searchIndex];\n // Are there variants with same URI as current level?\n // If so, find a match that does not require any level URI change\n const variants = levels.reduce(\n (variantMap: { [uri: string]: number[] }, level, index) => {\n const uri = level.uri;\n const renditions = variantMap[uri] || (variantMap[uri] = []);\n renditions.push(index);\n return variantMap;\n },\n {},\n );\n const renditions = variants[currentLevel.uri];\n if (renditions.length > 1) {\n searchIndex = Math.max.apply(Math, renditions);\n }\n // Find best match\n const currentVideoRange = currentLevel.videoRange;\n const currentFrameRate = currentLevel.frameRate;\n const currentVideoCodec = currentLevel.codecSet.substring(0, 4);\n const matchingVideo = searchDownAndUpList(\n levels,\n searchIndex,\n (level: Level) => {\n if (\n level.videoRange !== currentVideoRange ||\n level.frameRate !== currentFrameRate ||\n level.codecSet.substring(0, 4) !== currentVideoCodec\n ) {\n return false;\n }\n const audioGroups = level.audioGroups;\n const tracks = allAudioTracks.filter(\n (track): boolean =>\n !audioGroups || audioGroups.indexOf(track.groupId) !== -1,\n );\n return findMatchingOption(option, tracks, matchPredicate) > -1;\n },\n );\n if (matchingVideo > -1) {\n return matchingVideo;\n }\n return searchDownAndUpList(levels, searchIndex, (level: Level) => {\n const audioGroups = level.audioGroups;\n const tracks = allAudioTracks.filter(\n (track): boolean =>\n !audioGroups || audioGroups.indexOf(track.groupId) !== -1,\n );\n return findMatchingOption(option, tracks, matchPredicate) > -1;\n });\n}\n\nfunction searchDownAndUpList(\n arr: any[],\n searchIndex: number,\n predicate: (item: any) => boolean,\n): number {\n for (let i = searchIndex; i; i--) {\n if (predicate(arr[i])) {\n return i;\n }\n }\n for (let i = searchIndex + 1; i < arr.length; i++) {\n if (predicate(arr[i])) {\n return i;\n }\n }\n return -1;\n}\n","import EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\nimport { Events } from '../events';\nimport { ErrorDetails } from '../errors';\nimport { PlaylistLevelType } from '../types/loader';\nimport { logger } from '../utils/logger';\nimport {\n SUPPORTED_INFO_DEFAULT,\n getMediaDecodingInfoPromise,\n requiresMediaCapabilitiesDecodingInfo,\n} from '../utils/mediacapabilities-helper';\nimport {\n getAudioTracksByGroup,\n getCodecTiers,\n getStartCodecTier,\n type AudioTracksByGroup,\n type CodecSetTier,\n} from '../utils/rendition-helper';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { Level, VideoRange } from '../types/level';\nimport type { LoaderStats } from '../types/loader';\nimport type Hls from '../hls';\nimport type {\n FragLoadingData,\n FragLoadedData,\n FragBufferedData,\n LevelLoadedData,\n LevelSwitchingData,\n ManifestLoadingData,\n ErrorData,\n} from '../types/events';\nimport type { AbrComponentAPI } from '../types/component-api';\n\nclass AbrController implements AbrComponentAPI {\n protected hls: Hls;\n private lastLevelLoadSec: number = 0;\n private lastLoadedFragLevel: number = -1;\n private firstSelection: number = -1;\n private _nextAutoLevel: number = -1;\n private nextAutoLevelKey: string = '';\n private audioTracksByGroup: AudioTracksByGroup | null = null;\n private codecTiers: Record<string, CodecSetTier> | null = null;\n private timer: number = -1;\n private fragCurrent: Fragment | null = null;\n private partCurrent: Part | null = null;\n private bitrateTestDelay: number = 0;\n\n public bwEstimator: EwmaBandWidthEstimator;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.bwEstimator = this.initEstimator();\n this.registerListeners();\n }\n\n public resetEstimator(abrEwmaDefaultEstimate?: number) {\n if (abrEwmaDefaultEstimate) {\n logger.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);\n this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;\n }\n this.firstSelection = -1;\n this.bwEstimator = this.initEstimator();\n }\n\n private initEstimator(): EwmaBandWidthEstimator {\n const config = this.hls.config;\n return new EwmaBandWidthEstimator(\n config.abrEwmaSlowVoD,\n config.abrEwmaFastVoD,\n config.abrEwmaDefaultEstimate,\n );\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n protected unregisterListeners() {\n const { hls } = this;\n if (!hls) {\n return;\n }\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this.unregisterListeners();\n this.clearTimer();\n // @ts-ignore\n this.hls = this._abandonRulesCheck = null;\n this.fragCurrent = this.partCurrent = null;\n }\n\n protected onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) {\n this.lastLoadedFragLevel = -1;\n this.firstSelection = -1;\n this.lastLevelLoadSec = 0;\n this.fragCurrent = this.partCurrent = null;\n this.onLevelsUpdated();\n this.clearTimer();\n }\n\n private onLevelsUpdated() {\n if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {\n this.lastLoadedFragLevel = this.fragCurrent.level;\n }\n this._nextAutoLevel = -1;\n this.onMaxAutoLevelUpdated();\n this.codecTiers = null;\n this.audioTracksByGroup = null;\n }\n\n private onMaxAutoLevelUpdated() {\n this.firstSelection = -1;\n this.nextAutoLevelKey = '';\n }\n\n protected onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {\n const frag = data.frag;\n if (this.ignoreFragment(frag)) {\n return;\n }\n if (!frag.bitrateTest) {\n this.fragCurrent = frag;\n this.partCurrent = data.part ?? null;\n }\n this.clearTimer();\n this.timer = self.setInterval(this._abandonRulesCheck, 100);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData,\n ): void {\n this.clearTimer();\n }\n\n protected onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n return;\n }\n switch (data.details) {\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n // Reset last loaded level so that a new selection can be made after calling recoverMediaError\n this.lastLoadedFragLevel = -1;\n this.firstSelection = -1;\n break;\n case ErrorDetails.FRAG_LOAD_TIMEOUT: {\n const frag = data.frag;\n const { fragCurrent, partCurrent: part } = this;\n if (\n frag &&\n fragCurrent &&\n frag.sn === fragCurrent.sn &&\n frag.level === fragCurrent.level\n ) {\n const now = performance.now();\n const stats: LoaderStats = part ? part.stats : frag.stats;\n const timeLoading = now - stats.loading.start;\n const ttfb = stats.loading.first\n ? stats.loading.first - stats.loading.start\n : -1;\n const loadedFirstByte = stats.loaded && ttfb > -1;\n if (loadedFirstByte) {\n const ttfbEstimate = this.bwEstimator.getEstimateTTFB();\n this.bwEstimator.sample(\n timeLoading - Math.min(ttfbEstimate, ttfb),\n stats.loaded,\n );\n } else {\n this.bwEstimator.sampleTTFB(timeLoading);\n }\n }\n break;\n }\n }\n }\n\n private getTimeToLoadFrag(\n timeToFirstByteSec: number,\n bandwidth: number,\n fragSizeBits: number,\n isSwitch: boolean,\n ): number {\n const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;\n const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;\n return fragLoadSec + playlistLoadSec;\n }\n\n protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const config = this.hls.config;\n const { loading } = data.stats;\n const timeLoadingMs = loading.end - loading.start;\n if (Number.isFinite(timeLoadingMs)) {\n this.lastLevelLoadSec = timeLoadingMs / 1000;\n }\n if (data.details.live) {\n this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);\n } else {\n this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);\n }\n }\n\n /*\n This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load\n quickly enough to prevent underbuffering\n */\n private _abandonRulesCheck = () => {\n const { fragCurrent: frag, partCurrent: part, hls } = this;\n const { autoLevelEnabled, media } = hls;\n if (!frag || !media) {\n return;\n }\n\n const now = performance.now();\n const stats: LoaderStats = part ? part.stats : frag.stats;\n const duration = part ? part.duration : frag.duration;\n const timeLoading = now - stats.loading.start;\n const minAutoLevel = hls.minAutoLevel;\n // If frag loading is aborted, complete, or from lowest level, stop timer and return\n if (\n stats.aborted ||\n (stats.loaded && stats.loaded === stats.total) ||\n frag.level <= minAutoLevel\n ) {\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n\n // This check only runs if we're in ABR mode and actually playing\n if (\n !autoLevelEnabled ||\n media.paused ||\n !media.playbackRate ||\n !media.readyState\n ) {\n return;\n }\n\n const bufferInfo = hls.mainForwardBufferInfo;\n if (bufferInfo === null) {\n return;\n }\n\n const ttfbEstimate = this.bwEstimator.getEstimateTTFB();\n const playbackRate = Math.abs(media.playbackRate);\n // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed\n if (\n timeLoading <=\n Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))\n ) {\n return;\n }\n\n // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer\n const bufferStarvationDelay = bufferInfo.len / playbackRate;\n const ttfb = stats.loading.first\n ? stats.loading.first - stats.loading.start\n : -1;\n const loadedFirstByte = stats.loaded && ttfb > -1;\n const bwEstimate: number = this.getBwEstimate();\n const levels = hls.levels;\n const level = levels[frag.level];\n const expectedLen =\n stats.total ||\n Math.max(stats.loaded, Math.round((duration * level.averageBitrate) / 8));\n let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;\n if (timeStreaming < 1 && loadedFirstByte) {\n timeStreaming = Math.min(timeLoading, (stats.loaded * 8) / bwEstimate);\n }\n const loadRate = loadedFirstByte\n ? (stats.loaded * 1000) / timeStreaming\n : 0;\n // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment\n const fragLoadedDelay = loadRate\n ? (expectedLen - stats.loaded) / loadRate\n : (expectedLen * 8) / bwEstimate + ttfbEstimate / 1000;\n // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left\n if (fragLoadedDelay <= bufferStarvationDelay) {\n return;\n }\n\n const bwe = loadRate ? loadRate * 8 : bwEstimate;\n let fragLevelNextLoadedDelay: number = Number.POSITIVE_INFINITY;\n let nextLoadLevel: number;\n // Iterate through lower level and try to find the largest one that avoids rebuffering\n for (\n nextLoadLevel = frag.level - 1;\n nextLoadLevel > minAutoLevel;\n nextLoadLevel--\n ) {\n // compute time to load next fragment at lower level\n // 8 = bits per byte (bps/Bps)\n const levelNextBitrate = levels[nextLoadLevel].maxBitrate;\n fragLevelNextLoadedDelay = this.getTimeToLoadFrag(\n ttfbEstimate / 1000,\n bwe,\n duration * levelNextBitrate,\n !levels[nextLoadLevel].details,\n );\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n break;\n }\n }\n // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing\n // to load the current one\n if (fragLevelNextLoadedDelay >= fragLoadedDelay) {\n return;\n }\n\n // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down\n if (fragLevelNextLoadedDelay > duration * 10) {\n return;\n }\n hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;\n if (loadedFirstByte) {\n // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time\n this.bwEstimator.sample(\n timeLoading - Math.min(ttfbEstimate, ttfb),\n stats.loaded,\n );\n } else {\n // If there has been no loading progress, sample TTFB\n this.bwEstimator.sampleTTFB(timeLoading);\n }\n const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;\n if (\n this.getBwEstimate() * this.hls.config.abrBandWidthUpFactor >\n nextLoadLevelBitrate\n ) {\n this.resetEstimator(nextLoadLevelBitrate);\n }\n\n this.clearTimer();\n logger.warn(`[abr] Fragment ${frag.sn}${\n part ? ' part ' + part.index : ''\n } of level ${frag.level} is loading too slowly;\n Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s\n Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s\n Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(\n 3,\n )} s\n TTFB estimate: ${ttfb | 0} ms\n Current BW estimate: ${\n Number.isFinite(bwEstimate) ? bwEstimate | 0 : 'Unknown'\n } bps\n New BW estimate: ${this.getBwEstimate() | 0} bps\n Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);\n hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, { frag, part, stats });\n };\n\n protected onFragLoaded(\n event: Events.FRAG_LOADED,\n { frag, part }: FragLoadedData,\n ) {\n const stats = part ? part.stats : frag.stats;\n if (frag.type === PlaylistLevelType.MAIN) {\n this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n if (frag.level === this._nextAutoLevel) {\n this._nextAutoLevel = -1;\n }\n this.firstSelection = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const duration = part ? part.duration : frag.duration;\n const level = this.hls.levels[frag.level];\n const loadedBytes =\n (level.loaded ? level.loaded.bytes : 0) + stats.loaded;\n const loadedDuration =\n (level.loaded ? level.loaded.duration : 0) + duration;\n level.loaded = { bytes: loadedBytes, duration: loadedDuration };\n level.realBitrate = Math.round((8 * loadedBytes) / loadedDuration);\n }\n if (frag.bitrateTest) {\n const fragBufferedData: FragBufferedData = {\n stats,\n frag,\n part,\n id: frag.type,\n };\n this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);\n frag.bitrateTest = false;\n } else {\n // store level id after successful fragment load for playback\n this.lastLoadedFragLevel = frag.level;\n }\n }\n\n protected onFragBuffered(\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData,\n ) {\n const { frag, part } = data;\n const stats = part?.stats.loaded ? part.stats : frag.stats;\n\n if (stats.aborted) {\n return;\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;\n // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch\n // is used. If we used buffering in that case, our BW estimate sample will be very large.\n const processingMs =\n stats.parsing.end -\n stats.loading.start -\n Math.min(\n stats.loading.first - stats.loading.start,\n this.bwEstimator.getEstimateTTFB(),\n );\n this.bwEstimator.sample(processingMs, stats.loaded);\n stats.bwEstimate = this.getBwEstimate();\n if (frag.bitrateTest) {\n this.bitrateTestDelay = processingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n\n private ignoreFragment(frag: Fragment): boolean {\n // Only count non-alt-audio frags which were actually buffered in our BW calculations\n return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';\n }\n\n public clearTimer() {\n if (this.timer > -1) {\n self.clearInterval(this.timer);\n this.timer = -1;\n }\n }\n\n public get firstAutoLevel(): number {\n const { maxAutoLevel, minAutoLevel } = this.hls;\n const bwEstimate = this.getBwEstimate();\n const maxStartDelay = this.hls.config.maxStarvationDelay;\n const abrAutoLevel = this.findBestLevel(\n bwEstimate,\n minAutoLevel,\n maxAutoLevel,\n 0,\n maxStartDelay,\n 1,\n 1,\n );\n if (abrAutoLevel > -1) {\n return abrAutoLevel;\n }\n const firstLevel = this.hls.firstLevel;\n const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);\n logger.warn(\n `[abr] Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`,\n );\n return clamped;\n }\n\n public get forcedAutoLevel(): number {\n if (this.nextAutoLevelKey) {\n return -1;\n }\n return this._nextAutoLevel;\n }\n\n // return next auto level\n public get nextAutoLevel(): number {\n const forcedAutoLevel = this.forcedAutoLevel;\n const bwEstimator = this.bwEstimator;\n const useEstimate = bwEstimator.canEstimate();\n const loadedFirstFrag = this.lastLoadedFragLevel > -1;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (\n forcedAutoLevel !== -1 &&\n (!useEstimate ||\n !loadedFirstFrag ||\n this.nextAutoLevelKey === this.getAutoLevelKey())\n ) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n const nextABRAutoLevel =\n useEstimate && loadedFirstFrag\n ? this.getNextABRAutoLevel()\n : this.firstAutoLevel;\n\n // use forced auto level while it hasn't errored more than ABR selection\n if (forcedAutoLevel !== -1) {\n const levels = this.hls.levels;\n if (\n levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) &&\n levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError\n ) {\n return forcedAutoLevel;\n }\n }\n\n // save result until state has changed\n this._nextAutoLevel = nextABRAutoLevel;\n this.nextAutoLevelKey = this.getAutoLevelKey();\n\n return nextABRAutoLevel;\n }\n\n private getAutoLevelKey(): string {\n return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;\n }\n\n private getNextABRAutoLevel(): number {\n const { fragCurrent, partCurrent, hls } = this;\n const { maxAutoLevel, config, minAutoLevel } = hls;\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n const avgbw = this.getBwEstimate();\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferStarvationDelay = this.getStarvationDelay();\n\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n if (bufferStarvationDelay) {\n const bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay,\n 0,\n bwFactor,\n bwUpFactor,\n );\n if (bestLevel >= 0) {\n return bestLevel;\n }\n }\n // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering\n let maxStarvationDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxStarvationDelay)\n : config.maxStarvationDelay;\n\n if (!bufferStarvationDelay) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n const bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxLoadingDelay)\n : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.info(\n `[abr] bitrate test took ${Math.round(\n 1000 * bitrateTestDelay,\n )}ms, set first fragment max fetchDuration to ${Math.round(\n 1000 * maxStarvationDelay,\n )} ms`,\n );\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n const bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay,\n maxStarvationDelay,\n bwFactor,\n bwUpFactor,\n );\n logger.info(\n `[abr] ${\n bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'\n }, optimal quality level ${bestLevel}`,\n );\n if (bestLevel > -1) {\n return bestLevel;\n }\n // If no matching level found, see if min auto level would be a better option\n const minLevel = hls.levels[minAutoLevel];\n const autoLevel = hls.levels[hls.loadLevel];\n if (minLevel?.bitrate < autoLevel?.bitrate) {\n return minAutoLevel;\n }\n // or if bitrate is not lower, continue to use loadLevel\n return hls.loadLevel;\n }\n\n private getStarvationDelay(): number {\n const hls = this.hls;\n const media = hls.media;\n if (!media) {\n return Infinity;\n }\n // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n const playbackRate =\n media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;\n const bufferInfo = hls.mainForwardBufferInfo;\n return (bufferInfo ? bufferInfo.len : 0) / playbackRate;\n }\n\n private getBwEstimate(): number {\n return this.bwEstimator.canEstimate()\n ? this.bwEstimator.getEstimate()\n : this.hls.config.abrEwmaDefaultEstimate;\n }\n\n private findBestLevel(\n currentBw: number,\n minAutoLevel: number,\n maxAutoLevel: number,\n bufferStarvationDelay: number,\n maxStarvationDelay: number,\n bwFactor: number,\n bwUpFactor: number,\n ): number {\n const maxFetchDuration: number = bufferStarvationDelay + maxStarvationDelay;\n const lastLoadedFragLevel = this.lastLoadedFragLevel;\n const selectionBaseLevel =\n lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;\n const { fragCurrent, partCurrent } = this;\n const { levels, allAudioTracks, loadLevel, config } = this.hls;\n if (levels.length === 1) {\n return 0;\n }\n const level: Level | undefined = levels[selectionBaseLevel];\n const live = !!level?.details?.live;\n const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;\n let currentCodecSet: string | undefined;\n let currentVideoRange: VideoRange | undefined = 'SDR';\n let currentFrameRate = level?.frameRate || 0;\n\n const { audioPreference, videoPreference } = config;\n const audioTracksByGroup =\n this.audioTracksByGroup ||\n (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));\n if (firstSelection) {\n if (this.firstSelection !== -1) {\n return this.firstSelection;\n }\n const codecTiers =\n this.codecTiers ||\n (this.codecTiers = getCodecTiers(\n levels,\n audioTracksByGroup,\n minAutoLevel,\n maxAutoLevel,\n ));\n const startTier = getStartCodecTier(\n codecTiers,\n currentVideoRange,\n currentBw,\n audioPreference,\n videoPreference,\n );\n const { codecSet, videoRanges, minFramerate, minBitrate, preferHDR } =\n startTier;\n currentCodecSet = codecSet;\n currentVideoRange = preferHDR\n ? videoRanges[videoRanges.length - 1]\n : videoRanges[0];\n currentFrameRate = minFramerate;\n currentBw = Math.max(currentBw, minBitrate);\n logger.log(`[abr] picked start tier ${JSON.stringify(startTier)}`);\n } else {\n currentCodecSet = level?.codecSet;\n currentVideoRange = level?.videoRange;\n }\n\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n\n const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;\n const levelsSkipped: number[] = [];\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n const levelInfo = levels[i];\n const upSwitch = i > selectionBaseLevel;\n if (!levelInfo) {\n continue;\n }\n if (\n __USE_MEDIA_CAPABILITIES__ &&\n config.useMediaCapabilities &&\n !levelInfo.supportedResult &&\n !levelInfo.supportedPromise\n ) {\n const mediaCapabilities = navigator.mediaCapabilities as\n | MediaCapabilities\n | undefined;\n if (\n typeof mediaCapabilities?.decodingInfo === 'function' &&\n requiresMediaCapabilitiesDecodingInfo(\n levelInfo,\n audioTracksByGroup,\n currentVideoRange,\n currentFrameRate,\n currentBw,\n audioPreference,\n )\n ) {\n levelInfo.supportedPromise = getMediaDecodingInfoPromise(\n levelInfo,\n audioTracksByGroup,\n mediaCapabilities,\n );\n levelInfo.supportedPromise.then((decodingInfo) => {\n if (!this.hls) {\n return;\n }\n levelInfo.supportedResult = decodingInfo;\n const levels = this.hls.levels;\n const index = levels.indexOf(levelInfo);\n if (decodingInfo.error) {\n logger.warn(\n `[abr] MediaCapabilities decodingInfo error: \"${\n decodingInfo.error\n }\" for level ${index} ${JSON.stringify(decodingInfo)}`,\n );\n } else if (!decodingInfo.supported) {\n logger.warn(\n `[abr] Unsupported MediaCapabilities decodingInfo result for level ${index} ${JSON.stringify(\n decodingInfo,\n )}`,\n );\n if (index > -1 && levels.length > 1) {\n logger.log(`[abr] Removing unsupported level ${index}`);\n this.hls.removeLevel(index);\n }\n }\n });\n } else {\n levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;\n }\n }\n\n // skip candidates which change codec-family or video-range,\n // and which decrease or increase frame-rate for up and down-switch respectfully\n if (\n (currentCodecSet && levelInfo.codecSet !== currentCodecSet) ||\n (currentVideoRange && levelInfo.videoRange !== currentVideoRange) ||\n (upSwitch && currentFrameRate > levelInfo.frameRate) ||\n (!upSwitch &&\n currentFrameRate > 0 &&\n currentFrameRate < levelInfo.frameRate) ||\n (levelInfo.supportedResult &&\n !levelInfo.supportedResult.decodingInfoResults?.[0].smooth)\n ) {\n levelsSkipped.push(i);\n continue;\n }\n\n const levelDetails = levelInfo.details;\n const avgDuration =\n (partCurrent\n ? levelDetails?.partTarget\n : levelDetails?.averagetargetduration) || currentFragDuration;\n\n let adjustedbw: number;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (!upSwitch) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)\n const bitrate: number =\n currentFragDuration &&\n bufferStarvationDelay >= currentFragDuration * 2 &&\n maxStarvationDelay === 0\n ? levels[i].averageBitrate\n : levels[i].maxBitrate;\n const fetchDuration: number = this.getTimeToLoadFrag(\n ttfbEstimateSec,\n adjustedbw,\n bitrate * avgDuration,\n levelDetails === undefined,\n );\n\n const canSwitchWithinTolerance =\n // if adjusted bw is greater than level bitrate AND\n adjustedbw >= bitrate &&\n // no level change, or new level has no error history\n (i === lastLoadedFragLevel ||\n (levelInfo.loadError === 0 && levelInfo.fragmentError === 0)) &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1\n (fetchDuration <= ttfbEstimateSec ||\n !Number.isFinite(fetchDuration) ||\n (live && !this.bitrateTestDelay) ||\n fetchDuration < maxFetchDuration);\n if (canSwitchWithinTolerance) {\n const forcedAutoLevel = this.forcedAutoLevel;\n if (\n i !== loadLevel &&\n (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)\n ) {\n if (levelsSkipped.length) {\n logger.trace(\n `[abr] Skipped level(s) ${levelsSkipped.join(\n ',',\n )} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:\"${\n levels[levelsSkipped[0]].codecs\n }\" ${levels[levelsSkipped[0]].videoRange}; not compatible with \"${\n level.codecs\n }\" ${currentVideoRange}`,\n );\n }\n logger.info(\n `[abr] switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(\n adjustedbw,\n )})-bitrate=${Math.round(\n adjustedbw - bitrate,\n )} ttfb:${ttfbEstimateSec.toFixed(\n 1,\n )} avgDuration:${avgDuration.toFixed(\n 1,\n )} maxFetchDuration:${maxFetchDuration.toFixed(\n 1,\n )} fetchDuration:${fetchDuration.toFixed(\n 1,\n )} firstSelection:${firstSelection} codecSet:${currentCodecSet} videoRange:${currentVideoRange} hls.loadLevel:${loadLevel}`,\n );\n }\n if (firstSelection) {\n this.firstSelection = i;\n }\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n public set nextAutoLevel(nextLevel: number) {\n const { maxAutoLevel, minAutoLevel } = this.hls;\n const value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);\n if (this._nextAutoLevel !== value) {\n this.nextAutoLevelKey = '';\n this._nextAutoLevel = value;\n }\n }\n}\n\nexport default AbrController;\n","/**\n * @ignore\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\nexport default class TaskLoop {\n private readonly _boundTick: () => void;\n private _tickTimer: number | null = null;\n private _tickInterval: number | null = null;\n private _tickCallCount = 0;\n\n constructor() {\n this._boundTick = this.tick.bind(this);\n }\n\n public destroy() {\n this.onHandlerDestroying();\n this.onHandlerDestroyed();\n }\n\n protected onHandlerDestroying() {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n protected onHandlerDestroyed() {}\n\n public hasInterval(): boolean {\n return !!this._tickInterval;\n }\n\n public hasNextTick(): boolean {\n return !!this._tickTimer;\n }\n\n /**\n * @param millis - Interval time (ms)\n * @eturns True when interval has been scheduled, false when already scheduled (no effect)\n */\n public setInterval(millis: number): boolean {\n if (!this._tickInterval) {\n this._tickCallCount = 0;\n this._tickInterval = self.setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when interval was cleared, false when none was set (no effect)\n */\n public clearInterval(): boolean {\n if (this._tickInterval) {\n self.clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when timeout was cleared, false when none was set (no effect)\n */\n public clearNextTick(): boolean {\n if (this._tickTimer) {\n self.clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n public tick(): void {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.tickImmediate();\n }\n this._tickCallCount = 0;\n }\n }\n\n public tickImmediate(): void {\n this.clearNextTick();\n this._tickTimer = self.setTimeout(this._boundTick, 0);\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n protected doTick(): void {}\n}\n","import { Events } from '../events';\nimport { Fragment, Part } from '../loader/fragment';\nimport { PlaylistLevelType } from '../types/loader';\nimport type { SourceBufferName } from '../types/buffer';\nimport type {\n FragmentBufferedRange,\n FragmentEntity,\n FragmentTimeRange,\n} from '../types/fragment-tracker';\nimport type { ComponentAPI } from '../types/component-api';\nimport type {\n BufferAppendedData,\n FragBufferedData,\n FragLoadedData,\n} from '../types/events';\nimport type Hls from '../hls';\n\nexport const enum FragmentState {\n NOT_LOADED = 'NOT_LOADED',\n APPENDING = 'APPENDING',\n PARTIAL = 'PARTIAL',\n OK = 'OK',\n}\n\nexport class FragmentTracker implements ComponentAPI {\n private activePartLists: { [key in PlaylistLevelType]?: Part[] } =\n Object.create(null);\n private endListFragments: { [key in PlaylistLevelType]?: FragmentEntity } =\n Object.create(null);\n private fragments: Partial<Record<string, FragmentEntity>> =\n Object.create(null);\n private timeRanges:\n | {\n [key in SourceBufferName]?: TimeRanges;\n }\n | null = Object.create(null);\n\n private bufferPadding: number = 0.2;\n private hls: Hls;\n private hasGaps: boolean = false;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n\n public destroy() {\n this._unregisterListeners();\n // @ts-ignore\n this.fragments =\n // @ts-ignore\n this.activePartLists =\n // @ts-ignore\n this.endListFragments =\n this.timeRanges =\n null;\n }\n\n /**\n * Return a Fragment or Part with an appended range that matches the position and levelType\n * Otherwise, return null\n */\n public getAppendedFrag(\n position: number,\n levelType: PlaylistLevelType,\n ): Fragment | Part | null {\n const activeParts = this.activePartLists[levelType];\n if (activeParts) {\n for (let i = activeParts.length; i--; ) {\n const activePart = activeParts[i];\n if (!activePart) {\n break;\n }\n const appendedPTS = activePart.end;\n if (\n activePart.start <= position &&\n appendedPTS !== null &&\n position <= appendedPTS\n ) {\n return activePart;\n }\n }\n }\n return this.getBufferedFrag(position, levelType);\n }\n\n /**\n * Return a buffered Fragment that matches the position and levelType.\n * A buffered Fragment is one whose loading, parsing and appending is done (completed or \"partial\" meaning aborted).\n * If not found any Fragment, return null\n */\n public getBufferedFrag(\n position: number,\n levelType: PlaylistLevelType,\n ): Fragment | null {\n const { fragments } = this;\n const keys = Object.keys(fragments);\n for (let i = keys.length; i--; ) {\n const fragmentEntity = fragments[keys[i]];\n if (fragmentEntity?.body.type === levelType && fragmentEntity.buffered) {\n const frag = fragmentEntity.body;\n if (frag.start <= position && position <= frag.end) {\n return frag;\n }\n }\n }\n return null;\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n */\n public detectEvictedFragments(\n elementaryStream: SourceBufferName,\n timeRange: TimeRanges,\n playlistType: PlaylistLevelType,\n appendedPart?: Part | null,\n ) {\n if (this.timeRanges) {\n this.timeRanges[elementaryStream] = timeRange;\n }\n // Check if any flagged fragments have been unloaded\n // excluding anything newer than appendedPartSn\n const appendedPartSn = (appendedPart?.fragment.sn || -1) as number;\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (appendedPartSn >= (fragmentEntity.body.sn as number)) {\n return;\n }\n if (!fragmentEntity.buffered && !fragmentEntity.loaded) {\n if (fragmentEntity.body.type === playlistType) {\n this.removeFragment(fragmentEntity.body);\n }\n return;\n }\n const esData = fragmentEntity.range[elementaryStream];\n if (!esData) {\n return;\n }\n esData.time.some((time: FragmentTimeRange) => {\n const isNotBuffered = !this.isTimeBuffered(\n time.startPTS,\n time.endPTS,\n timeRange,\n );\n if (isNotBuffered) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n }\n return isNotBuffered;\n });\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n */\n public detectPartialFragments(data: FragBufferedData) {\n const timeRanges = this.timeRanges;\n const { frag, part } = data;\n if (!timeRanges || frag.sn === 'initSegment') {\n return;\n }\n\n const fragKey = getFragmentKey(frag);\n const fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity || (fragmentEntity.buffered && frag.gap)) {\n return;\n }\n const isFragHint = !frag.relurl;\n Object.keys(timeRanges).forEach((elementaryStream: SourceBufferName) => {\n const streamInfo = frag.elementaryStreams[elementaryStream];\n if (!streamInfo) {\n return;\n }\n const timeRange = timeRanges[elementaryStream] as TimeRanges;\n const partial = isFragHint || streamInfo.partial === true;\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(\n frag,\n part,\n partial,\n timeRange,\n );\n });\n fragmentEntity.loaded = null;\n if (Object.keys(fragmentEntity.range).length) {\n fragmentEntity.buffered = true;\n const endList = (fragmentEntity.body.endList =\n frag.endList || fragmentEntity.body.endList);\n if (endList) {\n this.endListFragments[fragmentEntity.body.type] = fragmentEntity;\n }\n if (!isPartial(fragmentEntity)) {\n // Remove older fragment parts from lookup after frag is tracked as buffered\n this.removeParts((frag.sn as number) - 1, frag.type);\n }\n } else {\n // remove fragment if nothing was appended\n this.removeFragment(fragmentEntity.body);\n }\n }\n\n private removeParts(snToKeep: number, levelType: PlaylistLevelType) {\n const activeParts = this.activePartLists[levelType];\n if (!activeParts) {\n return;\n }\n this.activePartLists[levelType] = activeParts.filter(\n (part) => (part.fragment.sn as number) >= snToKeep,\n );\n }\n\n public fragBuffered(frag: Fragment, force?: true) {\n const fragKey = getFragmentKey(frag);\n let fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity && force) {\n fragmentEntity = this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded: null,\n buffered: false,\n range: Object.create(null),\n };\n if (frag.gap) {\n this.hasGaps = true;\n }\n }\n if (fragmentEntity) {\n fragmentEntity.loaded = null;\n fragmentEntity.buffered = true;\n }\n }\n\n private getBufferedTimes(\n fragment: Fragment,\n part: Part | null,\n partial: boolean,\n timeRange: TimeRanges,\n ): FragmentBufferedRange {\n const buffered: FragmentBufferedRange = {\n time: [],\n partial,\n };\n const startPTS = fragment.start;\n const endPTS = fragment.end;\n const minEndPTS = fragment.minEndPTS || endPTS;\n const maxStartPTS = fragment.maxStartPTS || startPTS;\n for (let i = 0; i < timeRange.length; i++) {\n const startTime = timeRange.start(i) - this.bufferPadding;\n const endTime = timeRange.end(i) + this.bufferPadding;\n if (maxStartPTS >= startTime && minEndPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i)),\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n const start = Math.max(startPTS, timeRange.start(i));\n const end = Math.min(endPTS, timeRange.end(i));\n if (end > start) {\n buffered.partial = true;\n // Check for intersection with buffer\n // Get playable sections of the fragment\n buffered.time.push({\n startPTS: start,\n endPTS: end,\n });\n }\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n return buffered;\n }\n\n /**\n * Gets the partial fragment for a certain time\n */\n public getPartialFragment(time: number): Fragment | null {\n let bestFragment: Fragment | null = null;\n let timePadding: number;\n let startTime: number;\n let endTime: number;\n let bestOverlap: number = 0;\n const { bufferPadding, fragments } = this;\n Object.keys(fragments).forEach((key) => {\n const fragmentEntity = fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.start - bufferPadding;\n endTime = fragmentEntity.body.end + bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n public isEndListAppended(type: PlaylistLevelType): boolean {\n const lastFragmentEntity = this.endListFragments[type];\n return (\n lastFragmentEntity !== undefined &&\n (lastFragmentEntity.buffered || isPartial(lastFragmentEntity))\n );\n }\n\n public getState(fragment: Fragment): FragmentState {\n const fragKey = getFragmentKey(fragment);\n const fragmentEntity = this.fragments[fragKey];\n\n if (fragmentEntity) {\n if (!fragmentEntity.buffered) {\n return FragmentState.APPENDING;\n } else if (isPartial(fragmentEntity)) {\n return FragmentState.PARTIAL;\n } else {\n return FragmentState.OK;\n }\n }\n\n return FragmentState.NOT_LOADED;\n }\n\n private isTimeBuffered(\n startPTS: number,\n endPTS: number,\n timeRange: TimeRanges,\n ): boolean {\n let startTime;\n let endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n private onFragLoaded(event: Events.FRAG_LOADED, data: FragLoadedData) {\n const { frag, part } = data;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (frag.sn === 'initSegment' || frag.bitrateTest) {\n return;\n }\n\n // Fragment entity `loaded` FragLoadedData is null when loading parts\n const loaded = part ? null : data;\n\n const fragKey = getFragmentKey(frag);\n this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded,\n buffered: false,\n range: Object.create(null),\n };\n }\n\n private onBufferAppended(\n event: Events.BUFFER_APPENDED,\n data: BufferAppendedData,\n ) {\n const { frag, part, timeRanges } = data;\n if (frag.sn === 'initSegment') {\n return;\n }\n const playlistType = frag.type;\n if (part) {\n let activeParts = this.activePartLists[playlistType];\n if (!activeParts) {\n this.activePartLists[playlistType] = activeParts = [];\n }\n activeParts.push(part);\n }\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = timeRanges;\n Object.keys(timeRanges).forEach((elementaryStream: SourceBufferName) => {\n const timeRange = timeRanges[elementaryStream] as TimeRanges;\n this.detectEvictedFragments(\n elementaryStream,\n timeRange,\n playlistType,\n part,\n );\n });\n }\n\n private onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n this.detectPartialFragments(data);\n }\n\n private hasFragment(fragment: Fragment): boolean {\n const fragKey = getFragmentKey(fragment);\n return !!this.fragments[fragKey];\n }\n\n public hasParts(type: PlaylistLevelType): boolean {\n return !!this.activePartLists[type]?.length;\n }\n\n public removeFragmentsInRange(\n start: number,\n end: number,\n playlistType: PlaylistLevelType,\n withGapOnly?: boolean,\n unbufferedOnly?: boolean,\n ) {\n if (withGapOnly && !this.hasGaps) {\n return;\n }\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n const frag = fragmentEntity.body;\n if (frag.type !== playlistType || (withGapOnly && !frag.gap)) {\n return;\n }\n if (\n frag.start < end &&\n frag.end > start &&\n (fragmentEntity.buffered || unbufferedOnly)\n ) {\n this.removeFragment(frag);\n }\n });\n }\n\n public removeFragment(fragment: Fragment) {\n const fragKey = getFragmentKey(fragment);\n fragment.stats.loaded = 0;\n fragment.clearElementaryStreamInfo();\n const activeParts = this.activePartLists[fragment.type];\n if (activeParts) {\n const snToRemove = fragment.sn;\n this.activePartLists[fragment.type] = activeParts.filter(\n (part) => part.fragment.sn !== snToRemove,\n );\n }\n delete this.fragments[fragKey];\n if (fragment.endList) {\n delete this.endListFragments[fragment.type];\n }\n }\n\n public removeAllFragments() {\n this.fragments = Object.create(null);\n this.endListFragments = Object.create(null);\n this.activePartLists = Object.create(null);\n this.hasGaps = false;\n }\n}\n\nfunction isPartial(fragmentEntity: FragmentEntity): boolean {\n return (\n fragmentEntity.buffered &&\n (fragmentEntity.body.gap ||\n fragmentEntity.range.video?.partial ||\n fragmentEntity.range.audio?.partial ||\n fragmentEntity.range.audiovideo?.partial)\n );\n}\n\nfunction getFragmentKey(fragment: Fragment): string {\n return `${fragment.type}_${fragment.level}_${fragment.sn}`;\n}\n","/**\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 './level-helper';\n\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../loader/level-details';\n\nexport function findFirstFragWithCC(\n fragments: Fragment[],\n cc: number,\n): Fragment | null {\n for (let i = 0, len = fragments.length; i < len; i++) {\n if (fragments[i]?.cc === cc) {\n return fragments[i];\n }\n }\n return null;\n}\n\nexport function shouldAlignOnDiscontinuities(\n lastFrag: Fragment | null,\n switchDetails: LevelDetails | undefined,\n details: LevelDetails,\n): switchDetails is LevelDetails & boolean {\n if (switchDetails) {\n if (\n details.endCC > details.startCC ||\n (lastFrag && lastFrag.cc < details.startCC)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag(\n prevDetails: LevelDetails,\n curDetails: LevelDetails,\n) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nfunction adjustFragmentStart(frag: Fragment, sliding: number) {\n if (frag) {\n const start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n}\n\nexport function adjustSlidingStart(sliding: number, details: LevelDetails) {\n // Update segments\n const fragments = details.fragments;\n for (let i = 0, len = fragments.length; i < len; i++) {\n adjustFragmentStart(fragments[i], sliding);\n }\n // Update LL-HLS parts at the end of the playlist\n if (details.fragmentHint) {\n adjustFragmentStart(details.fragmentHint, sliding);\n }\n details.alignedSliding = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastFrag\n * @param lastLevel\n * @param details\n */\nexport function alignStream(\n lastFrag: Fragment | null,\n switchDetails: LevelDetails | undefined,\n details: LevelDetails,\n) {\n if (!switchDetails) {\n return;\n }\n alignDiscontinuities(lastFrag, details, switchDetails);\n if (!details.alignedSliding && switchDetails) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignMediaPlaylistByPDT(details, switchDetails);\n }\n if (!details.alignedSliding && switchDetails && !details.skippedSegments) {\n // Try to align on sn so that we pick a better start fragment.\n // Do not perform this on playlists with delta updates as this is only to align levels on switch\n // and adjustSliding only adjusts fragments after skippedSegments.\n adjustSliding(switchDetails, details);\n }\n}\n\n/**\n * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n * discontinuity sequence.\n * @param lastFrag - The last Fragment which shares the same discontinuity sequence\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nfunction alignDiscontinuities(\n lastFrag: Fragment | null,\n details: LevelDetails,\n switchDetails: LevelDetails | undefined,\n) {\n if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(\n switchDetails,\n details,\n );\n if (referenceFrag && Number.isFinite(referenceFrag.start)) {\n logger.log(\n `Adjusting PTS using last level due to CC increase within current level ${details.url}`,\n );\n adjustSlidingStart(referenceFrag.start, details);\n }\n }\n}\n\n/**\n * Ensures appropriate time-alignment between renditions based on PDT.\n * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs\n * for the last discontinuity sequence number shared by both playlists when present,\n * and uses the \"wallclock\"/PDT timeline as a cross-reference to `details`, adjusting the presentation\n * times/timelines of `details` accordingly.\n * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,\n * the primary purpose of this function is to ensure the \"local timelines\" of audio/subtitle tracks\n * are aligned to the main/video timeline, using PDT as the cross-reference/\"anchor\" that should\n * be consistent across playlists, per the HLS spec.\n * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).\n * @param refDetails - The details of the reference rendition with start and PDT times for alignment.\n */\nexport function alignMediaPlaylistByPDT(\n details: LevelDetails,\n refDetails: LevelDetails,\n) {\n if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {\n return;\n }\n\n const fragments = details.fragments;\n const refFragments = refDetails.fragments;\n if (!fragments.length || !refFragments.length) {\n return;\n }\n\n // Calculate a delta to apply to all fragments according to the delta in PDT times and start times\n // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.\n // If a fragment of the same discontinuity was not found use the middle fragment of both.\n let refFrag: Fragment | null | undefined;\n let frag: Fragment | null | undefined;\n const targetCC = Math.min(refDetails.endCC, details.endCC);\n if (refDetails.startCC < targetCC && details.startCC < targetCC) {\n refFrag = findFirstFragWithCC(refFragments, targetCC);\n frag = findFirstFragWithCC(fragments, targetCC);\n }\n if (!refFrag || !frag) {\n refFrag = refFragments[Math.floor(refFragments.length / 2)];\n frag =\n findFirstFragWithCC(fragments, refFrag.cc) ||\n fragments[Math.floor(fragments.length / 2)];\n }\n const refPDT = refFrag.programDateTime;\n const targetPDT = frag.programDateTime;\n if (!refPDT || !targetPDT) {\n return;\n }\n\n const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);\n adjustSlidingStart(delta, details);\n}\n","import { ErrorTypes, ErrorDetails } from '../errors';\nimport { Fragment } from './fragment';\nimport {\n Loader,\n LoaderConfiguration,\n FragmentLoaderContext,\n} from '../types/loader';\nimport { getLoaderConfigWithoutReties } from '../utils/error-helper';\nimport type { HlsConfig } from '../config';\nimport type { BaseSegment, Part } from './fragment';\nimport type {\n ErrorData,\n FragLoadedData,\n PartsLoadedData,\n} from '../types/events';\n\nconst MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb\n\nexport default class FragmentLoader {\n private readonly config: HlsConfig;\n private loader: Loader<FragmentLoaderContext> | null = null;\n private partLoadTimeout: number = -1;\n\n constructor(config: HlsConfig) {\n this.config = config;\n }\n\n destroy() {\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n }\n\n abort() {\n if (this.loader) {\n // Abort the loader for current fragment. Only one may load at any given time\n this.loader.abort();\n }\n }\n\n load(\n frag: Fragment,\n onProgress?: FragmentLoadProgressCallback,\n ): Promise<FragLoadedData> {\n const url = frag.url;\n if (!url) {\n return Promise.reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n error: new Error(\n `Fragment does not have a ${url ? 'part list' : 'url'}`,\n ),\n networkDetails: null,\n }),\n );\n }\n this.abort();\n\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap) {\n if (frag.tagList.some((tags) => tags[0] === 'GAP')) {\n reject(createGapLoadError(frag));\n return;\n } else {\n // Reset temporary treatment as GAP tag\n frag.gap = false;\n }\n }\n const loader =\n (this.loader =\n frag.loader =\n FragmentILoader\n ? new FragmentILoader(config)\n : (new DefaultILoader(config) as Loader<FragmentLoaderContext>));\n const loaderContext = createLoaderContext(frag);\n const loadPolicy = getLoaderConfigWithoutReties(\n config.fragLoadPolicy.default,\n );\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE,\n };\n // Assign frag stats to the loader's stats reference\n frag.stats = loader.stats;\n loader.load(loaderContext, loaderConfig, {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n let payload = response.data as ArrayBuffer;\n if (context.resetIV && frag.decryptdata) {\n frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));\n payload = payload.slice(16);\n }\n resolve({\n frag,\n part: null,\n payload,\n networkDetails,\n });\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n response: { url, data: undefined, ...response },\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats,\n }),\n );\n },\n onAbort: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n error: new Error('Aborted'),\n networkDetails,\n stats,\n }),\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats,\n }),\n );\n },\n onProgress: (stats, context, data, networkDetails) => {\n if (onProgress) {\n onProgress({\n frag,\n part: null,\n payload: data as ArrayBuffer,\n networkDetails,\n });\n }\n },\n });\n });\n }\n\n public loadPart(\n frag: Fragment,\n part: Part,\n onProgress: FragmentLoadProgressCallback,\n ): Promise<FragLoadedData> {\n this.abort();\n\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap || part.gap) {\n reject(createGapLoadError(frag, part));\n return;\n }\n const loader =\n (this.loader =\n frag.loader =\n FragmentILoader\n ? new FragmentILoader(config)\n : (new DefaultILoader(config) as Loader<FragmentLoaderContext>));\n const loaderContext = createLoaderContext(frag, part);\n // Should we define another load policy for parts?\n const loadPolicy = getLoaderConfigWithoutReties(\n config.fragLoadPolicy.default,\n );\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: MIN_CHUNK_SIZE,\n };\n // Assign part stats to the loader's stats reference\n part.stats = loader.stats;\n loader.load(loaderContext, loaderConfig, {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n this.updateStatsFromPart(frag, part);\n const partLoadedData: FragLoadedData = {\n frag,\n part,\n payload: response.data as ArrayBuffer,\n networkDetails,\n };\n onProgress(partLoadedData);\n resolve(partLoadedData);\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n part,\n response: {\n url: loaderContext.url,\n data: undefined,\n ...response,\n },\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats,\n }),\n );\n },\n onAbort: (stats, context, networkDetails) => {\n frag.stats.aborted = part.stats.aborted;\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n part,\n error: new Error('Aborted'),\n networkDetails,\n stats,\n }),\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n part,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats,\n }),\n );\n },\n });\n });\n }\n\n private updateStatsFromPart(frag: Fragment, part: Part) {\n const fragStats = frag.stats;\n const partStats = part.stats;\n const partTotal = partStats.total;\n fragStats.loaded += partStats.loaded;\n if (partTotal) {\n const estTotalParts = Math.round(frag.duration / part.duration);\n const estLoadedParts = Math.min(\n Math.round(fragStats.loaded / partTotal),\n estTotalParts,\n );\n const estRemainingParts = estTotalParts - estLoadedParts;\n const estRemainingBytes =\n estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);\n fragStats.total = fragStats.loaded + estRemainingBytes;\n } else {\n fragStats.total = Math.max(fragStats.loaded, fragStats.total);\n }\n const fragLoading = fragStats.loading;\n const partLoading = partStats.loading;\n if (fragLoading.start) {\n // add to fragment loader latency\n fragLoading.first += partLoading.first - partLoading.start;\n } else {\n fragLoading.start = partLoading.start;\n fragLoading.first = partLoading.first;\n }\n fragLoading.end = partLoading.end;\n }\n\n private resetLoader(frag: Fragment, loader: Loader<FragmentLoaderContext>) {\n frag.loader = null;\n if (this.loader === loader) {\n self.clearTimeout(this.partLoadTimeout);\n this.loader = null;\n }\n loader.destroy();\n }\n}\n\nfunction createLoaderContext(\n frag: Fragment,\n part: Part | null = null,\n): FragmentLoaderContext {\n const segment: BaseSegment = part || frag;\n const loaderContext: FragmentLoaderContext = {\n frag,\n part,\n responseType: 'arraybuffer',\n url: segment.url,\n headers: {},\n rangeStart: 0,\n rangeEnd: 0,\n };\n const start = segment.byteRangeStartOffset as number;\n const end = segment.byteRangeEndOffset as number;\n if (Number.isFinite(start) && Number.isFinite(end)) {\n let byteRangeStart = start;\n let byteRangeEnd = end;\n if (frag.sn === 'initSegment' && frag.decryptdata?.method === 'AES-128') {\n // MAP segment encrypted with method 'AES-128', when served with HTTP Range,\n // has the unencrypted size specified in the range.\n // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6\n const fragmentLen = end - start;\n if (fragmentLen % 16) {\n byteRangeEnd = end + (16 - (fragmentLen % 16));\n }\n if (start !== 0) {\n loaderContext.resetIV = true;\n byteRangeStart = start - 16;\n }\n }\n loaderContext.rangeStart = byteRangeStart;\n loaderContext.rangeEnd = byteRangeEnd;\n }\n return loaderContext;\n}\n\nfunction createGapLoadError(frag: Fragment, part?: Part): LoadError {\n const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);\n const errorData: FragLoadFailResult = {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_GAP,\n fatal: false,\n frag,\n error,\n networkDetails: null,\n };\n if (part) {\n errorData.part = part;\n }\n (part ? part : frag).stats.aborted = true;\n return new LoadError(errorData);\n}\n\nexport class LoadError extends Error {\n public readonly data: FragLoadFailResult;\n constructor(data: FragLoadFailResult) {\n super(data.error.message);\n this.data = data;\n }\n}\n\nexport interface FragLoadFailResult extends ErrorData {\n frag: Fragment;\n part?: Part;\n response?: {\n data: any;\n // error status code\n code: number;\n // error description\n text: string;\n url: string;\n };\n networkDetails: any;\n}\n\nexport type FragmentLoadProgressCallback = (\n result: FragLoadedData | PartsLoadedData,\n) => void;\n","export default class AESCrypto {\n private subtle: SubtleCrypto;\n private aesIV: Uint8Array;\n\n constructor(subtle: SubtleCrypto, iv: Uint8Array) {\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n decrypt(data: ArrayBuffer, key: CryptoKey) {\n return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);\n }\n}\n","export default class FastAESKey {\n private subtle: SubtleCrypto;\n private key: ArrayBuffer;\n\n constructor(subtle: SubtleCrypto, key: ArrayBuffer) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey() {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, [\n 'encrypt',\n 'decrypt',\n ]);\n }\n}\n","import { sliceUint8 } from '../utils/typed-array';\n\n// PKCS7\nexport function removePadding(array: Uint8Array): Uint8Array {\n const outputBytes = array.byteLength;\n const paddingBytes =\n outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return sliceUint8(array, 0, outputBytes - paddingBytes);\n }\n return array;\n}\n\nexport default class AESDecryptor {\n private rcon: Array<number> = [\n 0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,\n ];\n private subMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private invSubMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private sBox: Uint32Array = new Uint32Array(256);\n private invSBox: Uint32Array = new Uint32Array(256);\n private key: Uint32Array = new Uint32Array(0);\n\n private ksRows: number = 0;\n private keySize: number = 0;\n private keySchedule!: Uint32Array;\n private invKeySchedule!: Uint32Array;\n\n constructor() {\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_(arrayBuffer) {\n const view = new DataView(arrayBuffer);\n const newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n }\n\n initTable() {\n const sBox = this.sBox;\n const invSBox = this.invSBox;\n const subMix = this.subMix;\n const subMix0 = subMix[0];\n const subMix1 = subMix[1];\n const subMix2 = subMix[2];\n const subMix3 = subMix[3];\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n const x2 = d[x];\n const x4 = d[x2];\n const x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey(keyBuffer: ArrayBuffer) {\n // convert keyBuffer to Uint32Array\n const key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = key[offset] === this.key[offset];\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n const keySize = (this.keySize = key.length);\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n const ksRows = (this.ksRows = (keySize + 6 + 1) * 4);\n let ksRow;\n let invKsRow;\n\n const keySchedule = (this.keySchedule = new Uint32Array(ksRows));\n const invKeySchedule = (this.invKeySchedule = new Uint32Array(ksRows));\n const sbox = this.sBox;\n const rcon = this.rcon;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] =\n invSubMix0[sbox[t >>> 24]] ^\n invSubMix1[sbox[(t >>> 16) & 0xff]] ^\n invSubMix2[sbox[(t >>> 8) & 0xff]] ^\n invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap(word) {\n return (\n (word << 24) |\n ((word & 0xff00) << 8) |\n ((word & 0xff0000) >> 8) |\n (word >>> 24)\n );\n }\n\n decrypt(inputArrayBuffer: ArrayBuffer, offset: number, aesIV: ArrayBuffer) {\n const nRounds = this.keySize + 6;\n const invKeySchedule = this.invKeySchedule;\n const invSBOX = this.invSBox;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n const inputInt32 = new Int32Array(inputArrayBuffer);\n const outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n let ksRow, i;\n const swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 =\n invSubMix0[s0 >>> 24] ^\n invSubMix1[(s1 >> 16) & 0xff] ^\n invSubMix2[(s2 >> 8) & 0xff] ^\n invSubMix3[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n invSubMix0[s1 >>> 24] ^\n invSubMix1[(s2 >> 16) & 0xff] ^\n invSubMix2[(s3 >> 8) & 0xff] ^\n invSubMix3[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n invSubMix0[s2 >>> 24] ^\n invSubMix1[(s3 >> 16) & 0xff] ^\n invSubMix2[(s0 >> 8) & 0xff] ^\n invSubMix3[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n invSubMix0[s3 >>> 24] ^\n invSubMix1[(s0 >> 16) & 0xff] ^\n invSubMix2[(s1 >> 8) & 0xff] ^\n invSubMix3[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 =\n (invSBOX[s0 >>> 24] << 24) ^\n (invSBOX[(s1 >> 16) & 0xff] << 16) ^\n (invSBOX[(s2 >> 8) & 0xff] << 8) ^\n invSBOX[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n (invSBOX[s1 >>> 24] << 24) ^\n (invSBOX[(s2 >> 16) & 0xff] << 16) ^\n (invSBOX[(s3 >> 8) & 0xff] << 8) ^\n invSBOX[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n (invSBOX[s2 >>> 24] << 24) ^\n (invSBOX[(s3 >> 16) & 0xff] << 16) ^\n (invSBOX[(s0 >> 8) & 0xff] << 8) ^\n invSBOX[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n (invSBOX[s3 >>> 24] << 24) ^\n (invSBOX[(s0 >> 16) & 0xff] << 16) ^\n (invSBOX[(s1 >> 8) & 0xff] << 8) ^\n invSBOX[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return outputInt32.buffer;\n }\n}\n","import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor, { removePadding } from './aes-decryptor';\nimport { logger } from '../utils/logger';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { sliceUint8 } from '../utils/typed-array';\nimport type { HlsConfig } from '../config';\n\nconst CHUNK_SIZE = 16; // 16 bytes, 128 bits\n\nexport default class Decrypter {\n private logEnabled: boolean = true;\n private removePKCS7Padding: boolean;\n private subtle: SubtleCrypto | null = null;\n private softwareDecrypter: AESDecryptor | null = null;\n private key: ArrayBuffer | null = null;\n private fastAesKey: FastAESKey | null = null;\n private remainderData: Uint8Array | null = null;\n private currentIV: ArrayBuffer | null = null;\n private currentResult: ArrayBuffer | null = null;\n private useSoftware: boolean;\n\n constructor(config: HlsConfig, { removePKCS7Padding = true } = {}) {\n this.useSoftware = config.enableSoftwareAES;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = self.crypto;\n if (browserCrypto) {\n this.subtle =\n browserCrypto.subtle ||\n ((browserCrypto as any).webkitSubtle as SubtleCrypto);\n }\n } catch (e) {\n /* no-op */\n }\n }\n\n this.useSoftware = !this.subtle;\n }\n\n destroy() {\n this.subtle = null;\n this.softwareDecrypter = null;\n this.key = null;\n this.fastAesKey = null;\n this.remainderData = null;\n this.currentIV = null;\n this.currentResult = null;\n }\n\n public isSync() {\n return this.useSoftware;\n }\n\n public flush(): Uint8Array | null {\n const { currentResult, remainderData } = this;\n if (!currentResult || remainderData) {\n this.reset();\n return null;\n }\n const data = new Uint8Array(currentResult);\n this.reset();\n if (this.removePKCS7Padding) {\n return removePadding(data);\n }\n return data;\n }\n\n public reset() {\n this.currentResult = null;\n this.currentIV = null;\n this.remainderData = null;\n if (this.softwareDecrypter) {\n this.softwareDecrypter = null;\n }\n }\n\n public decrypt(\n data: Uint8Array | ArrayBuffer,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): Promise<ArrayBuffer> {\n if (this.useSoftware) {\n return new Promise((resolve, reject) => {\n this.softwareDecrypt(new Uint8Array(data), key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n resolve(decryptResult.buffer);\n } else {\n reject(new Error('[softwareDecrypt] Failed to decrypt data'));\n }\n });\n }\n return this.webCryptoDecrypt(new Uint8Array(data), key, iv);\n }\n\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n public softwareDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): ArrayBuffer | null {\n const { currentIV, currentResult, remainderData } = this;\n this.logOnce('JS AES decrypt');\n // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call\n // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached\n // the end on flush(), but by that time we have already received all bytes for the segment.\n // Progressive decryption does not work with WebCrypto\n\n if (remainderData) {\n data = appendUint8Array(remainderData, data);\n this.remainderData = null;\n }\n\n // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)\n const currentChunk = this.getValidChunk(data);\n if (!currentChunk.length) {\n return null;\n }\n\n if (currentIV) {\n iv = currentIV;\n }\n\n let softwareDecrypter = this.softwareDecrypter;\n if (!softwareDecrypter) {\n softwareDecrypter = this.softwareDecrypter = new AESDecryptor();\n }\n softwareDecrypter.expandKey(key);\n\n const result = currentResult;\n\n this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);\n this.currentIV = sliceUint8(currentChunk, -16).buffer;\n\n if (!result) {\n return null;\n }\n return result;\n }\n\n public webCryptoDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): Promise<ArrayBuffer> {\n if (this.key !== key || !this.fastAesKey) {\n if (!this.subtle) {\n return Promise.resolve(this.onWebCryptoError(data, key, iv));\n }\n this.key = key;\n this.fastAesKey = new FastAESKey(this.subtle, key);\n }\n return this.fastAesKey\n .expandKey()\n .then((aesKey) => {\n // decrypt using web crypto\n if (!this.subtle) {\n return Promise.reject(new Error('web crypto not initialized'));\n }\n this.logOnce('WebCrypto AES decrypt');\n const crypto = new AESCrypto(this.subtle, new Uint8Array(iv));\n return crypto.decrypt(data.buffer, aesKey);\n })\n .catch((err) => {\n logger.warn(\n `[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`,\n );\n\n return this.onWebCryptoError(data, key, iv);\n });\n }\n\n private onWebCryptoError(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer,\n ): ArrayBuffer | never {\n this.useSoftware = true;\n this.logEnabled = true;\n this.softwareDecrypt(data, key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n return decryptResult.buffer;\n }\n throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');\n }\n\n private getValidChunk(data: Uint8Array): Uint8Array {\n let currentChunk = data;\n const splitPoint = data.length - (data.length % CHUNK_SIZE);\n if (splitPoint !== data.length) {\n currentChunk = sliceUint8(data, 0, splitPoint);\n this.remainderData = sliceUint8(data, splitPoint);\n }\n return currentChunk;\n }\n\n private logOnce(msg: string) {\n if (!this.logEnabled) {\n return;\n }\n logger.log(`[decrypter]: ${msg}`);\n this.logEnabled = false;\n }\n}\n","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r: TimeRanges) {\n let log = '';\n const len = r.length;\n for (let i = 0; i < len; i++) {\n log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;\n }\n\n return log;\n },\n};\n\nexport default TimeRanges;\n","import TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport { Bufferable, BufferHelper, BufferInfo } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\nimport { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { alignStream } from '../utils/discontinuities';\nimport {\n findFragmentByPDT,\n findFragmentByPTS,\n findFragWithCC,\n} from './fragment-finders';\nimport {\n findPart,\n getFragmentWithSN,\n getPartWith,\n updateFragPTSDTS,\n} from '../utils/level-helper';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { Fragment, Part } from '../loader/fragment';\nimport FragmentLoader, {\n FragmentLoadProgressCallback,\n LoadError,\n} from '../loader/fragment-loader';\nimport KeyLoader from '../loader/key-loader';\nimport { LevelDetails } from '../loader/level-details';\nimport Decrypter from '../crypt/decrypter';\nimport TimeRanges from '../utils/time-ranges';\nimport { PlaylistLevelType } from '../types/loader';\nimport { getRetryDelay } from '../utils/error-helper';\nimport { NetworkErrorAction } from './error-controller';\nimport type {\n BufferAppendingData,\n ErrorData,\n FragLoadedData,\n PartsLoadedData,\n KeyLoadedData,\n MediaAttachedData,\n BufferFlushingData,\n ManifestLoadedData,\n} from '../types/events';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type { Level } from '../types/level';\nimport type { RemuxedTrack } from '../types/remuxer';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { SourceBufferName } from '../types/buffer';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\ntype ResolveFragLoaded = (FragLoadedEndData) => void;\ntype RejectFragLoaded = (LoadError) => void;\n\nexport const State = {\n STOPPED: 'STOPPED',\n IDLE: 'IDLE',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK: 'WAITING_TRACK',\n PARSING: 'PARSING',\n PARSED: 'PARSED',\n ENDED: 'ENDED',\n ERROR: 'ERROR',\n WAITING_INIT_PTS: 'WAITING_INIT_PTS',\n WAITING_LEVEL: 'WAITING_LEVEL',\n};\n\nexport default class BaseStreamController\n extends TaskLoop\n implements NetworkComponentAPI\n{\n protected hls: Hls;\n\n protected fragPrevious: Fragment | null = null;\n protected fragCurrent: Fragment | null = null;\n protected fragmentTracker: FragmentTracker;\n protected transmuxer: TransmuxerInterface | null = null;\n protected _state: string = State.STOPPED;\n protected playlistType: PlaylistLevelType;\n protected media: HTMLMediaElement | null = null;\n protected mediaBuffer: Bufferable | null = null;\n protected config: HlsConfig;\n protected bitrateTest: boolean = false;\n protected lastCurrentTime: number = 0;\n protected nextLoadPosition: number = 0;\n protected startPosition: number = 0;\n protected startTimeOffset: number | null = null;\n protected loadedmetadata: boolean = false;\n protected retryDate: number = 0;\n protected levels: Array<Level> | null = null;\n protected fragmentLoader: FragmentLoader;\n protected keyLoader: KeyLoader;\n protected levelLastLoaded: Level | null = null;\n protected startFragRequested: boolean = false;\n protected decrypter: Decrypter;\n protected initPTS: RationalTimestamp[] = [];\n protected onvseeking: EventListener | null = null;\n protected onvended: EventListener | null = null;\n\n private readonly logPrefix: string = '';\n protected log: (msg: any) => void;\n protected warn: (msg: any) => void;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader,\n logPrefix: string,\n playlistType: PlaylistLevelType,\n ) {\n super();\n this.playlistType = playlistType;\n this.logPrefix = logPrefix;\n this.log = logger.log.bind(logger, `${logPrefix}:`);\n this.warn = logger.warn.bind(logger, `${logPrefix}:`);\n this.hls = hls;\n this.fragmentLoader = new FragmentLoader(hls.config);\n this.keyLoader = keyLoader;\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.decrypter = new Decrypter(hls.config);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n\n protected doTick() {\n this.onTickEnd();\n }\n\n protected onTickEnd() {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public startLoad(startPosition: number): void {}\n\n public stopLoad() {\n this.fragmentLoader.abort();\n this.keyLoader.abort(this.playlistType);\n const frag = this.fragCurrent;\n if (frag?.loader) {\n frag.abortRequests();\n this.fragmentTracker.removeFragment(frag);\n }\n this.resetTransmuxer();\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.clearInterval();\n this.clearNextTick();\n this.state = State.STOPPED;\n }\n\n protected _streamEnded(\n bufferInfo: BufferInfo,\n levelDetails: LevelDetails,\n ): boolean {\n // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,\n // of nothing loading/loaded return false\n if (\n levelDetails.live ||\n bufferInfo.nextStart ||\n !bufferInfo.end ||\n !this.media\n ) {\n return false;\n }\n const partList = levelDetails.partList;\n // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,\n // check instead if the last part is buffered.\n if (partList?.length) {\n const lastPart = partList[partList.length - 1];\n\n // Checking the midpoint of the part for potential margin of error and related issues.\n // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)\n // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream\n // part mismatches for independent audio and video playlists/segments.\n const lastPartBuffered = BufferHelper.isBuffered(\n this.media,\n lastPart.start + lastPart.duration / 2,\n );\n return lastPartBuffered;\n }\n\n const playlistType =\n levelDetails.fragments[levelDetails.fragments.length - 1].type;\n return this.fragmentTracker.isEndListAppended(playlistType);\n }\n\n protected getLevelDetails(): LevelDetails | undefined {\n if (this.levels && this.levelLastLoaded !== null) {\n return this.levelLastLoaded?.details;\n }\n }\n\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ) {\n const media = (this.media = this.mediaBuffer = data.media);\n this.onvseeking = this.onMediaSeeking.bind(this) as EventListener;\n this.onvended = this.onMediaEnded.bind(this) as EventListener;\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n const config = this.config;\n if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {\n this.startLoad(config.startPosition);\n }\n }\n\n protected onMediaDetaching() {\n const media = this.media;\n if (media?.ended) {\n this.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // remove video listeners\n if (media && this.onvseeking && this.onvended) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvended = null;\n }\n if (this.keyLoader) {\n this.keyLoader.detach();\n }\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.fragmentTracker.removeAllFragments();\n this.stopLoad();\n }\n\n protected onMediaSeeking() {\n const { config, fragCurrent, media, mediaBuffer, state } = this;\n const currentTime: number = media ? media.currentTime : 0;\n const bufferInfo = BufferHelper.bufferInfo(\n mediaBuffer ? mediaBuffer : media,\n currentTime,\n config.maxBufferHole,\n );\n\n this.log(\n `media seeking to ${\n Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime\n }, state: ${state}`,\n );\n\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n } else if (fragCurrent) {\n // Seeking while frag load is in progress\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset =\n fragCurrent.start + fragCurrent.duration + tolerance;\n // if seeking out of buffered range or into new one\n if (\n !bufferInfo.len ||\n fragEndOffset < bufferInfo.start ||\n fragStartOffset > bufferInfo.end\n ) {\n const pastFragment = currentTime > fragEndOffset;\n // if the seek position is outside the current fragment range\n if (currentTime < fragStartOffset || pastFragment) {\n if (pastFragment && fragCurrent.loader) {\n this.log(\n 'seeking outside of buffer while fragment load in progress, cancel fragment load',\n );\n fragCurrent.abortRequests();\n this.resetLoadingState();\n }\n this.fragPrevious = null;\n }\n }\n }\n\n if (media) {\n // Remove gap fragments\n this.fragmentTracker.removeFragmentsInRange(\n currentTime,\n Infinity,\n this.playlistType,\n true,\n );\n\n this.lastCurrentTime = currentTime;\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.loadedmetadata && !bufferInfo.len) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // Async tick to speed up processing\n this.tickImmediate();\n }\n\n protected onMediaEnded() {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n protected onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ): void {\n this.startTimeOffset = data.startTimeOffset;\n this.initPTS = [];\n }\n\n protected onHandlerDestroying() {\n this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n this.stopLoad();\n super.onHandlerDestroying();\n // @ts-ignore\n this.hls = null;\n }\n\n protected onHandlerDestroyed() {\n this.state = State.STOPPED;\n if (this.fragmentLoader) {\n this.fragmentLoader.destroy();\n }\n if (this.keyLoader) {\n this.keyLoader.destroy();\n }\n if (this.decrypter) {\n this.decrypter.destroy();\n }\n\n this.hls =\n this.log =\n this.warn =\n this.decrypter =\n this.keyLoader =\n this.fragmentLoader =\n this.fragmentTracker =\n null as any;\n super.onHandlerDestroyed();\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number,\n ) {\n this._loadFragForPlayback(frag, level, targetBufferTime);\n }\n\n private _loadFragForPlayback(\n frag: Fragment,\n level: Level,\n targetBufferTime: number,\n ) {\n const progressCallback: FragmentLoadProgressCallback = (\n data: FragLoadedData,\n ) => {\n if (this.fragContextChanged(frag)) {\n this.warn(\n `Fragment ${frag.sn}${\n data.part ? ' p: ' + data.part.index : ''\n } of level ${frag.level} was dropped during download.`,\n );\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n frag.stats.chunkCount++;\n this._handleFragmentLoadProgress(data);\n };\n\n this._doFragLoad(frag, level, targetBufferTime, progressCallback)\n .then((data) => {\n if (!data) {\n // if we're here we probably needed to backtrack or are waiting for more parts\n return;\n }\n const state = this.state;\n if (this.fragContextChanged(frag)) {\n if (\n state === State.FRAG_LOADING ||\n (!this.fragCurrent && state === State.PARSING)\n ) {\n this.fragmentTracker.removeFragment(frag);\n this.state = State.IDLE;\n }\n return;\n }\n\n if ('payload' in data) {\n this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);\n this.hls.trigger(Events.FRAG_LOADED, data);\n }\n\n // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback\n this._handleFragmentLoadComplete(data);\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(`Frag error: ${reason?.message || reason}`);\n this.resetFragmentLoading(frag);\n });\n }\n\n protected clearTrackerIfNeeded(frag: Fragment) {\n const { fragmentTracker } = this;\n const fragState = fragmentTracker.getState(frag);\n if (fragState === FragmentState.APPENDING) {\n // Lower the max buffer length and try again\n const playlistType = frag.type as PlaylistLevelType;\n const bufferedInfo = this.getFwdBufferInfo(\n this.mediaBuffer,\n playlistType,\n );\n const minForwardBufferLength = Math.max(\n frag.duration,\n bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength,\n );\n // If backtracking, always remove from the tracker without reducing max buffer length\n const backtrackFragment = (this as any).backtrackFragment as\n | Fragment\n | undefined;\n const backtracked = backtrackFragment\n ? (frag.sn as number) - (backtrackFragment.sn as number)\n : 0;\n if (\n backtracked === 1 ||\n this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)\n ) {\n fragmentTracker.removeFragment(frag);\n }\n } else if (this.mediaBuffer?.buffered.length === 0) {\n // Stop gap for bad tracker / buffer flush behavior\n fragmentTracker.removeAllFragments();\n } else if (fragmentTracker.hasParts(frag.type)) {\n // In low latency mode, remove fragments for which only some parts were buffered\n fragmentTracker.detectPartialFragments({\n frag,\n part: null,\n stats: frag.stats,\n id: frag.type,\n });\n if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {\n fragmentTracker.removeFragment(frag);\n }\n }\n }\n\n protected checkLiveUpdate(details: LevelDetails) {\n if (details.updated && !details.live) {\n // Live stream ended, update fragment tracker\n const lastFragment = details.fragments[details.fragments.length - 1];\n this.fragmentTracker.detectPartialFragments({\n frag: lastFragment,\n part: null,\n stats: lastFragment.stats,\n id: lastFragment.type,\n });\n }\n if (!details.fragments[0]) {\n details.deltaUpdateFailed = true;\n }\n }\n\n protected flushMainBuffer(\n startOffset: number,\n endOffset: number,\n type: SourceBufferName | null = null,\n ) {\n if (!(startOffset - endOffset)) {\n return;\n }\n // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,\n // passing a null type flushes both buffers\n const flushScope: BufferFlushingData = { startOffset, endOffset, type };\n this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);\n }\n\n protected _loadInitSegment(frag: Fragment, level: Level) {\n this._doFragLoad(frag, level)\n .then((data) => {\n if (!data || this.fragContextChanged(frag) || !this.levels) {\n throw new Error('init load aborted');\n }\n\n return data;\n })\n .then((data: FragLoadedData) => {\n const { hls } = this;\n const { payload } = data;\n const decryptData = frag.decryptdata;\n\n // check to see if the payload needs to be decrypted\n if (\n payload &&\n payload.byteLength > 0 &&\n decryptData?.key &&\n decryptData.iv &&\n decryptData.method === 'AES-128'\n ) {\n const startTime = self.performance.now();\n // decrypt init segment data\n return this.decrypter\n .decrypt(\n new Uint8Array(payload),\n decryptData.key.buffer,\n decryptData.iv.buffer,\n )\n .catch((err) => {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_DECRYPT_ERROR,\n fatal: false,\n error: err,\n reason: err.message,\n frag,\n });\n throw err;\n })\n .then((decryptedData) => {\n const endTime = self.performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime,\n },\n });\n data.payload = decryptedData;\n return this.completeInitSegmentLoad(data);\n });\n }\n return this.completeInitSegmentLoad(data);\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(reason);\n this.resetFragmentLoading(frag);\n });\n }\n\n private completeInitSegmentLoad(data: FragLoadedData) {\n const { levels } = this;\n if (!levels) {\n throw new Error('init load aborted, missing levels');\n }\n const stats = data.frag.stats;\n this.state = State.IDLE;\n data.frag.data = new Uint8Array(data.payload);\n stats.parsing.start = stats.buffering.start = self.performance.now();\n stats.parsing.end = stats.buffering.end = self.performance.now();\n this.tick();\n }\n\n protected fragContextChanged(frag: Fragment | null) {\n const { fragCurrent } = this;\n return (\n !frag ||\n !fragCurrent ||\n frag.sn !== fragCurrent.sn ||\n frag.level !== fragCurrent.level\n );\n }\n\n protected fragBufferedComplete(frag: Fragment, part: Part | null) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n this.log(\n `Buffered ${frag.type} sn: ${frag.sn}${\n part ? ' part: ' + part.index : ''\n } of ${\n this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track'\n } ${frag.level} (frag:[${(frag.startPTS ?? NaN).toFixed(3)}-${(\n frag.endPTS ?? NaN\n ).toFixed(3)}] > buffer:${\n media\n ? TimeRanges.toString(BufferHelper.getBuffered(media))\n : '(detached)'\n })`,\n );\n if (frag.sn !== 'initSegment') {\n if (frag.type !== PlaylistLevelType.SUBTITLE) {\n const el = frag.elementaryStreams;\n if (!Object.keys(el).some((type) => !!el[type])) {\n // empty segment\n this.state = State.IDLE;\n return;\n }\n }\n const level = this.levels?.[frag.level];\n if (level?.fragmentError) {\n this.log(\n `Resetting level fragment error count of ${level.fragmentError} on frag buffered`,\n );\n level.fragmentError = 0;\n }\n }\n this.state = State.IDLE;\n if (!media) {\n return;\n }\n if (\n !this.loadedmetadata &&\n frag.type == PlaylistLevelType.MAIN &&\n media.buffered.length &&\n this.fragCurrent?.sn === this.fragPrevious?.sn\n ) {\n this.loadedmetadata = true;\n this.seekToStartPos();\n }\n this.tick();\n }\n\n protected seekToStartPos() {}\n\n protected _handleFragmentLoadComplete(fragLoadedEndData: PartsLoadedData) {\n const { transmuxer } = this;\n if (!transmuxer) {\n return;\n }\n const { frag, part, partsLoaded } = fragLoadedEndData;\n // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data\n const complete =\n !partsLoaded ||\n partsLoaded.length === 0 ||\n partsLoaded.some((fragLoaded) => !fragLoaded);\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount + 1,\n 0,\n part ? part.index : -1,\n !complete,\n );\n transmuxer.flush(chunkMeta);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected _handleFragmentLoadProgress(\n frag: PartsLoadedData | FragLoadedData,\n ) {}\n\n protected _doFragLoad(\n frag: Fragment,\n level: Level,\n targetBufferTime: number | null = null,\n progressCallback?: FragmentLoadProgressCallback,\n ): Promise<PartsLoadedData | FragLoadedData | null> {\n const details = level?.details;\n if (!this.levels || !details) {\n throw new Error(\n `frag load aborted, missing level${details ? '' : ' detail'}s`,\n );\n }\n\n let keyLoadingPromise: Promise<KeyLoadedData | void> | null = null;\n if (frag.encrypted && !frag.decryptdata?.key) {\n this.log(\n `Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${\n this.logPrefix === '[stream-controller]' ? 'level' : 'track'\n } ${frag.level}`,\n );\n this.state = State.KEY_LOADING;\n this.fragCurrent = frag;\n keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {\n if (!this.fragContextChanged(keyLoadedData.frag)) {\n this.hls.trigger(Events.KEY_LOADED, keyLoadedData);\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n }\n return keyLoadedData;\n }\n });\n this.hls.trigger(Events.KEY_LOADING, { frag });\n if (this.fragCurrent === null) {\n keyLoadingPromise = Promise.reject(\n new Error(`frag load aborted, context changed in KEY_LOADING`),\n );\n }\n } else if (!frag.encrypted && details.encryptedFragments.length) {\n this.keyLoader.loadClear(frag, details.encryptedFragments);\n }\n\n targetBufferTime = Math.max(frag.start, targetBufferTime || 0);\n if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {\n const partList = details.partList;\n if (partList && progressCallback) {\n if (targetBufferTime > frag.end && details.fragmentHint) {\n frag = details.fragmentHint;\n }\n const partIndex = this.getNextPart(partList, frag, targetBufferTime);\n if (partIndex > -1) {\n const part = partList[partIndex];\n this.log(\n `Loading part sn: ${frag.sn} p: ${part.index} cc: ${\n frag.cc\n } of playlist [${details.startSN}-${\n details.endSN\n }] parts [0-${partIndex}-${partList.length - 1}] ${\n this.logPrefix === '[stream-controller]' ? 'level' : 'track'\n }: ${frag.level}, target: ${parseFloat(\n targetBufferTime.toFixed(3),\n )}`,\n );\n this.nextLoadPosition = part.start + part.duration;\n this.state = State.FRAG_LOADING;\n let result: Promise<PartsLoadedData | FragLoadedData | null>;\n if (keyLoadingPromise) {\n result = keyLoadingPromise\n .then((keyLoadedData) => {\n if (\n !keyLoadedData ||\n this.fragContextChanged(keyLoadedData.frag)\n ) {\n return null;\n }\n return this.doFragPartsLoad(\n frag,\n part,\n level,\n progressCallback,\n );\n })\n .catch((error) => this.handleFragLoadError(error));\n } else {\n result = this.doFragPartsLoad(\n frag,\n part,\n level,\n progressCallback,\n ).catch((error: LoadError) => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, {\n frag,\n part,\n targetBufferTime,\n });\n if (this.fragCurrent === null) {\n return Promise.reject(\n new Error(\n `frag load aborted, context changed in FRAG_LOADING parts`,\n ),\n );\n }\n return result;\n } else if (\n !frag.url ||\n this.loadedEndOfParts(partList, targetBufferTime)\n ) {\n // Fragment hint has no parts\n return Promise.resolve(null);\n }\n }\n }\n\n this.log(\n `Loading fragment ${frag.sn} cc: ${frag.cc} ${\n details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : ''\n }${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${\n frag.level\n }, target: ${parseFloat(targetBufferTime.toFixed(3))}`,\n );\n // Don't update nextLoadPosition for fragments which are not buffered\n if (Number.isFinite(frag.sn as number) && !this.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n this.state = State.FRAG_LOADING;\n\n // Load key before streaming fragment data\n const dataOnProgress = this.config.progressive;\n let result: Promise<PartsLoadedData | FragLoadedData | null>;\n if (dataOnProgress && keyLoadingPromise) {\n result = keyLoadingPromise\n .then((keyLoadedData) => {\n if (!keyLoadedData || this.fragContextChanged(keyLoadedData?.frag)) {\n return null;\n }\n return this.fragmentLoader.load(frag, progressCallback);\n })\n .catch((error) => this.handleFragLoadError(error));\n } else {\n // load unencrypted fragment data with progress event,\n // or handle fragment result after key and fragment are finished loading\n result = Promise.all([\n this.fragmentLoader.load(\n frag,\n dataOnProgress ? progressCallback : undefined,\n ),\n keyLoadingPromise,\n ])\n .then(([fragLoadedData]) => {\n if (!dataOnProgress && fragLoadedData && progressCallback) {\n progressCallback(fragLoadedData);\n }\n return fragLoadedData;\n })\n .catch((error) => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, { frag, targetBufferTime });\n if (this.fragCurrent === null) {\n return Promise.reject(\n new Error(`frag load aborted, context changed in FRAG_LOADING`),\n );\n }\n return result;\n }\n\n private doFragPartsLoad(\n frag: Fragment,\n fromPart: Part,\n level: Level,\n progressCallback: FragmentLoadProgressCallback,\n ): Promise<PartsLoadedData | null> {\n return new Promise(\n (resolve: ResolveFragLoaded, reject: RejectFragLoaded) => {\n const partsLoaded: FragLoadedData[] = [];\n const initialPartList = level.details?.partList;\n const loadPart = (part: Part) => {\n this.fragmentLoader\n .loadPart(frag, part, progressCallback)\n .then((partLoadedData: FragLoadedData) => {\n partsLoaded[part.index] = partLoadedData;\n const loadedPart = partLoadedData.part as Part;\n this.hls.trigger(Events.FRAG_LOADED, partLoadedData);\n const nextPart =\n getPartWith(level, frag.sn as number, part.index + 1) ||\n findPart(initialPartList, frag.sn as number, part.index + 1);\n if (nextPart) {\n loadPart(nextPart);\n } else {\n return resolve({\n frag,\n part: loadedPart,\n partsLoaded,\n });\n }\n })\n .catch(reject);\n };\n loadPart(fromPart);\n },\n );\n }\n\n private handleFragLoadError(error: LoadError | Error) {\n if ('data' in error) {\n const data = error.data;\n if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {\n this.handleFragLoadAborted(data.frag, data.part);\n } else {\n this.hls.trigger(Events.ERROR, data as ErrorData);\n }\n } else {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n err: error,\n error,\n fatal: true,\n });\n }\n return null;\n }\n\n protected _handleTransmuxerFlush(chunkMeta: ChunkMetadata) {\n const context = this.getCurrentContext(chunkMeta);\n if (!context || this.state !== State.PARSING) {\n if (\n !this.fragCurrent &&\n this.state !== State.STOPPED &&\n this.state !== State.ERROR\n ) {\n this.state = State.IDLE;\n }\n return;\n }\n const { frag, part, level } = context;\n const now = self.performance.now();\n frag.stats.parsing.end = now;\n if (part) {\n part.stats.parsing.end = now;\n }\n this.updateLevelTiming(frag, part, level, chunkMeta.partial);\n }\n\n protected getCurrentContext(\n chunkMeta: ChunkMetadata,\n ): { frag: Fragment; part: Part | null; level: Level } | null {\n const { levels, fragCurrent } = this;\n const { level: levelIndex, sn, part: partIndex } = chunkMeta;\n if (!levels?.[levelIndex]) {\n this.warn(\n `Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`,\n );\n return null;\n }\n const level = levels[levelIndex];\n const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;\n const frag = part\n ? part.fragment\n : getFragmentWithSN(level, sn, fragCurrent);\n if (!frag) {\n return null;\n }\n if (fragCurrent && fragCurrent !== frag) {\n frag.stats = fragCurrent.stats;\n }\n return { frag, part, level };\n }\n\n protected bufferFragmentData(\n data: RemuxedTrack,\n frag: Fragment,\n part: Part | null,\n chunkMeta: ChunkMetadata,\n noBacktracking?: boolean,\n ) {\n if (!data || this.state !== State.PARSING) {\n return;\n }\n\n const { data1, data2 } = data;\n let buffer = data1;\n if (data1 && data2) {\n // Combine the moof + mdat so that we buffer with a single append\n buffer = appendUint8Array(data1, data2);\n }\n\n if (!buffer?.length) {\n return;\n }\n\n const segment: BufferAppendingData = {\n type: data.type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n data: buffer,\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n\n if (data.dropped && data.independent && !part) {\n if (noBacktracking) {\n return;\n }\n // Clear buffer so that we reload previous segments sequentially if required\n this.flushBufferGap(frag);\n }\n }\n\n protected flushBufferGap(frag: Fragment) {\n const media = this.media;\n if (!media) {\n return;\n }\n // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed\n if (!BufferHelper.isBuffered(media, media.currentTime)) {\n this.flushMainBuffer(0, frag.start);\n return;\n }\n // Remove back-buffer without interrupting playback to allow back tracking\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const fragDuration = frag.duration;\n const segmentFraction = Math.min(\n this.config.maxFragLookUpTolerance * 2,\n fragDuration * 0.25,\n );\n const start = Math.max(\n Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction),\n currentTime + segmentFraction,\n );\n if (frag.start - start > segmentFraction) {\n this.flushMainBuffer(start, frag.start);\n }\n }\n\n protected getFwdBufferInfo(\n bufferable: Bufferable | null,\n type: PlaylistLevelType,\n ): BufferInfo | null {\n const pos = this.getLoadPosition();\n if (!Number.isFinite(pos)) {\n return null;\n }\n return this.getFwdBufferInfoAtPos(bufferable, pos, type);\n }\n\n protected getFwdBufferInfoAtPos(\n bufferable: Bufferable | null,\n pos: number,\n type: PlaylistLevelType,\n ): BufferInfo | null {\n const {\n config: { maxBufferHole },\n } = this;\n const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);\n // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos\n if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {\n const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);\n if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {\n return BufferHelper.bufferInfo(\n bufferable,\n pos,\n Math.max(bufferInfo.nextStart, maxBufferHole),\n );\n }\n }\n return bufferInfo;\n }\n\n protected getMaxBufferLength(levelBitrate?: number): number {\n const { config } = this;\n let maxBufLen;\n if (levelBitrate) {\n maxBufLen = Math.max(\n (8 * config.maxBufferSize) / levelBitrate,\n config.maxBufferLength,\n );\n } else {\n maxBufLen = config.maxBufferLength;\n }\n return Math.min(maxBufLen, config.maxMaxBufferLength);\n }\n\n protected reduceMaxBufferLength(threshold: number, fragDuration: number) {\n const config = this.config;\n const minLength = Math.max(\n Math.min(threshold - fragDuration, config.maxBufferLength),\n fragDuration,\n );\n const reducedLength = Math.max(\n threshold - fragDuration * 3,\n config.maxMaxBufferLength / 2,\n minLength,\n );\n if (reducedLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength = reducedLength;\n this.warn(`Reduce max buffer length to ${reducedLength}s`);\n return true;\n }\n return false;\n }\n\n protected getAppendedFrag(\n position: number,\n playlistType: PlaylistLevelType = PlaylistLevelType.MAIN,\n ): Fragment | null {\n const fragOrPart = this.fragmentTracker.getAppendedFrag(\n position,\n PlaylistLevelType.MAIN,\n );\n if (fragOrPart && 'fragment' in fragOrPart) {\n return fragOrPart.fragment;\n }\n return fragOrPart;\n }\n\n protected getNextFragment(\n pos: number,\n levelDetails: LevelDetails,\n ): Fragment | null {\n const fragments = levelDetails.fragments;\n const fragLen = fragments.length;\n\n if (!fragLen) {\n return null;\n }\n\n // find fragment index, contiguous with end of buffer position\n const { config } = this;\n const start = fragments[0].start;\n let frag;\n\n if (levelDetails.live) {\n const initialLiveManifestSize = config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n this.warn(\n `Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`,\n );\n return null;\n }\n // The real fragment start times for a live stream are only known after the PTS range for that level is known.\n // In order to discover the range, we load the best matching fragment for that level and demux it.\n // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that\n // we get the fragment matching that start time\n if (\n (!levelDetails.PTSKnown &&\n !this.startFragRequested &&\n this.startPosition === -1) ||\n pos < start\n ) {\n frag = this.getInitialLiveFragment(levelDetails, fragments);\n this.startPosition = this.nextLoadPosition = frag\n ? this.hls.liveSyncPosition || frag.start\n : pos;\n }\n } else if (pos <= start) {\n // VoD playlist: if loadPosition before start of playlist, load first fragment\n frag = fragments[0];\n }\n\n // If we haven't run into any special cases already, just load the fragment most closely matching the requested position\n if (!frag) {\n const end = config.lowLatencyMode\n ? levelDetails.partEnd\n : levelDetails.fragmentEnd;\n frag = this.getFragmentAtPosition(pos, end, levelDetails);\n }\n\n return this.mapToInitFragWhenRequired(frag);\n }\n\n protected isLoopLoading(frag: Fragment, targetBufferTime: number): boolean {\n const trackerState = this.fragmentTracker.getState(frag);\n return (\n (trackerState === FragmentState.OK ||\n (trackerState === FragmentState.PARTIAL && !!frag.gap)) &&\n this.nextLoadPosition > targetBufferTime\n );\n }\n\n protected getNextFragmentLoopLoading(\n frag: Fragment,\n levelDetails: LevelDetails,\n bufferInfo: BufferInfo,\n playlistType: PlaylistLevelType,\n maxBufLen: number,\n ): Fragment | null {\n const gapStart = frag.gap;\n const nextFragment = this.getNextFragment(\n this.nextLoadPosition,\n levelDetails,\n );\n if (nextFragment === null) {\n return nextFragment;\n }\n frag = nextFragment;\n if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {\n // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length\n const nextbufferInfo = this.getFwdBufferInfoAtPos(\n this.mediaBuffer ? this.mediaBuffer : this.media,\n bufferInfo.nextStart,\n playlistType,\n );\n if (\n nextbufferInfo !== null &&\n bufferInfo.len + nextbufferInfo.len >= maxBufLen\n ) {\n // Returning here might result in not finding an audio and video candiate to skip to\n this.log(\n `buffer full after gaps in \"${playlistType}\" playlist starting at sn: ${frag.sn}`,\n );\n return null;\n }\n }\n return frag;\n }\n\n mapToInitFragWhenRequired(frag: Fragment | null): typeof frag {\n // If an initSegment is present, it must be buffered first\n if (frag?.initSegment && !frag?.initSegment.data && !this.bitrateTest) {\n return frag.initSegment;\n }\n\n return frag;\n }\n\n getNextPart(\n partList: Part[],\n frag: Fragment,\n targetBufferTime: number,\n ): number {\n let nextPart = -1;\n let contiguous = false;\n let independentAttrOmitted = true;\n for (let i = 0, len = partList.length; i < len; i++) {\n const part = partList[i];\n independentAttrOmitted = independentAttrOmitted && !part.independent;\n if (nextPart > -1 && targetBufferTime < part.start) {\n break;\n }\n const loaded = part.loaded;\n if (loaded) {\n nextPart = -1;\n } else if (\n (contiguous || part.independent || independentAttrOmitted) &&\n part.fragment === frag\n ) {\n nextPart = i;\n }\n contiguous = loaded;\n }\n return nextPart;\n }\n\n private loadedEndOfParts(\n partList: Part[],\n targetBufferTime: number,\n ): boolean {\n const lastPart = partList[partList.length - 1];\n return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;\n }\n\n /*\n This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the\n \"sliding\" of the playlist, which is its offset from the start of playback. After sliding we can compute the real\n start and end times for each fragment in the playlist (after which this method will not need to be called).\n */\n protected getInitialLiveFragment(\n levelDetails: LevelDetails,\n fragments: Array<Fragment>,\n ): Fragment | null {\n const fragPrevious = this.fragPrevious;\n let frag: Fragment | null = null;\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding\n this.log(\n `Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`,\n );\n frag = findFragmentByPDT(\n fragments,\n fragPrevious.endProgramDateTime,\n this.config.maxFragLookUpTolerance,\n );\n }\n if (!frag) {\n // SN does not need to be accurate between renditions, but depending on the packaging it may be so.\n const targetSN = (fragPrevious.sn as number) + 1;\n if (\n targetSN >= levelDetails.startSN &&\n targetSN <= levelDetails.endSN\n ) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n // Ensure that we're staying within the continuity range, since PTS resets upon a new range\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n this.log(\n `Live playlist, switching playlist, load frag with next SN: ${\n frag!.sn\n }`,\n );\n }\n }\n // It's important to stay within the continuity range if available; otherwise the fragments in the playlist\n // will have the wrong start times\n if (!frag) {\n frag = findFragWithCC(fragments, fragPrevious.cc);\n if (frag) {\n this.log(\n `Live playlist, switching playlist, load frag with same CC: ${frag.sn}`,\n );\n }\n }\n }\n } else {\n // Find a new start fragment when fragPrevious is null\n const liveStart = this.hls.liveSyncPosition;\n if (liveStart !== null) {\n frag = this.getFragmentAtPosition(\n liveStart,\n this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge,\n levelDetails,\n );\n }\n }\n\n return frag;\n }\n\n /*\n This method finds the best matching fragment given the provided position.\n */\n protected getFragmentAtPosition(\n bufferEnd: number,\n end: number,\n levelDetails: LevelDetails,\n ): Fragment | null {\n const { config } = this;\n let { fragPrevious } = this;\n let { fragments, endSN } = levelDetails;\n const { fragmentHint } = levelDetails;\n const { maxFragLookUpTolerance } = config;\n const partList = levelDetails.partList;\n\n const loadingParts = !!(\n config.lowLatencyMode &&\n partList?.length &&\n fragmentHint\n );\n if (loadingParts && fragmentHint && !this.bitrateTest) {\n // Include incomplete fragment with parts at end\n fragments = fragments.concat(fragmentHint);\n endSN = fragmentHint.sn as number;\n }\n\n let frag;\n if (bufferEnd < end) {\n const lookupTolerance =\n bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPTS(\n fragPrevious,\n fragments,\n bufferEnd,\n lookupTolerance,\n );\n } else {\n // reach end of playlist\n frag = fragments[fragments.length - 1];\n }\n\n if (frag) {\n const curSNIdx = frag.sn - levelDetails.startSN;\n // Move fragPrevious forward to support forcing the next fragment to load\n // when the buffer catches up to a previously buffered range.\n const fragState = this.fragmentTracker.getState(frag);\n if (\n fragState === FragmentState.OK ||\n (fragState === FragmentState.PARTIAL && frag.gap)\n ) {\n fragPrevious = frag;\n }\n if (\n fragPrevious &&\n frag.sn === fragPrevious.sn &&\n (!loadingParts || partList[0].fragment.sn > frag.sn)\n ) {\n // Force the next fragment to load if the previous one was already selected. This can occasionally happen with\n // non-uniform fragment durations\n const sameLevel = fragPrevious && frag.level === fragPrevious.level;\n if (sameLevel) {\n const nextFrag = fragments[curSNIdx + 1];\n if (\n frag.sn < endSN &&\n this.fragmentTracker.getState(nextFrag) !== FragmentState.OK\n ) {\n frag = nextFrag;\n } else {\n frag = null;\n }\n }\n }\n }\n return frag;\n }\n\n protected synchronizeToLiveEdge(levelDetails: LevelDetails) {\n const { config, media } = this;\n if (!media) {\n return;\n }\n const liveSyncPosition = this.hls.liveSyncPosition;\n const currentTime = media.currentTime;\n const start = levelDetails.fragments[0].start;\n const end = levelDetails.edge;\n const withinSlidingWindow =\n currentTime >= start - config.maxFragLookUpTolerance &&\n currentTime <= end;\n // Continue if we can seek forward to sync position or if current time is outside of sliding window\n if (\n liveSyncPosition !== null &&\n media.duration > liveSyncPosition &&\n (currentTime < liveSyncPosition || !withinSlidingWindow)\n ) {\n // Continue if buffer is starving or if current time is behind max latency\n const maxLatency =\n config.liveMaxLatencyDuration !== undefined\n ? config.liveMaxLatencyDuration\n : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n if (\n (!withinSlidingWindow && media.readyState < 4) ||\n currentTime < end - maxLatency\n ) {\n if (!this.loadedmetadata) {\n this.nextLoadPosition = liveSyncPosition;\n }\n // Only seek if ready and there is not a significant forward buffer available for playback\n if (media.readyState) {\n this.warn(\n `Playback: ${currentTime.toFixed(\n 3,\n )} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(\n 3,\n )}`,\n );\n media.currentTime = liveSyncPosition;\n }\n }\n }\n }\n\n protected alignPlaylists(\n details: LevelDetails,\n previousDetails: LevelDetails | undefined,\n switchDetails: LevelDetails | undefined,\n ): number {\n // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,\n // this could all go in level-helper mergeDetails()\n const length = details.fragments.length;\n if (!length) {\n this.warn(`No fragments in live playlist`);\n return 0;\n }\n const slidingStart = details.fragments[0].start;\n const firstLevelLoad = !previousDetails;\n const aligned = details.alignedSliding && Number.isFinite(slidingStart);\n if (firstLevelLoad || (!aligned && !slidingStart)) {\n const { fragPrevious } = this;\n alignStream(fragPrevious, switchDetails, details);\n const alignedSlidingStart = details.fragments[0].start;\n this.log(\n `Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${\n previousDetails ? previousDetails.startSN : 'na'\n }->${details.startSN} prev-sn: ${\n fragPrevious ? fragPrevious.sn : 'na'\n } fragments: ${length}`,\n );\n return alignedSlidingStart;\n }\n return slidingStart;\n }\n\n protected waitForCdnTuneIn(details: LevelDetails) {\n // Wait for Low-Latency CDN Tune-in to get an updated playlist\n const advancePartLimit = 3;\n return (\n details.live &&\n details.canBlockReload &&\n details.partTarget &&\n details.tuneInGoal >\n Math.max(details.partHoldBack, details.partTarget * advancePartLimit)\n );\n }\n\n protected setStartPosition(details: LevelDetails, sliding: number) {\n // compute start position if set to -1. use it straight away if value is defined\n let startPosition = this.startPosition;\n if (startPosition < sliding) {\n startPosition = -1;\n }\n if (startPosition === -1 || this.lastCurrentTime === -1) {\n // Use Playlist EXT-X-START:TIME-OFFSET when set\n // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match\n const offsetInMultivariantPlaylist = this.startTimeOffset !== null;\n const startTimeOffset = offsetInMultivariantPlaylist\n ? this.startTimeOffset\n : details.startTimeOffset;\n if (startTimeOffset !== null && Number.isFinite(startTimeOffset)) {\n startPosition = sliding + startTimeOffset;\n if (startTimeOffset < 0) {\n startPosition += details.totalduration;\n }\n startPosition = Math.min(\n Math.max(sliding, startPosition),\n sliding + details.totalduration,\n );\n this.log(\n `Start time offset ${startTimeOffset} found in ${\n offsetInMultivariantPlaylist ? 'multivariant' : 'media'\n } playlist, adjust startPosition to ${startPosition}`,\n );\n this.startPosition = startPosition;\n } else if (details.live) {\n // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has\n // not been specified via the config or an as an argument to startLoad (#3736).\n startPosition = this.hls.liveSyncPosition || sliding;\n } else {\n this.startPosition = startPosition = 0;\n }\n this.lastCurrentTime = startPosition;\n }\n this.nextLoadPosition = startPosition;\n }\n\n protected getLoadPosition(): number {\n const { media } = this;\n // if we have not yet loaded any fragment, start loading from start position\n let pos = 0;\n if (this.loadedmetadata && media) {\n pos = media.currentTime;\n } else if (this.nextLoadPosition) {\n pos = this.nextLoadPosition;\n }\n\n return pos;\n }\n\n private handleFragLoadAborted(frag: Fragment, part: Part | undefined) {\n if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {\n this.warn(\n `Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${\n frag.level\n } was aborted`,\n );\n this.resetFragmentLoading(frag);\n }\n }\n\n protected resetFragmentLoading(frag: Fragment) {\n if (\n !this.fragCurrent ||\n (!this.fragContextChanged(frag) &&\n this.state !== State.FRAG_LOADING_WAITING_RETRY)\n ) {\n this.state = State.IDLE;\n }\n }\n\n protected onFragmentOrKeyLoadError(\n filterType: PlaylistLevelType,\n data: ErrorData,\n ) {\n if (data.chunkMeta && !data.frag) {\n const context = this.getCurrentContext(data.chunkMeta);\n if (context) {\n data.frag = context.frag;\n }\n }\n const frag = data.frag;\n // Handle frag error related to caller's filterType\n if (!frag || frag.type !== filterType || !this.levels) {\n return;\n }\n if (this.fragContextChanged(frag)) {\n this.warn(\n `Frag load error must match current frag to retry ${frag.url} > ${this.fragCurrent?.url}`,\n );\n return;\n }\n const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;\n if (gapTagEncountered) {\n this.fragmentTracker.fragBuffered(frag, true);\n }\n // keep retrying until the limit will be reached\n const errorAction = data.errorAction;\n const { action, retryCount = 0, retryConfig } = errorAction || {};\n if (\n errorAction &&\n action === NetworkErrorAction.RetryRequest &&\n retryConfig\n ) {\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n const delay = getRetryDelay(retryConfig, retryCount);\n this.warn(\n `Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${\n data.details\n }, retrying loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } in ${delay}ms`,\n );\n errorAction.resolved = true;\n this.retryDate = self.performance.now() + delay;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else if (retryConfig && errorAction) {\n this.resetFragmentErrors(filterType);\n if (retryCount < retryConfig.maxNumRetry) {\n // Network retry is skipped when level switch is preferred\n if (\n !gapTagEncountered &&\n action !== NetworkErrorAction.RemoveAlternatePermanently\n ) {\n errorAction.resolved = true;\n }\n } else {\n logger.warn(\n `${data.details} reached or exceeded max retry (${retryCount})`,\n );\n return;\n }\n } else if (\n errorAction?.action === NetworkErrorAction.SendAlternateToPenaltyBox\n ) {\n this.state = State.WAITING_LEVEL;\n } else {\n this.state = State.ERROR;\n }\n // Perform next async tick sooner to speed up error action resolution\n this.tickImmediate();\n }\n\n protected reduceLengthAndFlushBuffer(data: ErrorData): boolean {\n // if in appending state\n if (this.state === State.PARSING || this.state === State.PARSED) {\n const frag = data.frag;\n const playlistType = data.parent as PlaylistLevelType;\n const bufferedInfo = this.getFwdBufferInfo(\n this.mediaBuffer,\n playlistType,\n );\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n // reduce max buf len if current position is buffered\n const buffered = bufferedInfo && bufferedInfo.len > 0.5;\n if (buffered) {\n this.reduceMaxBufferLength(bufferedInfo.len, frag?.duration || 10);\n }\n const flushBuffer = !buffered;\n if (flushBuffer) {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n this.warn(\n `Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`,\n );\n }\n if (frag) {\n this.fragmentTracker.removeFragment(frag);\n this.nextLoadPosition = frag.start;\n }\n this.resetLoadingState();\n return flushBuffer;\n }\n return false;\n }\n\n protected resetFragmentErrors(filterType: PlaylistLevelType) {\n if (filterType === PlaylistLevelType.AUDIO) {\n // Reset current fragment since audio track audio is essential and may not have a fail-over track\n this.fragCurrent = null;\n }\n // Fragment errors that result in a level switch or redundant fail-over\n // should reset the stream controller state to idle\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n }\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n\n protected afterBufferFlushed(\n media: Bufferable,\n bufferType: SourceBufferName,\n playlistType: PlaylistLevelType,\n ) {\n if (!media) {\n return;\n }\n // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media\n // (so that we will check against video.buffered ranges in case of alt audio track)\n const bufferedTimeRanges = BufferHelper.getBuffered(media);\n this.fragmentTracker.detectEvictedFragments(\n bufferType,\n bufferedTimeRanges,\n playlistType,\n );\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n }\n }\n\n protected resetLoadingState() {\n this.log('Reset loading state');\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.state = State.IDLE;\n }\n\n protected resetStartWhenNotLoaded(level: Level | null): void {\n // if loadedmetadata is not set, it means that first frag request failed\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n const details = level ? level.details : null;\n if (details?.live) {\n // Update the start position and return to IDLE to recover live start\n this.startPosition = -1;\n this.setStartPosition(details, 0);\n this.resetLoadingState();\n } else {\n this.nextLoadPosition = this.startPosition;\n }\n }\n }\n\n protected resetWhenMissingContext(chunkMeta: ChunkMetadata) {\n this.warn(\n `The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`,\n );\n this.removeUnbufferedFrags();\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n this.resetLoadingState();\n }\n\n protected removeUnbufferedFrags(start: number = 0) {\n this.fragmentTracker.removeFragmentsInRange(\n start,\n Infinity,\n this.playlistType,\n false,\n true,\n );\n }\n\n private updateLevelTiming(\n frag: Fragment,\n part: Part | null,\n level: Level,\n partial: boolean,\n ) {\n const details = level.details as LevelDetails;\n if (!details) {\n this.warn('level.details undefined');\n return;\n }\n const parsed = Object.keys(frag.elementaryStreams).reduce(\n (result, type) => {\n const info = frag.elementaryStreams[type];\n if (info) {\n const parsedDuration = info.endPTS - info.startPTS;\n if (parsedDuration <= 0) {\n // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.\n // The new transmuxer will be configured with a time offset matching the next fragment start,\n // preventing the timeline from shifting.\n this.warn(\n `Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`,\n );\n return result || false;\n }\n const drift = partial\n ? 0\n : updateFragPTSDTS(\n details,\n frag,\n info.startPTS,\n info.endPTS,\n info.startDTS,\n info.endDTS,\n );\n this.hls.trigger(Events.LEVEL_PTS_UPDATED, {\n details,\n level,\n drift,\n type,\n frag,\n start: info.startPTS,\n end: info.endPTS,\n });\n return true;\n }\n return result;\n },\n false,\n );\n if (!parsed && this.transmuxer?.error === null) {\n const error = new Error(\n `Found no media in fragment ${frag.sn} of level ${frag.level} resetting transmuxer to fallback to playlist timing`,\n );\n if (level.fragmentError === 0) {\n // Mark and track the odd empty segment as a gap to avoid reloading\n level.fragmentError++;\n frag.gap = true;\n this.fragmentTracker.removeFragment(frag);\n this.fragmentTracker.fragBuffered(frag, true);\n }\n this.warn(error.message);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n frag,\n reason: `Found no media in msn ${frag.sn} of level \"${level.url}\"`,\n });\n if (!this.hls) {\n return;\n }\n this.resetTransmuxer();\n // For this error fallthrough. Marking parsed will allow advancing to next fragment.\n }\n this.state = State.PARSED;\n this.hls.trigger(Events.FRAG_PARSED, { frag, part });\n }\n\n protected resetTransmuxer() {\n if (this.transmuxer) {\n this.transmuxer.destroy();\n this.transmuxer = null;\n }\n }\n\n protected recoverWorkerError(data: ErrorData) {\n if (data.event === 'demuxerWorker') {\n this.fragmentTracker.removeAllFragments();\n this.resetTransmuxer();\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n this.resetLoadingState();\n }\n }\n\n set state(nextState) {\n const previousState = this._state;\n if (previousState !== nextState) {\n this._state = nextState;\n this.log(`${previousState}->${nextState}`);\n }\n }\n\n get state() {\n return this._state;\n }\n}\n","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 type { DemuxedTrack } from '../types/demuxer';\n\nexport function dummyTrack(type = '', inputTimeScale = 90000): DemuxedTrack {\n return {\n type,\n id: -1,\n pid: -1,\n inputTimeScale,\n sequenceNumber: -1,\n samples: [],\n dropped: 0,\n };\n}\n","import * as ID3 from '../id3';\nimport {\n DemuxerResult,\n Demuxer,\n DemuxedAudioTrack,\n AudioFrame,\n DemuxedMetadataTrack,\n DemuxedVideoTrackBase,\n DemuxedUserdataTrack,\n KeyData,\n MetadataSchema,\n} from '../../types/demuxer';\nimport { dummyTrack } from '../dummy-demuxed-track';\nimport { appendUint8Array } from '../../utils/mp4-tools';\nimport { sliceUint8 } from '../../utils/typed-array';\nimport { RationalTimestamp } from '../../utils/timescale-conversion';\n\nclass BaseAudioDemuxer implements Demuxer {\n protected _audioTrack!: DemuxedAudioTrack;\n protected _id3Track!: DemuxedMetadataTrack;\n protected frameIndex: number = 0;\n protected cachedData: Uint8Array | null = null;\n protected basePTS: number | null = null;\n protected initPTS: RationalTimestamp | null = null;\n protected lastPTS: number | null = null;\n\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n this._id3Track = {\n type: 'id3',\n id: 3,\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n };\n }\n\n resetTimeStamp(deaultTimestamp: RationalTimestamp | null) {\n this.initPTS = deaultTimestamp;\n this.resetContiguity();\n }\n\n resetContiguity(): void {\n this.basePTS = null;\n this.lastPTS = null;\n this.frameIndex = 0;\n }\n\n canParse(data: Uint8Array, offset: number): boolean {\n return false;\n }\n\n appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n ): AudioFrame | void {}\n\n // feed incoming data to the front of the parsing pipeline\n demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n if (this.cachedData) {\n data = appendUint8Array(this.cachedData, data);\n this.cachedData = null;\n }\n\n let id3Data: Uint8Array | undefined = ID3.getID3Data(data, 0);\n let offset = id3Data ? id3Data.length : 0;\n let lastDataIndex;\n const track = this._audioTrack;\n const id3Track = this._id3Track;\n const timestamp = id3Data ? ID3.getTimeStamp(id3Data) : undefined;\n const length = data.length;\n\n if (\n this.basePTS === null ||\n (this.frameIndex === 0 && Number.isFinite(timestamp))\n ) {\n this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);\n this.lastPTS = this.basePTS;\n }\n\n if (this.lastPTS === null) {\n this.lastPTS = this.basePTS;\n }\n\n // more expressive than alternative: id3Data?.length\n if (id3Data && id3Data.length > 0) {\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n }\n\n while (offset < length) {\n if (this.canParse(data, offset)) {\n const frame = this.appendFrame(track, data, offset);\n if (frame) {\n this.frameIndex++;\n this.lastPTS = frame.sample.pts;\n offset += frame.length;\n lastDataIndex = offset;\n } else {\n offset = length;\n }\n } else if (ID3.canParse(data, offset)) {\n // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data\n id3Data = ID3.getID3Data(data, offset)!;\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n offset += id3Data.length;\n lastDataIndex = offset;\n } else {\n offset++;\n }\n if (offset === length && lastDataIndex !== length) {\n const partialData = sliceUint8(data, lastDataIndex);\n if (this.cachedData) {\n this.cachedData = appendUint8Array(this.cachedData, partialData);\n } else {\n this.cachedData = partialData;\n }\n }\n }\n\n return {\n audioTrack: track,\n videoTrack: dummyTrack() as DemuxedVideoTrackBase,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error(\n `[${this}] This demuxer does not support Sample-AES decryption`,\n ),\n );\n }\n\n flush(timeOffset: number): DemuxerResult {\n // Parse cache in case of remaining frames.\n const cachedData = this.cachedData;\n if (cachedData) {\n this.cachedData = null;\n this.demux(cachedData, 0);\n }\n\n return {\n audioTrack: this._audioTrack,\n videoTrack: dummyTrack() as DemuxedVideoTrackBase,\n id3Track: this._id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n destroy() {}\n}\n\n/**\n * Initialize PTS\n * <p>\n * use timestamp unless it is undefined, NaN or Infinity\n * </p>\n */\nexport const initPTSFn = (\n timestamp: number | undefined,\n timeOffset: number,\n initPTS: RationalTimestamp | null,\n): number => {\n if (Number.isFinite(timestamp as number)) {\n return timestamp! * 90;\n }\n const init90kHz = initPTS\n ? (initPTS.baseTime * 90000) / initPTS.timescale\n : 0;\n return timeOffset * 90000 + init90kHz;\n};\nexport default BaseAudioDemuxer;\n","/**\n * ADTS parser helper\n * @link https://wiki.multimedia.cx/index.php?title=ADTS\n */\nimport { logger } from '../../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../../errors';\nimport type { HlsEventEmitter } from '../../events';\nimport { Events } from '../../events';\nimport type {\n DemuxedAudioTrack,\n AudioFrame,\n AudioSample,\n} from '../../types/demuxer';\n\ntype AudioConfig = {\n config: number[];\n samplerate: number;\n channelCount: number;\n codec: string;\n manifestCodec: string;\n};\n\ntype FrameHeader = {\n headerLength: number;\n frameLength: number;\n};\n\nexport function getAudioConfig(\n observer: HlsEventEmitter,\n data: Uint8Array,\n offset: number,\n audioCodec: string,\n): AudioConfig | void {\n let adtsObjectType: number;\n let adtsExtensionSamplingIndex: number;\n let adtsChannelConfig: number;\n let config: number[];\n const userAgent = navigator.userAgent.toLowerCase();\n const manifestCodec = audioCodec;\n const adtsSamplingRates = [\n 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025,\n 8000, 7350,\n ];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;\n const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;\n if (adtsSamplingIndex > adtsSamplingRates.length - 1) {\n const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);\n observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: true,\n error,\n reason: error.message,\n });\n return;\n }\n adtsChannelConfig = (data[offset + 2] & 0x01) << 2;\n // byte 3\n adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;\n logger.log(\n `manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`,\n );\n // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/i.test(userAgent)) {\n if (adtsSamplingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi/Opera ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if (\n (audioCodec &&\n (audioCodec.indexOf('mp4a.40.29') !== -1 ||\n audioCodec.indexOf('mp4a.40.5') !== -1)) ||\n (!audioCodec && adtsSamplingIndex >= 6)\n ) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (\n (audioCodec &&\n audioCodec.indexOf('mp4a.40.2') !== -1 &&\n ((adtsSamplingIndex >= 6 && adtsChannelConfig === 1) ||\n /vivaldi/i.test(userAgent))) ||\n (!audioCodec && adtsChannelConfig === 1)\n ) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSamplingIndex & 0x0e) >> 1;\n config[1] |= (adtsSamplingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChannelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSamplingIndex\n config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;\n config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n return {\n config,\n samplerate: adtsSamplingRates[adtsSamplingIndex],\n channelCount: adtsChannelConfig,\n codec: 'mp4a.40.' + adtsObjectType,\n manifestCodec,\n };\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nexport function getHeaderLength(data: Uint8Array, offset: number): number {\n return data[offset + 1] & 0x01 ? 7 : 9;\n}\n\nexport function getFullFrameLength(data: Uint8Array, offset: number): number {\n return (\n ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xe0) >>> 5)\n );\n}\n\nexport function canGetFrameLength(data: Uint8Array, offset: number): boolean {\n return offset + 5 < data.length;\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n return (\n canGetFrameLength(data, offset) &&\n isHeaderPattern(data, offset) &&\n getFullFrameLength(data, offset) <= data.length - offset\n );\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (isHeader(data, offset)) {\n // ADTS header Length\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n const frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n\nexport function initTrackConfig(\n track: DemuxedAudioTrack,\n observer: HlsEventEmitter,\n data: Uint8Array,\n offset: number,\n audioCodec: string,\n) {\n if (!track.samplerate) {\n const config = getAudioConfig(observer, data, offset, audioCodec);\n if (!config) {\n return;\n }\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(\n `parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`,\n );\n }\n}\n\nexport function getFrameDuration(samplerate: number): number {\n return (1024 * 90000) / samplerate;\n}\n\nexport function parseFrameHeader(\n data: Uint8Array,\n offset: number,\n): FrameHeader | void {\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength <= data.length) {\n // retrieve frame size\n const frameLength = getFullFrameLength(data, offset) - headerLength;\n if (frameLength > 0) {\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);\n return { headerLength, frameLength };\n }\n }\n}\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number,\n): AudioFrame {\n const frameDuration = getFrameDuration(track.samplerate as number);\n const stamp = pts + frameIndex * frameDuration;\n const header = parseFrameHeader(data, offset);\n let unit: Uint8Array;\n if (header) {\n const { frameLength, headerLength } = header;\n const length = headerLength + frameLength;\n const missing = Math.max(0, offset + length - data.length);\n // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);\n if (missing) {\n unit = new Uint8Array(length - headerLength);\n unit.set(data.subarray(offset + headerLength, data.length), 0);\n } else {\n unit = data.subarray(offset + headerLength, offset + length);\n }\n\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n if (!missing) {\n track.samples.push(sample as AudioSample);\n }\n\n return { sample, length, missing };\n }\n // overflow incomplete header\n const length = data.length - offset;\n unit = new Uint8Array(length);\n unit.set(data.subarray(offset, data.length), 0);\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n return { sample, length, missing: -1 };\n}\n","/**\n * MPEG parser helper\n */\nimport { DemuxedAudioTrack } from '../../types/demuxer';\n\nlet chromeVersion: number | null = null;\n\nconst BitratesMap = [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56,\n 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80,\n 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144,\n 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144,\n 160,\n];\n\nconst SamplingRateMap = [\n 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000,\n];\n\nconst SamplesCoefficients = [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0, // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n];\n\nconst BytesInSlot = [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4, // Layer1\n];\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number,\n) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return;\n }\n\n const header = parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n const frameDuration = (header.samplesPerFrame * 90000) / header.sampleRate;\n const stamp = pts + frameIndex * frameDuration;\n const sample = {\n unit: data.subarray(offset, offset + header.frameLength),\n pts: stamp,\n dts: stamp,\n };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n\n return { sample, length: header.frameLength, missing: 0 };\n }\n}\n\nexport function parseHeader(data: Uint8Array, offset: number) {\n const mpegVersion = (data[offset + 1] >> 3) & 3;\n const mpegLayer = (data[offset + 1] >> 1) & 3;\n const bitRateIndex = (data[offset + 2] >> 4) & 15;\n const sampleRateIndex = (data[offset + 2] >> 2) & 3;\n if (\n mpegVersion !== 1 &&\n bitRateIndex !== 0 &&\n bitRateIndex !== 15 &&\n sampleRateIndex !== 3\n ) {\n const paddingBit = (data[offset + 2] >> 1) & 1;\n const channelMode = data[offset + 3] >> 6;\n const columnInBitrates =\n mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;\n const bitRate =\n BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;\n const columnInSampleRates =\n mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;\n const sampleRate =\n SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];\n const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];\n const bytesInSlot = BytesInSlot[mpegLayer];\n const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n const frameLength =\n Math.floor((sampleCoefficient * bitRate) / sampleRate + paddingBit) *\n bytesInSlot;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n const needChromeFix = !!chromeVersion && chromeVersion <= 87;\n\n if (\n needChromeFix &&\n mpegLayer === 2 &&\n bitRate >= 224000 &&\n channelMode === 0\n ) {\n // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)\n data[offset + 3] = data[offset + 3] | 0x80;\n }\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\n }\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return (\n data[offset] === 0xff &&\n (data[offset + 1] & 0xe0) === 0xe0 &&\n (data[offset + 1] & 0x06) !== 0x00\n );\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n const headerSize = 4;\n\n return isHeaderPattern(data, offset) && headerSize <= data.length - offset;\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n // MPEG header Length\n const headerLength = 4;\n // MPEG frame Length\n const header = parseHeader(data, offset);\n let frameLength = headerLength;\n if (header?.frameLength) {\n frameLength = header.frameLength;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n","/**\n * AAC demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ADTS from './adts';\nimport * as MpegAudio from './mpegaudio';\nimport { logger } from '../../utils/logger';\nimport * as ID3 from '../id3';\nimport type { HlsEventEmitter } from '../../events';\nimport type { HlsConfig } from '../../config';\n\nclass AACDemuxer extends BaseAudioDemuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n\n constructor(observer, config) {\n super();\n this.observer = observer;\n this.config = config;\n }\n\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/adts',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'aac',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS\n static probe(data: Uint8Array | undefined): boolean {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0);\n let offset = id3Data?.length || 0;\n\n if (MpegAudio.probe(data, offset)) {\n return false;\n }\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return ADTS.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n track.manifestCodec,\n );\n const frame = ADTS.appendFrame(\n track,\n data,\n offset,\n this.basePTS as number,\n this.frameIndex,\n );\n if (frame && frame.missing === 0) {\n return frame;\n }\n }\n}\n\nexport default AACDemuxer;\n","/**\n * MP4 demuxer\n */\nimport {\n Demuxer,\n DemuxerResult,\n PassthroughTrack,\n DemuxedAudioTrack,\n DemuxedUserdataTrack,\n DemuxedMetadataTrack,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport {\n findBox,\n segmentValidRange,\n appendUint8Array,\n parseEmsg,\n parseSamples,\n parseInitSegment,\n RemuxerTrackIdConfig,\n hasMoofData,\n} from '../utils/mp4-tools';\nimport { dummyTrack } from './dummy-demuxed-track';\nimport type { HlsEventEmitter } from '../events';\nimport type { HlsConfig } from '../config';\n\nconst emsgSchemePattern = /\\/emsg[-/]ID3/i;\n\nclass MP4Demuxer implements Demuxer {\n private remainderData: Uint8Array | null = null;\n private timeOffset: number = 0;\n private config: HlsConfig;\n private videoTrack?: PassthroughTrack;\n private audioTrack?: DemuxedAudioTrack;\n private id3Track?: DemuxedMetadataTrack;\n private txtTrack?: DemuxedUserdataTrack;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig) {\n this.config = config;\n }\n\n public resetTimeStamp() {}\n\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n const videoTrack = (this.videoTrack = dummyTrack(\n 'video',\n 1,\n ) as PassthroughTrack);\n const audioTrack = (this.audioTrack = dummyTrack(\n 'audio',\n 1,\n ) as DemuxedAudioTrack);\n const captionTrack = (this.txtTrack = dummyTrack(\n 'text',\n 1,\n ) as DemuxedUserdataTrack);\n\n this.id3Track = dummyTrack('id3', 1) as DemuxedMetadataTrack;\n this.timeOffset = 0;\n\n if (!initSegment?.byteLength) {\n return;\n }\n const initData = parseInitSegment(initSegment);\n\n if (initData.video) {\n const { id, timescale, codec } = initData.video;\n videoTrack.id = id;\n videoTrack.timescale = captionTrack.timescale = timescale;\n videoTrack.codec = codec;\n }\n\n if (initData.audio) {\n const { id, timescale, codec } = initData.audio;\n audioTrack.id = id;\n audioTrack.timescale = timescale;\n audioTrack.codec = codec;\n }\n\n captionTrack.id = RemuxerTrackIdConfig.text;\n videoTrack.sampleDuration = 0;\n videoTrack.duration = audioTrack.duration = trackDuration;\n }\n\n public resetContiguity(): void {\n this.remainderData = null;\n }\n\n static probe(data: Uint8Array) {\n return hasMoofData(data);\n }\n\n public demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n this.timeOffset = timeOffset;\n // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter\n let videoSamples = data;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n if (this.config.progressive) {\n // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.\n // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee\n // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.\n if (this.remainderData) {\n videoSamples = appendUint8Array(this.remainderData, data);\n }\n const segmentedData = segmentValidRange(videoSamples);\n this.remainderData = segmentedData.remainder;\n videoTrack.samples = segmentedData.valid || new Uint8Array();\n } else {\n videoTrack.samples = videoSamples;\n }\n\n const id3Track = this.extractID3Track(videoTrack, timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: this.audioTrack as DemuxedAudioTrack,\n id3Track,\n textTrack: this.txtTrack as DemuxedUserdataTrack,\n };\n }\n\n public flush() {\n const timeOffset = this.timeOffset;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n videoTrack.samples = this.remainderData || new Uint8Array();\n this.remainderData = null;\n\n const id3Track = this.extractID3Track(videoTrack, this.timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: dummyTrack() as DemuxedAudioTrack,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n private extractID3Track(\n videoTrack: PassthroughTrack,\n timeOffset: number,\n ): DemuxedMetadataTrack {\n const id3Track = this.id3Track as DemuxedMetadataTrack;\n if (videoTrack.samples.length) {\n const emsgs = findBox(videoTrack.samples, ['emsg']);\n if (emsgs) {\n emsgs.forEach((data: Uint8Array) => {\n const emsgInfo = parseEmsg(data);\n if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {\n const pts = Number.isFinite(emsgInfo.presentationTime)\n ? emsgInfo.presentationTime! / emsgInfo.timeScale\n : timeOffset +\n emsgInfo.presentationTimeDelta! / emsgInfo.timeScale;\n let duration =\n emsgInfo.eventDuration === 0xffffffff\n ? Number.POSITIVE_INFINITY\n : emsgInfo.eventDuration / emsgInfo.timeScale;\n // Safari takes anything <= 0.001 seconds and maps it to Infinity\n if (duration <= 0.001) {\n duration = Number.POSITIVE_INFINITY;\n }\n const payload = emsgInfo.payload;\n id3Track.samples.push({\n data: payload,\n len: payload.byteLength,\n dts: pts,\n pts: pts,\n type: MetadataSchema.emsg,\n duration: duration,\n });\n }\n });\n }\n }\n return id3Track;\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error('The MP4 demuxer does not support SAMPLE-AES decryption'),\n );\n }\n\n destroy() {}\n}\n\nexport default MP4Demuxer;\n","export const getAudioBSID = (data: Uint8Array, offset: number): number => {\n // check the bsid to confirm ac-3 | ec-3\n let bsid = 0;\n let numBits = 5;\n offset += numBits;\n const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage\n const mask = new Uint32Array(1); // unsigned 32 bit mask value\n const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage\n while (numBits > 0) {\n byte[0] = data[offset];\n // read remaining bits, upto 8 bits at a time\n const bits = Math.min(numBits, 8);\n const shift = 8 - bits;\n mask[0] = (0xff000000 >>> (24 + shift)) << shift;\n temp[0] = (byte[0] & mask[0]) >> shift;\n bsid = !bsid ? temp[0] : (bsid << bits) | temp[0];\n offset += 1;\n numBits -= bits;\n }\n return bsid;\n};\n","import BaseAudioDemuxer from './base-audio-demuxer';\nimport { getID3Data, getTimeStamp } from '../id3';\nimport { getAudioBSID } from './dolby';\nimport type { HlsEventEmitter } from '../../events';\nimport type { AudioFrame, DemuxedAudioTrack } from '../../types/demuxer';\n\nexport class AC3Demuxer extends BaseAudioDemuxer {\n private readonly observer: HlsEventEmitter;\n\n constructor(observer) {\n super();\n this.observer = observer;\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/ac-3',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'ac3',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n canParse(data: Uint8Array, offset: number): boolean {\n return offset + 64 < data.length;\n }\n\n appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n ): AudioFrame | void {\n const frameLength = appendFrame(\n track,\n data,\n offset,\n this.basePTS as number,\n this.frameIndex,\n );\n if (frameLength !== -1) {\n const sample = track.samples[track.samples.length - 1];\n return { sample, length: frameLength, missing: 0 };\n }\n }\n\n static probe(data: Uint8Array | undefined): boolean {\n if (!data) {\n return false;\n }\n\n const id3Data = getID3Data(data, 0);\n if (!id3Data) {\n return false;\n }\n\n // look for the ac-3 sync bytes\n const offset = id3Data.length;\n if (\n data[offset] === 0x0b &&\n data[offset + 1] === 0x77 &&\n getTimeStamp(id3Data) !== undefined &&\n // check the bsid to confirm ac-3\n getAudioBSID(data, offset) < 16\n ) {\n return true;\n }\n return false;\n }\n}\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n start: number,\n pts: number,\n frameIndex: number,\n): number {\n if (start + 8 > data.length) {\n return -1; // not enough bytes left\n }\n\n if (data[start] !== 0x0b || data[start + 1] !== 0x77) {\n return -1; // invalid magic\n }\n\n // get sample rate\n const samplingRateCode = data[start + 4] >> 6;\n if (samplingRateCode >= 3) {\n return -1; // invalid sampling rate\n }\n\n const samplingRateMap = [48000, 44100, 32000];\n const sampleRate = samplingRateMap[samplingRateCode];\n\n // get frame size\n const frameSizeCode = data[start + 4] & 0x3f;\n const frameSizeMap = [\n 64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105,\n 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174,\n 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244,\n 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417,\n 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558,\n 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975,\n 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728,\n 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920,\n ];\n\n const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;\n if (start + frameLength > data.length) {\n return -1;\n }\n\n // get channel count\n const channelMode = data[start + 6] >> 5;\n let skipCount = 0;\n if (channelMode === 2) {\n skipCount += 2;\n } else {\n if (channelMode & 1 && channelMode !== 1) {\n skipCount += 2;\n }\n if (channelMode & 4) {\n skipCount += 2;\n }\n }\n\n const lfeon =\n (((data[start + 6] << 8) | data[start + 7]) >> (12 - skipCount)) & 1;\n\n const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];\n const channelCount = channelsMap[channelMode] + lfeon;\n\n // build dac3 box\n const bsid = data[start + 5] >> 3;\n const bsmod = data[start + 5] & 7;\n\n const config = new Uint8Array([\n (samplingRateCode << 6) | (bsid << 1) | (bsmod >> 2),\n ((bsmod & 3) << 6) |\n (channelMode << 3) |\n (lfeon << 2) |\n (frameSizeCode >> 4),\n (frameSizeCode << 4) & 0xe0,\n ]);\n\n const frameDuration = (1536 / sampleRate) * 90000;\n const stamp = pts + frameIndex * frameDuration;\n const unit = data.subarray(start, start + frameLength);\n\n track.config = config;\n track.channelCount = channelCount;\n track.samplerate = sampleRate;\n track.samples.push({ unit, pts: stamp });\n\n return frameLength;\n}\n","import type { ParsedVideoSample } from '../tsdemuxer';\nimport {\n DemuxedVideoTrack,\n VideoSample,\n VideoSampleUnit,\n} from '../../types/demuxer';\nimport { logger } from '../../utils/logger';\n\nclass BaseVideoParser {\n protected VideoSample: ParsedVideoSample | null = null;\n\n protected createVideoSample(\n key: boolean,\n pts: number | undefined,\n dts: number | undefined,\n debug: string,\n ): ParsedVideoSample {\n return {\n key,\n frame: false,\n pts,\n dts,\n units: [],\n debug,\n length: 0,\n };\n }\n\n protected getLastNalUnit(\n samples: VideoSample[],\n ): VideoSampleUnit | undefined {\n let VideoSample = this.VideoSample;\n let lastUnit: VideoSampleUnit | undefined;\n // try to fallback to previous sample if current one is empty\n if (!VideoSample || VideoSample.units.length === 0) {\n VideoSample = samples[samples.length - 1];\n }\n if (VideoSample?.units) {\n const units = VideoSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n protected pushAccessUnit(\n VideoSample: ParsedVideoSample,\n videoTrack: DemuxedVideoTrack,\n ) {\n if (VideoSample.units.length && VideoSample.frame) {\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (VideoSample.pts === undefined) {\n const samples = videoTrack.samples;\n const nbSamples = samples.length;\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n VideoSample.pts = lastSample.pts;\n VideoSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n videoTrack.dropped++;\n return;\n }\n }\n videoTrack.samples.push(VideoSample as VideoSample);\n }\n if (VideoSample.debug.length) {\n logger.log(\n VideoSample.pts + '/' + VideoSample.dts + ':' + VideoSample.debug,\n );\n }\n }\n}\n\nexport default BaseVideoParser;\n","/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n */\n\nimport { logger } from '../../utils/logger';\n\nclass ExpGolomb {\n private data: Uint8Array;\n public bytesAvailable: number;\n private word: number;\n private bitsAvailable: number;\n\n constructor(data: Uint8Array) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord(): void {\n const data = this.data;\n const bytesAvailable = this.bytesAvailable;\n const position = data.byteLength - bytesAvailable;\n const workingBytes = new Uint8Array(4);\n const availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits(count: number): void {\n let skipBytes; // :int\n count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= skipBytes << 3;\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits(size: number): number {\n let bits = Math.min(this.bitsAvailable, size); // :uint\n const valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n } else {\n throw new Error('no bits available');\n }\n\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return (valu << bits) | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ(): number {\n let leadingZeroCount; // :uint\n for (\n leadingZeroCount = 0;\n leadingZeroCount < this.bitsAvailable;\n ++leadingZeroCount\n ) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG(): void {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG(): void {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG(): number {\n const clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG(): number {\n const valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean(): boolean {\n return this.readBits(1) === 1;\n }\n\n // ():int\n readUByte(): number {\n return this.readBits(8);\n }\n\n // ():int\n readUShort(): number {\n return this.readBits(16);\n }\n\n // ():int\n readUInt(): number {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList(count: number): void {\n let lastScale = 8;\n let nextScale = 8;\n let deltaScale;\n for (let j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = nextScale === 0 ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @returns an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS(): {\n width: number;\n height: number;\n pixelRatio: [number, number];\n } {\n let frameCropLeftOffset = 0;\n let frameCropRightOffset = 0;\n let frameCropTopOffset = 0;\n let frameCropBottomOffset = 0;\n let numRefFramesInPicOrderCntCycle;\n let scalingListCount;\n let i;\n const readUByte = this.readUByte.bind(this);\n const readBits = this.readBits.bind(this);\n const readUEG = this.readUEG.bind(this);\n const readBoolean = this.readBoolean.bind(this);\n const skipBits = this.skipBits.bind(this);\n const skipEG = this.skipEG.bind(this);\n const skipUEG = this.skipUEG.bind(this);\n const skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n const profileIdc = readUByte(); // profile_idc\n readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n readUByte(); // level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (\n profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128\n ) {\n const chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // separate_colour_plane_flag\n\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) {\n // seq_scaling_matrix_present_flag\n scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) {\n // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n const picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG();\n } // offset_for_ref_frame[ i ]\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n const picWidthInMbsMinus1 = readUEG();\n const picHeightInMapUnitsMinus1 = readUEG();\n const frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) {\n // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio: [number, number] = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1:\n pixelRatio = [1, 1];\n break;\n case 2:\n pixelRatio = [12, 11];\n break;\n case 3:\n pixelRatio = [10, 11];\n break;\n case 4:\n pixelRatio = [16, 11];\n break;\n case 5:\n pixelRatio = [40, 33];\n break;\n case 6:\n pixelRatio = [24, 11];\n break;\n case 7:\n pixelRatio = [20, 11];\n break;\n case 8:\n pixelRatio = [32, 11];\n break;\n case 9:\n pixelRatio = [80, 33];\n break;\n case 10:\n pixelRatio = [18, 11];\n break;\n case 11:\n pixelRatio = [15, 11];\n break;\n case 12:\n pixelRatio = [64, 33];\n break;\n case 13:\n pixelRatio = [160, 99];\n break;\n case 14:\n pixelRatio = [4, 3];\n break;\n case 15:\n pixelRatio = [3, 2];\n break;\n case 16:\n pixelRatio = [2, 1];\n break;\n case 255: {\n pixelRatio = [\n (readUByte() << 8) | readUByte(),\n (readUByte() << 8) | readUByte(),\n ];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil(\n (picWidthInMbsMinus1 + 1) * 16 -\n frameCropLeftOffset * 2 -\n frameCropRightOffset * 2,\n ),\n height:\n (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 -\n (frameMbsOnlyFlag ? 2 : 4) *\n (frameCropTopOffset + frameCropBottomOffset),\n pixelRatio: pixelRatio,\n };\n }\n\n readSliceType() {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n","import BaseVideoParser from './base-video-parser';\nimport {\n DemuxedVideoTrack,\n DemuxedUserdataTrack,\n VideoSampleUnit,\n} from '../../types/demuxer';\nimport {\n appendUint8Array,\n parseSEIMessageFromNALu,\n} from '../../utils/mp4-tools';\nimport ExpGolomb from './exp-golomb';\nimport type { PES } from '../tsdemuxer';\n\nclass AvcVideoParser extends BaseVideoParser {\n public parseAVCPES(\n track: DemuxedVideoTrack,\n textTrack: DemuxedUserdataTrack,\n pes: PES,\n last: boolean,\n duration: number,\n ) {\n const units = this.parseAVCNALu(track, pes.data);\n const debug = false;\n let VideoSample = this.VideoSample;\n let push: boolean;\n let spsfound = false;\n // free pes.data to save up some memory\n (pes as any).data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (VideoSample && units.length && !track.audFound) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = this.createVideoSample(\n false,\n pes.pts,\n pes.dts,\n '',\n );\n }\n\n units.forEach((unit) => {\n switch (unit.type) {\n // NDR\n case 1: {\n let iskey = false;\n push = true;\n const data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n const sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n // if (sliceType === 2 || sliceType === 7) {\n if (\n sliceType === 2 ||\n sliceType === 4 ||\n sliceType === 7 ||\n sliceType === 9\n ) {\n iskey = true;\n }\n }\n\n if (iskey) {\n // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push\n if (VideoSample?.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n }\n\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(\n true,\n pes.pts,\n pes.dts,\n '',\n );\n }\n\n if (debug) {\n VideoSample.debug += 'NDR ';\n }\n\n VideoSample.frame = true;\n VideoSample.key = iskey;\n\n break;\n // IDR\n }\n case 5:\n push = true;\n // handle PES not starting with AUD\n // if we have frame data already, that cannot belong to the same frame, so force a push\n if (VideoSample?.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(\n true,\n pes.pts,\n pes.dts,\n '',\n );\n }\n\n if (debug) {\n VideoSample.debug += 'IDR ';\n }\n\n VideoSample.key = true;\n VideoSample.frame = true;\n break;\n // SEI\n case 6: {\n push = true;\n if (debug && VideoSample) {\n VideoSample.debug += 'SEI ';\n }\n parseSEIMessageFromNALu(\n unit.data,\n 1,\n pes.pts as number,\n textTrack.samples,\n );\n break;\n // SPS\n }\n case 7: {\n push = true;\n spsfound = true;\n if (debug && VideoSample) {\n VideoSample.debug += 'SPS ';\n }\n const sps = unit.data;\n const expGolombDecoder = new ExpGolomb(sps);\n const config = expGolombDecoder.readSPS();\n\n if (\n !track.sps ||\n track.width !== config.width ||\n track.height !== config.height ||\n track.pixelRatio?.[0] !== config.pixelRatio[0] ||\n track.pixelRatio?.[1] !== config.pixelRatio[1]\n ) {\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [sps];\n track.duration = duration;\n const codecarray = sps.subarray(1, 4);\n let codecstring = 'avc1.';\n for (let i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n codecstring += h;\n }\n track.codec = codecstring;\n }\n\n break;\n }\n // PPS\n case 8:\n push = true;\n if (debug && VideoSample) {\n VideoSample.debug += 'PPS ';\n }\n\n track.pps = [unit.data];\n\n break;\n // AUD\n case 9:\n push = true;\n track.audFound = true;\n if (VideoSample) {\n this.pushAccessUnit(VideoSample, track);\n }\n\n VideoSample = this.VideoSample = this.createVideoSample(\n false,\n pes.pts,\n pes.dts,\n debug ? 'AUD ' : '',\n );\n break;\n // Filler Data\n case 12:\n push = true;\n break;\n default:\n push = false;\n if (VideoSample) {\n VideoSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (VideoSample && push) {\n const units = VideoSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && VideoSample) {\n this.pushAccessUnit(VideoSample, track);\n this.VideoSample = null;\n }\n }\n\n private parseAVCNALu(\n track: DemuxedVideoTrack,\n array: Uint8Array,\n ): Array<{\n data: Uint8Array;\n type: number;\n state?: number;\n }> {\n const len = array.byteLength;\n let state = track.naluState || 0;\n const lastState = state;\n const units: VideoSampleUnit[] = [];\n let i = 0;\n let value: number;\n let overflow: number;\n let unitType: number;\n let lastUnitStart = -1;\n let lastUnitType: number = 0;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n overflow = i - state - 1;\n if (lastUnitStart >= 0) {\n const unit: VideoSampleUnit = {\n data: array.subarray(lastUnitStart, overflow),\n type: lastUnitType,\n };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n if (lastState && i <= 4 - lastState) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(\n 0,\n lastUnit.data.byteLength - lastState,\n );\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n lastUnit.data = appendUint8Array(\n lastUnit.data,\n array.subarray(0, overflow),\n );\n lastUnit.state = 0;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n const unit: VideoSampleUnit = {\n data: array.subarray(lastUnitStart, len),\n type: lastUnitType,\n state: state,\n };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n lastUnit.data = appendUint8Array(lastUnit.data, array);\n }\n }\n track.naluState = state;\n return units;\n }\n}\n\nexport default AvcVideoParser;\n","/**\n * SAMPLE-AES decrypter\n */\n\nimport { HlsConfig } from '../config';\nimport Decrypter from '../crypt/decrypter';\nimport { HlsEventEmitter } from '../events';\nimport type {\n AudioSample,\n VideoSample,\n VideoSampleUnit,\n DemuxedVideoTrackBase,\n KeyData,\n} from '../types/demuxer';\nimport { discardEPB } from '../utils/mp4-tools';\n\nclass SampleAesDecrypter {\n private keyData: KeyData;\n private decrypter: Decrypter;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig, keyData: KeyData) {\n this.keyData = keyData;\n this.decrypter = new Decrypter(config, {\n removePKCS7Padding: false,\n });\n }\n\n decryptBuffer(encryptedData: Uint8Array | ArrayBuffer): Promise<ArrayBuffer> {\n return this.decrypter.decrypt(\n encryptedData,\n this.keyData.key.buffer,\n this.keyData.iv.buffer,\n );\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n private decryptAacSample(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void,\n ) {\n const curUnit = samples[sampleIndex].unit;\n if (curUnit.length <= 16) {\n // No encrypted portion in this sample (first 16 bytes is not\n // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),\n return;\n }\n const encryptedData = curUnit.subarray(\n 16,\n curUnit.length - (curUnit.length % 16),\n );\n const encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length,\n );\n\n this.decryptBuffer(encryptedBuffer).then((decryptedBuffer: ArrayBuffer) => {\n const decryptedData = new Uint8Array(decryptedBuffer);\n curUnit.set(decryptedData, 16);\n\n if (!this.decrypter.isSync()) {\n this.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void,\n ) {\n for (; ; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n this.decryptAacSample(samples, sampleIndex, callback);\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData(decodedData: Uint8Array) {\n const encryptedDataLen =\n Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n const encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (\n let inputPos = 32;\n inputPos < decodedData.length - 16;\n inputPos += 160, outputPos += 16\n ) {\n encryptedData.set(\n decodedData.subarray(inputPos, inputPos + 16),\n outputPos,\n );\n }\n\n return encryptedData;\n }\n\n getAvcDecryptedUnit(\n decodedData: Uint8Array,\n decryptedData: ArrayLike<number> | ArrayBuffer | SharedArrayBuffer,\n ) {\n const uint8DecryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (\n let outputPos = 32;\n outputPos < decodedData.length - 16;\n outputPos += 160, inputPos += 16\n ) {\n decodedData.set(\n uint8DecryptedData.subarray(inputPos, inputPos + 16),\n outputPos,\n );\n }\n\n return decodedData;\n }\n\n decryptAvcSample(\n samples: VideoSample[],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void,\n curUnit: VideoSampleUnit,\n ) {\n const decodedData = discardEPB(curUnit.data);\n const encryptedData = this.getAvcEncryptedData(decodedData);\n\n this.decryptBuffer(encryptedData.buffer).then(\n (decryptedBuffer: ArrayBuffer) => {\n curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);\n\n if (!this.decrypter.isSync()) {\n this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n },\n );\n }\n\n decryptAvcSamples(\n samples: DemuxedVideoTrackBase['samples'],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void,\n ) {\n if (samples instanceof Uint8Array) {\n throw new Error('Cannot decrypt samples of type Uint8Array');\n }\n\n for (; ; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n const curUnits = samples[sampleIndex].units;\n for (; ; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n const curUnit = curUnits[unitIndex];\n if (\n curUnit.data.length <= 48 ||\n (curUnit.type !== 1 && curUnit.type !== 5)\n ) {\n continue;\n }\n\n this.decryptAvcSample(\n samples,\n sampleIndex,\n unitIndex,\n callback,\n curUnit,\n );\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n }\n}\n\nexport default SampleAesDecrypter;\n","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n */\n\nimport * as ADTS from './audio/adts';\nimport * as MpegAudio from './audio/mpegaudio';\nimport * as AC3 from './audio/ac3-demuxer';\nimport AvcVideoParser from './video/avc-video-parser';\nimport SampleAesDecrypter from './sample-aes';\nimport { Events } from '../events';\nimport { appendUint8Array, RemuxerTrackIdConfig } from '../utils/mp4-tools';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport type { HlsConfig } from '../config';\nimport type { HlsEventEmitter } from '../events';\nimport {\n DemuxedVideoTrack,\n DemuxedAudioTrack,\n DemuxedTrack,\n Demuxer,\n DemuxerResult,\n VideoSample,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n ElementaryStreamData,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport { AudioFrame } from '../types/demuxer';\n\nexport type ParsedTimestamp = {\n pts?: number;\n dts?: number;\n};\n\nexport type PES = ParsedTimestamp & {\n data: Uint8Array;\n len: number;\n};\n\nexport type ParsedVideoSample = ParsedTimestamp &\n Omit<VideoSample, 'pts' | 'dts'>;\n\nexport interface TypeSupported {\n mpeg: boolean;\n mp3: boolean;\n ac3: boolean;\n}\n\nconst PACKET_LENGTH = 188;\n\nclass TSDemuxer implements Demuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n private typeSupported: TypeSupported;\n\n private sampleAes: SampleAesDecrypter | null = null;\n private pmtParsed: boolean = false;\n private audioCodec?: string;\n private videoCodec?: string;\n private _duration: number = 0;\n private _pmtId: number = -1;\n\n private _videoTrack?: DemuxedVideoTrack;\n private _audioTrack?: DemuxedAudioTrack;\n private _id3Track?: DemuxedMetadataTrack;\n private _txtTrack?: DemuxedUserdataTrack;\n private aacOverFlow: AudioFrame | null = null;\n private remainderData: Uint8Array | null = null;\n private videoParser: AvcVideoParser;\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported: TypeSupported,\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.videoParser = new AvcVideoParser();\n }\n\n static probe(data: Uint8Array) {\n const syncOffset = TSDemuxer.syncOffset(data);\n if (syncOffset > 0) {\n logger.warn(\n `MPEG2-TS detected but first sync word found @ offset ${syncOffset}`,\n );\n }\n return syncOffset !== -1;\n }\n\n static syncOffset(data: Uint8Array): number {\n const length = data.length;\n let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;\n let i = 0;\n while (i < scanwindow) {\n // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47\n let foundPat = false;\n let packetStart = -1;\n let tsPackets = 0;\n for (let j = i; j < length; j += PACKET_LENGTH) {\n if (\n data[j] === 0x47 &&\n (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)\n ) {\n tsPackets++;\n if (packetStart === -1) {\n packetStart = j;\n // First sync word found at offset, increase scan length (#5251)\n if (packetStart !== 0) {\n scanwindow =\n Math.min(\n packetStart + PACKET_LENGTH * 99,\n data.length - PACKET_LENGTH,\n ) + 1;\n }\n }\n if (!foundPat) {\n foundPat = parsePID(data, j) === 0;\n }\n // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)\n if (\n foundPat &&\n tsPackets > 1 &&\n ((packetStart === 0 && tsPackets > 2) ||\n j + PACKET_LENGTH > scanwindow)\n ) {\n return packetStart;\n }\n } else if (tsPackets) {\n // Exit if sync word found, but does not contain contiguous packets\n return -1;\n } else {\n break;\n }\n }\n i++;\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n */\n static createTrack(\n type: 'audio' | 'video' | 'id3' | 'text',\n duration?: number,\n ): DemuxedTrack {\n return {\n container:\n type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n duration: type === 'audio' ? duration : undefined,\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n */\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string,\n videoCodec: string,\n trackDuration: number,\n ) {\n this.pmtParsed = false;\n this._pmtId = -1;\n\n this._videoTrack = TSDemuxer.createTrack('video') as DemuxedVideoTrack;\n this._audioTrack = TSDemuxer.createTrack(\n 'audio',\n trackDuration,\n ) as DemuxedAudioTrack;\n this._id3Track = TSDemuxer.createTrack('id3') as DemuxedMetadataTrack;\n this._txtTrack = TSDemuxer.createTrack('text') as DemuxedUserdataTrack;\n this._audioTrack.segmentCodec = 'aac';\n\n // flush any partial content\n this.aacOverFlow = null;\n this.remainderData = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = trackDuration;\n }\n\n public resetTimeStamp() {}\n\n public resetContiguity(): void {\n const { _audioTrack, _videoTrack, _id3Track } = this;\n if (_audioTrack) {\n _audioTrack.pesData = null;\n }\n if (_videoTrack) {\n _videoTrack.pesData = null;\n }\n if (_id3Track) {\n _id3Track.pesData = null;\n }\n this.aacOverFlow = null;\n this.remainderData = null;\n }\n\n public demux(\n data: Uint8Array,\n timeOffset: number,\n isSampleAes = false,\n flush = false,\n ): DemuxerResult {\n if (!isSampleAes) {\n this.sampleAes = null;\n }\n\n let pes: PES | null;\n\n const videoTrack = this._videoTrack as DemuxedVideoTrack;\n const audioTrack = this._audioTrack as DemuxedAudioTrack;\n const id3Track = this._id3Track as DemuxedMetadataTrack;\n const textTrack = this._txtTrack as DemuxedUserdataTrack;\n\n let videoPid = videoTrack.pid;\n let videoData = videoTrack.pesData;\n let audioPid = audioTrack.pid;\n let id3Pid = id3Track.pid;\n let audioData = audioTrack.pesData;\n let id3Data = id3Track.pesData;\n let unknownPID: number | null = null;\n let pmtParsed = this.pmtParsed;\n let pmtId = this._pmtId;\n\n let len = data.length;\n if (this.remainderData) {\n data = appendUint8Array(this.remainderData, data);\n len = data.length;\n this.remainderData = null;\n }\n\n if (len < PACKET_LENGTH && !flush) {\n this.remainderData = data;\n return {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n }\n\n const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));\n len -= (len - syncOffset) % PACKET_LENGTH;\n if (len < data.byteLength && !flush) {\n this.remainderData = new Uint8Array(\n data.buffer,\n len,\n data.buffer.byteLength - len,\n );\n }\n\n // loop through TS packets\n let tsPacketErrors = 0;\n for (let start = syncOffset; start < len; start += PACKET_LENGTH) {\n if (data[start] === 0x47) {\n const stt = !!(data[start + 1] & 0x40);\n const pid = parsePID(data, start);\n const atf = (data[start + 3] & 0x30) >> 4;\n\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n let offset: number;\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === start + PACKET_LENGTH) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case videoPid:\n if (stt) {\n if (videoData && (pes = parsePES(videoData))) {\n this.videoParser.parseAVCPES(\n videoTrack,\n textTrack,\n pes,\n false,\n this._duration,\n );\n }\n\n videoData = { data: [], size: 0 };\n }\n if (videoData) {\n videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n videoData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case audioPid:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n case 'ac3':\n if (__USE_M2TS_ADVANCED_CODECS__) {\n this.parseAC3PES(audioTrack, pes);\n }\n break;\n }\n }\n audioData = { data: [], size: 0 };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n audioData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case id3Pid:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n }\n\n id3Data = { data: [], size: 0 };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));\n id3Data.size += start + PACKET_LENGTH - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n pmtId = this._pmtId = parsePAT(data, offset);\n // logger.log('PMT PID:' + this._pmtId);\n break;\n case pmtId: {\n if (stt) {\n offset += data[offset] + 1;\n }\n\n const parsedPIDs = parsePMT(\n data,\n offset,\n this.typeSupported,\n isSampleAes,\n this.observer,\n );\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n videoPid = parsedPIDs.videoPid;\n if (videoPid > 0) {\n videoTrack.pid = videoPid;\n videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;\n }\n\n audioPid = parsedPIDs.audioPid;\n if (audioPid > 0) {\n audioTrack.pid = audioPid;\n audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;\n }\n id3Pid = parsedPIDs.id3Pid;\n if (id3Pid > 0) {\n id3Track.pid = id3Pid;\n }\n\n if (unknownPID !== null && !pmtParsed) {\n logger.warn(\n `MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`,\n );\n unknownPID = null;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset - 188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n }\n case 0x11:\n case 0x1fff:\n break;\n default:\n unknownPID = pid;\n break;\n }\n } else {\n tsPacketErrors++;\n }\n }\n\n if (tsPacketErrors > 0) {\n emitParsingError(\n this.observer,\n new Error(\n `Found ${tsPacketErrors} TS packet/s that do not start with 0x47`,\n ),\n );\n }\n\n videoTrack.pesData = videoData;\n audioTrack.pesData = audioData;\n id3Track.pesData = id3Data;\n\n const demuxResult: DemuxerResult = {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n\n if (flush) {\n this.extractRemainingSamples(demuxResult);\n }\n\n return demuxResult;\n }\n\n public flush(): DemuxerResult | Promise<DemuxerResult> {\n const { remainderData } = this;\n this.remainderData = null;\n let result: DemuxerResult;\n if (remainderData) {\n result = this.demux(remainderData, -1, false, true);\n } else {\n result = {\n videoTrack: this._videoTrack as DemuxedVideoTrack,\n audioTrack: this._audioTrack as DemuxedAudioTrack,\n id3Track: this._id3Track as DemuxedMetadataTrack,\n textTrack: this._txtTrack as DemuxedUserdataTrack,\n };\n }\n this.extractRemainingSamples(result);\n if (this.sampleAes) {\n return this.decrypt(result, this.sampleAes);\n }\n return result;\n }\n\n private extractRemainingSamples(demuxResult: DemuxerResult) {\n const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult;\n const videoData = videoTrack.pesData;\n const audioData = audioTrack.pesData;\n const id3Data = id3Track.pesData;\n // try to parse last PES packets\n let pes: PES | null;\n if (videoData && (pes = parsePES(videoData))) {\n this.videoParser.parseAVCPES(\n videoTrack as DemuxedVideoTrack,\n textTrack as DemuxedUserdataTrack,\n pes,\n true,\n this._duration,\n );\n videoTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n videoTrack.pesData = videoData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n case 'ac3':\n if (__USE_M2TS_ADVANCED_CODECS__) {\n this.parseAC3PES(audioTrack, pes);\n }\n break;\n }\n audioTrack.pesData = null;\n } else {\n if (audioData?.size) {\n logger.log(\n 'last AAC PES packet truncated,might overlap between fragments',\n );\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n }\n\n public demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number,\n ): Promise<DemuxerResult> {\n const demuxResult = this.demux(\n data,\n timeOffset,\n true,\n !this.config.progressive,\n );\n const sampleAes = (this.sampleAes = new SampleAesDecrypter(\n this.observer,\n this.config,\n keyData,\n ));\n return this.decrypt(demuxResult, sampleAes);\n }\n\n private decrypt(\n demuxResult: DemuxerResult,\n sampleAes: SampleAesDecrypter,\n ): Promise<DemuxerResult> {\n return new Promise((resolve) => {\n const { audioTrack, videoTrack } = demuxResult;\n if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {\n sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {\n if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n } else {\n resolve(demuxResult);\n }\n });\n } else if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n }\n });\n }\n\n public destroy() {\n this._duration = 0;\n }\n\n private parseAACPES(track: DemuxedAudioTrack, pes: PES) {\n let startOffset = 0;\n const aacOverFlow = this.aacOverFlow;\n let data = pes.data;\n if (aacOverFlow) {\n this.aacOverFlow = null;\n const frameMissingBytes = aacOverFlow.missing;\n const sampleLength = aacOverFlow.sample.unit.byteLength;\n // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);\n if (frameMissingBytes === -1) {\n data = appendUint8Array(aacOverFlow.sample.unit, data);\n } else {\n const frameOverflowBytes = sampleLength - frameMissingBytes;\n aacOverFlow.sample.unit.set(\n data.subarray(0, frameMissingBytes),\n frameOverflowBytes,\n );\n track.samples.push(aacOverFlow.sample);\n startOffset = aacOverFlow.missing;\n }\n }\n // look for ADTS header (0xFFFx)\n let offset: number;\n let len: number;\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset !== startOffset) {\n let reason: string;\n const recoverable = offset < len - 1;\n if (recoverable) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n } else {\n reason = 'No ADTS header found in AAC PES';\n }\n emitParsingError(this.observer, new Error(reason), recoverable);\n if (!recoverable) {\n return;\n }\n }\n\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n this.audioCodec as string,\n );\n\n let pts: number;\n if (pes.pts !== undefined) {\n pts = pes.pts;\n } else if (aacOverFlow) {\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n const frameDuration = ADTS.getFrameDuration(track.samplerate as number);\n pts = aacOverFlow.sample.pts + frameDuration;\n } else {\n logger.warn('[tsdemuxer]: AAC PES unknown PTS');\n return;\n }\n\n // scan for aac samples\n let frameIndex = 0;\n let frame;\n while (offset < len) {\n frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n offset += frame.length;\n if (!frame.missing) {\n frameIndex++;\n for (; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n } else {\n this.aacOverFlow = frame;\n break;\n }\n }\n }\n\n private parseMPEGPES(track: DemuxedAudioTrack, pes: PES) {\n const data = pes.data;\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n const pts = pes.pts;\n if (pts === undefined) {\n logger.warn('[tsdemuxer]: MPEG PES unknown PTS');\n return;\n }\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n const frame = MpegAudio.appendFrame(\n track,\n data,\n offset,\n pts,\n frameIndex,\n );\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n\n private parseAC3PES(track: DemuxedAudioTrack, pes: PES) {\n if (__USE_M2TS_ADVANCED_CODECS__) {\n const data = pes.data;\n const pts = pes.pts;\n if (pts === undefined) {\n logger.warn('[tsdemuxer]: AC3 PES unknown PTS');\n return;\n }\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let parsed;\n\n while (\n offset < length &&\n (parsed = AC3.appendFrame(track, data, offset, pts, frameIndex++)) > 0\n ) {\n offset += parsed;\n }\n }\n }\n\n private parseID3PES(id3Track: DemuxedMetadataTrack, pes: PES) {\n if (pes.pts === undefined) {\n logger.warn('[tsdemuxer]: ID3 PES unknown PTS');\n return;\n }\n const id3Sample = Object.assign({}, pes as Required<PES>, {\n type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n id3Track.samples.push(id3Sample);\n }\n}\n\nfunction parsePID(data: Uint8Array, offset: number): number {\n // pid is a 13-bit field starting at the last bit of TS[1]\n return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];\n}\n\nfunction parsePAT(data: Uint8Array, offset: number): number {\n // skip the PSI header and parse the first PMT entry\n return ((data[offset + 10] & 0x1f) << 8) | data[offset + 11];\n}\n\nfunction parsePMT(\n data: Uint8Array,\n offset: number,\n typeSupported: TypeSupported,\n isSampleAes: boolean,\n observer: HlsEventEmitter,\n) {\n const result = {\n audioPid: -1,\n videoPid: -1,\n id3Pid: -1,\n segmentVideoCodec: 'avc',\n segmentAudioCodec: 'aac',\n };\n const sectionLength = ((data[offset + 1] & 0x0f) << 8) | data[offset + 2];\n const tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n const programInfoLength =\n ((data[offset + 10] & 0x0f) << 8) | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n const pid = parsePID(data, offset);\n const esInfoLength = ((data[offset + 3] & 0x0f) << 8) | data[offset + 4];\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');\n break;\n }\n /* falls through */\n case 0x0f: // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n // logger.log('AAC PID:' + pid);\n if (result.audioPid === -1) {\n result.audioPid = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3Pid === -1) {\n result.id3Pid = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('H.264');\n break;\n }\n /* falls through */\n case 0x1b: // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n // logger.log('AVC PID:' + pid);\n if (result.videoPid === -1) {\n result.videoPid = pid;\n result.segmentVideoCodec = 'avc';\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (!typeSupported.mpeg && !typeSupported.mp3) {\n logger.log('MPEG audio found, not supported in this browser');\n } else if (result.audioPid === -1) {\n result.audioPid = pid;\n result.segmentAudioCodec = 'mp3';\n }\n break;\n\n case 0xc1: // SAMPLE-AES AC3\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('AC-3');\n break;\n }\n /* falls through */\n case 0x81:\n if (__USE_M2TS_ADVANCED_CODECS__) {\n if (!typeSupported.ac3) {\n logger.log('AC-3 audio found, not supported in this browser');\n } else if (result.audioPid === -1) {\n result.audioPid = pid;\n result.segmentAudioCodec = 'ac3';\n }\n } else {\n logger.warn('AC-3 in M2TS support not included in build');\n }\n break;\n\n case 0x06:\n // stream_type 6 can mean a lot of different things in case of DVB.\n // We need to look at the descriptors. Right now, we're only interested\n // in AC-3 audio, so we do the descriptor parsing only when we don't have\n // an audio PID yet.\n if (result.audioPid === -1 && esInfoLength > 0) {\n let parsePos = offset + 5;\n let remaining = esInfoLength;\n\n while (remaining > 2) {\n const descriptorId = data[parsePos];\n\n switch (descriptorId) {\n case 0x6a: // DVB Descriptor for AC-3\n if (__USE_M2TS_ADVANCED_CODECS__) {\n if (typeSupported.ac3 !== true) {\n logger.log(\n 'AC-3 audio found, not supported in this browser for now',\n );\n } else {\n result.audioPid = pid;\n result.segmentAudioCodec = 'ac3';\n }\n } else {\n logger.warn('AC-3 in M2TS support not included in build');\n }\n break;\n }\n\n const descriptorLen = data[parsePos + 1] + 2;\n parsePos += descriptorLen;\n remaining -= descriptorLen;\n }\n }\n break;\n\n case 0xc2: // SAMPLE-AES EC3\n /* falls through */\n case 0x87:\n emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'));\n return result;\n\n case 0x24:\n emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'));\n return result;\n\n default:\n // logger.log('unknown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += esInfoLength + 5;\n }\n return result;\n}\n\nfunction emitParsingError(\n observer: HlsEventEmitter,\n error: Error,\n levelRetry?: boolean,\n) {\n logger.warn(`parsing error: ${error.message}`);\n observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n levelRetry,\n error,\n reason: error.message,\n });\n}\n\nfunction logEncryptedSamplesFoundInUnencryptedStream(type: string) {\n logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);\n}\n\nfunction parsePES(stream: ElementaryStreamData): PES | null {\n let i = 0;\n let frag: Uint8Array;\n let pesLen: number;\n let pesHdrLen: number;\n let pesPts: number | undefined;\n let pesDts: number | undefined;\n const data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n data[0] = appendUint8Array(data[0], data[1]);\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n\n const pesFlags = frag[7];\n if (pesFlags & 0xc0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts =\n (frag[9] & 0x0e) * 536870912 + // 1 << 29\n (frag[10] & 0xff) * 4194304 + // 1 << 22\n (frag[11] & 0xfe) * 16384 + // 1 << 14\n (frag[12] & 0xff) * 128 + // 1 << 7\n (frag[13] & 0xfe) / 2;\n\n if (pesFlags & 0x40) {\n pesDts =\n (frag[14] & 0x0e) * 536870912 + // 1 << 29\n (frag[15] & 0xff) * 4194304 + // 1 << 22\n (frag[16] & 0xfe) * 16384 + // 1 << 14\n (frag[17] & 0xff) * 128 + // 1 << 7\n (frag[18] & 0xfe) / 2;\n\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(\n `${Math.round(\n (pesPts - pesDts) / 90000,\n )}s delta between PTS and DTS, align them`,\n );\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n let payloadStartOffset = pesHdrLen + 9;\n if (stream.size <= payloadStartOffset) {\n return null;\n }\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n const pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };\n }\n return null;\n}\n\nexport default TSDemuxer;\n","/**\n * MP3 demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport { getID3Data, getTimeStamp } from '../id3';\nimport { getAudioBSID } from './dolby';\nimport { logger } from '../../utils/logger';\nimport * as MpegAudio from './mpegaudio';\n\nclass MP3Demuxer extends BaseAudioDemuxer {\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/mpeg',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'mp3',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n static probe(data: Uint8Array | undefined): boolean {\n if (!data) {\n return false;\n }\n\n // check if data contains ID3 timestamp and MPEG sync word\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n const id3Data = getID3Data(data, 0);\n let offset = id3Data?.length || 0;\n\n // Check for ac-3|ec-3 sync bytes and return false if present\n if (\n id3Data &&\n data[offset] === 0x0b &&\n data[offset + 1] === 0x77 &&\n getTimeStamp(id3Data) !== undefined &&\n // check the bsid to confirm ac-3 or ec-3 (not mp3)\n getAudioBSID(data, offset) <= 16\n ) {\n return false;\n }\n\n for (let length = data.length; offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return MpegAudio.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n if (this.basePTS === null) {\n return;\n }\n return MpegAudio.appendFrame(\n track,\n data,\n offset,\n this.basePTS,\n this.frameIndex,\n );\n }\n}\n\nexport default MP3Demuxer;\n","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame(\n codec?: string,\n channelCount?: number,\n ): Uint8Array | undefined {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([\n 0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80,\n ]);\n } else if (channelCount === 3) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x8e,\n ]);\n } else if (channelCount === 4) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38,\n ]);\n } else if (channelCount === 5) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38,\n ]);\n } else if (channelCount === 6) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2,\n 0x00, 0x20, 0x08, 0xe0,\n ]);\n }\n\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n }\n break;\n }\n return undefined;\n }\n}\n\nexport default AAC;\n","/**\n * Generate MP4 Box\n */\n\nimport { appendUint8Array } from '../utils/mp4-tools';\n\ntype HdlrTypes = {\n video: Uint8Array;\n audio: Uint8Array;\n};\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n public static types: Record<string, number[]>;\n private static HDLR_TYPES: HdlrTypes;\n private static STTS: Uint8Array;\n private static STSC: Uint8Array;\n private static STCO: Uint8Array;\n private static STSZ: Uint8Array;\n private static VMHD: Uint8Array;\n private static SMHD: Uint8Array;\n private static STSD: Uint8Array;\n private static FTYP: Uint8Array;\n private static DINF: Uint8Array;\n\n static init() {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n dac3: [],\n 'ac-3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: [],\n };\n\n let i: string;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3),\n ];\n }\n }\n\n const videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x76,\n 0x69,\n 0x64,\n 0x65, // handler_type: 'vide'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x56,\n 0x69,\n 0x64,\n 0x65,\n 0x6f,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'VideoHandler'\n ]);\n\n const audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x73,\n 0x6f,\n 0x75,\n 0x6e, // handler_type: 'soun'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x53,\n 0x6f,\n 0x75,\n 0x6e,\n 0x64,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n video: videoHdlr,\n audio: audioHdlr,\n };\n\n const dref = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01, // entry_count\n 0x00,\n 0x00,\n 0x00,\n 0x0c, // entry_size\n 0x75,\n 0x72,\n 0x6c,\n 0x20, // 'url' type\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x01, // entry_flags\n ]);\n\n const stco = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x01, // flags\n 0x00,\n 0x00, // graphicsmode\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00, // balance\n 0x00,\n 0x00, // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n ]); // entry_count\n\n const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n const minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(\n MP4.types.ftyp,\n majorBrand,\n minorVersion,\n majorBrand,\n avc1Brand,\n );\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box(type, ...payload: Uint8Array[]) {\n let size = 8;\n let i = payload.length;\n const len = i;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n\n const result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.mdhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x55,\n 0xc4, // 'und' language (undetermined)\n 0x00,\n 0x00,\n ]),\n );\n }\n\n static mdia(track) {\n return MP4.box(\n MP4.types.mdia,\n MP4.mdhd(track.timescale, track.duration),\n MP4.hdlr(track.type),\n MP4.minf(track),\n );\n }\n\n static mfhd(sequenceNumber) {\n return MP4.box(\n MP4.types.mfhd,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00,\n 0x00, // flags\n sequenceNumber >> 24,\n (sequenceNumber >> 16) & 0xff,\n (sequenceNumber >> 8) & 0xff,\n sequenceNumber & 0xff, // sequence_number\n ]),\n );\n }\n\n static minf(track) {\n if (track.type === 'audio') {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.smhd, MP4.SMHD),\n MP4.DINF,\n MP4.stbl(track),\n );\n } else {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.vmhd, MP4.VMHD),\n MP4.DINF,\n MP4.stbl(track),\n );\n }\n }\n\n static moof(sn, baseMediaDecodeTime, track) {\n return MP4.box(\n MP4.types.moof,\n MP4.mfhd(sn),\n MP4.traf(track, baseMediaDecodeTime),\n );\n }\n\n static moov(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(\n null,\n [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)]\n .concat(boxes)\n .concat(MP4.mvex(tracks)),\n );\n }\n\n static mvex(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);\n }\n\n static mvhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n const bytes = new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x01,\n 0x00,\n 0x00, // 1.0 rate\n 0x01,\n 0x00, // 1.0 volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0xff,\n 0xff,\n 0xff,\n 0xff, // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp(track) {\n const samples = track.samples || [];\n const bytes = new Uint8Array(4 + samples.length);\n let i;\n let flags;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] =\n (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n flags.hasRedundancy;\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl(track) {\n return MP4.box(\n MP4.types.stbl,\n MP4.stsd(track),\n MP4.box(MP4.types.stts, MP4.STTS),\n MP4.box(MP4.types.stsc, MP4.STSC),\n MP4.box(MP4.types.stsz, MP4.STSZ),\n MP4.box(MP4.types.stco, MP4.STCO),\n );\n }\n\n static avc1(track) {\n let sps: number[] = [];\n let pps: number[] = [];\n let i;\n let data;\n let len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xff);\n sps.push(len & 0xff);\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xff);\n pps.push(len & 0xff);\n\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n const avcc = MP4.box(\n MP4.types.avcC,\n new Uint8Array(\n [\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xe0 | track.sps.length, // 3bit reserved (111) + numOfSequenceParameterSets\n ]\n .concat(sps)\n .concat([\n track.pps.length, // numOfPictureParameterSets\n ])\n .concat(pps),\n ),\n ); // \"PPS\"\n const width = track.width;\n const height = track.height;\n const hSpacing = track.pixelRatio[0];\n const vSpacing = track.pixelRatio[1];\n\n return MP4.box(\n MP4.types.avc1,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00, // pre_defined\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n (width >> 8) & 0xff,\n width & 0xff, // width\n (height >> 8) & 0xff,\n height & 0xff, // height\n 0x00,\n 0x48,\n 0x00,\n 0x00, // horizresolution\n 0x00,\n 0x48,\n 0x00,\n 0x00, // vertresolution\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // frame_count\n 0x12,\n 0x64,\n 0x61,\n 0x69,\n 0x6c, // dailymotion/hls.js\n 0x79,\n 0x6d,\n 0x6f,\n 0x74,\n 0x69,\n 0x6f,\n 0x6e,\n 0x2f,\n 0x68,\n 0x6c,\n 0x73,\n 0x2e,\n 0x6a,\n 0x73,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // compressorname\n 0x00,\n 0x18, // depth = 24\n 0x11,\n 0x11,\n ]), // pre_defined = -1\n avcc,\n MP4.box(\n MP4.types.btrt,\n new Uint8Array([\n 0x00,\n 0x1c,\n 0x9c,\n 0x80, // bufferSizeDB\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0, // maxBitrate\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0,\n ]),\n ), // avgBitrate\n MP4.box(\n MP4.types.pasp,\n new Uint8Array([\n hSpacing >> 24, // hSpacing\n (hSpacing >> 16) & 0xff,\n (hSpacing >> 8) & 0xff,\n hSpacing & 0xff,\n vSpacing >> 24, // vSpacing\n (vSpacing >> 16) & 0xff,\n (vSpacing >> 8) & 0xff,\n vSpacing & 0xff,\n ]),\n ),\n );\n }\n\n static esds(track) {\n const configlen = track.config.length;\n return new Uint8Array(\n [\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17 + configlen, // length\n 0x00,\n 0x01, // es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f + configlen, // length\n 0x40, // codec : mpeg4_audio\n 0x15, // stream_type\n 0x00,\n 0x00,\n 0x00, // buffer_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // maxBitrate\n 0x00,\n 0x00,\n 0x00,\n 0x00, // avgBitrate\n\n 0x05, // descriptor_type\n ]\n .concat([configlen])\n .concat(track.config)\n .concat([0x06, 0x01, 0x02]),\n ); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static audioStsd(track) {\n const samplerate = track.samplerate;\n return new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n track.channelCount, // channelcount\n 0x00,\n 0x10, // sampleSize:16bits\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved2\n (samplerate >> 8) & 0xff,\n samplerate & 0xff, //\n 0x00,\n 0x00,\n ]);\n }\n\n static mp4a(track) {\n return MP4.box(\n MP4.types.mp4a,\n MP4.audioStsd(track),\n MP4.box(MP4.types.esds, MP4.esds(track)),\n );\n }\n\n static mp3(track) {\n return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));\n }\n\n static ac3(track) {\n return MP4.box(\n MP4.types['ac-3'],\n MP4.audioStsd(track),\n MP4.box(MP4.types.dac3, track.config),\n );\n }\n\n static stsd(track) {\n if (track.type === 'audio') {\n if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n if (track.segmentCodec === 'ac3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));\n }\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd(track) {\n const id = track.id;\n const duration = track.duration * track.timescale;\n const width = track.width;\n const height = track.height;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.tkhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x07, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (id >> 24) & 0xff,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00, // layer\n 0x00,\n 0x00, // alternate_group\n 0x00,\n 0x00, // non-audio track volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n (width >> 8) & 0xff,\n width & 0xff,\n 0x00,\n 0x00, // width\n (height >> 8) & 0xff,\n height & 0xff,\n 0x00,\n 0x00, // height\n ]),\n );\n }\n\n static traf(track, baseMediaDecodeTime) {\n const sampleDependencyTable = MP4.sdtp(track);\n const id = track.id;\n const upperWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime / (UINT32_MAX + 1),\n );\n const lowerWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime % (UINT32_MAX + 1),\n );\n return MP4.box(\n MP4.types.traf,\n MP4.box(\n MP4.types.tfhd,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n ]),\n ),\n MP4.box(\n MP4.types.tfdt,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n upperWordBaseMediaDecodeTime >> 24,\n (upperWordBaseMediaDecodeTime >> 16) & 0xff,\n (upperWordBaseMediaDecodeTime >> 8) & 0xff,\n upperWordBaseMediaDecodeTime & 0xff,\n lowerWordBaseMediaDecodeTime >> 24,\n (lowerWordBaseMediaDecodeTime >> 16) & 0xff,\n (lowerWordBaseMediaDecodeTime >> 8) & 0xff,\n lowerWordBaseMediaDecodeTime & 0xff,\n ]),\n ),\n MP4.trun(\n track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8,\n ), // mdat header\n sampleDependencyTable,\n );\n }\n\n /**\n * Generate a track box.\n * @param track a track definition\n */\n static trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex(track) {\n const id = track.id;\n return MP4.box(\n MP4.types.trex,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x01, // default_sample_description_index\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_duration\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_size\n 0x00,\n 0x01,\n 0x00,\n 0x01, // default_sample_flags\n ]),\n );\n }\n\n static trun(track, offset) {\n const samples = track.samples || [];\n const len = samples.length;\n const arraylen = 12 + 16 * len;\n const array = new Uint8Array(arraylen);\n let i;\n let sample;\n let duration;\n let size;\n let flags;\n let cts;\n offset += 8 + arraylen;\n array.set(\n [\n track.type === 'video' ? 0x01 : 0x00, // version 1 for video with signed-int sample_composition_time_offset\n 0x00,\n 0x0f,\n 0x01, // flags\n (len >>> 24) & 0xff,\n (len >>> 16) & 0xff,\n (len >>> 8) & 0xff,\n len & 0xff, // sample_count\n (offset >>> 24) & 0xff,\n (offset >>> 16) & 0xff,\n (offset >>> 8) & 0xff,\n offset & 0xff, // data_offset\n ],\n 0,\n );\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set(\n [\n (duration >>> 24) & 0xff,\n (duration >>> 16) & 0xff,\n (duration >>> 8) & 0xff,\n duration & 0xff, // sample_duration\n (size >>> 24) & 0xff,\n (size >>> 16) & 0xff,\n (size >>> 8) & 0xff,\n size & 0xff, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & (0xf0 << 8),\n flags.degradPrio & 0x0f, // sample_flags\n (cts >>> 24) & 0xff,\n (cts >>> 16) & 0xff,\n (cts >>> 8) & 0xff,\n cts & 0xff, // sample_composition_time_offset\n ],\n 12 + 16 * i,\n );\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n const movie = MP4.moov(tracks);\n const result = appendUint8Array(MP4.FTYP, movie);\n return result;\n }\n}\n\nexport default MP4;\n","const MPEG_TS_CLOCK_FREQ_HZ = 90000;\n\nexport type RationalTimestamp = {\n baseTime: number; // ticks\n timescale: number; // ticks per second\n};\n\nexport function toTimescaleFromBase(\n baseTime: number,\n destScale: number,\n srcBase: number = 1,\n round: boolean = false,\n): number {\n const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\n\nexport function toTimescaleFromScale(\n baseTime: number,\n destScale: number,\n srcScale: number = 1,\n round: boolean = false,\n): number {\n return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);\n}\n\nexport function toMsFromMpegTsClock(\n baseTime: number,\n round: boolean = false,\n): number {\n return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\n\nexport function toMpegTsClockFromTimescale(\n baseTime: number,\n srcScale: number = 1,\n): number {\n return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n}\n","import AAC from './aac-helper';\nimport MP4 from './mp4-generator';\nimport type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport {\n InitSegmentData,\n Remuxer,\n RemuxerResult,\n RemuxedMetadata,\n RemuxedTrack,\n RemuxedUserdata,\n} from '../types/remuxer';\nimport { PlaylistLevelType } from '../types/loader';\nimport {\n RationalTimestamp,\n toMsFromMpegTsClock,\n} from '../utils/timescale-conversion';\nimport type {\n AudioSample,\n VideoSample,\n DemuxedAudioTrack,\n DemuxedVideoTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n} from '../types/demuxer';\nimport type { TrackSet } from '../types/track';\nimport type { SourceBufferName } from '../types/buffer';\nimport type { Fragment } from '../loader/fragment';\nimport type { HlsConfig } from '../config';\n\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds\nconst AAC_SAMPLES_PER_FRAME = 1024;\nconst MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;\nconst AC3_SAMPLES_PER_FRAME = 1536;\n\nlet chromeVersion: number | null = null;\nlet safariWebkitVersion: number | null = null;\n\nexport default class MP4Remuxer implements Remuxer {\n private observer: HlsEventEmitter;\n private config: HlsConfig;\n private typeSupported: any;\n private ISGenerated: boolean = false;\n private _initPTS: RationalTimestamp | null = null;\n private _initDTS: RationalTimestamp | null = null;\n private nextAvcDts: number | null = null;\n private nextAudioPts: number | null = null;\n private videoSampleDuration: number | null = null;\n private isAudioContiguous: boolean = false;\n private isVideoContiguous: boolean = false;\n private videoTrackConfig?: {\n width?: number;\n height?: number;\n pixelRatio?: [number, number];\n };\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported,\n vendor = '',\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n if (safariWebkitVersion === null) {\n const result = navigator.userAgent.match(/Safari\\/(\\d+)/i);\n safariWebkitVersion = result ? parseInt(result[1]) : 0;\n }\n }\n\n destroy() {\n // @ts-ignore\n this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;\n }\n\n resetTimeStamp(defaultTimeStamp: RationalTimestamp | null) {\n logger.log('[mp4-remuxer]: initPTS & initDTS reset');\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetNextTimestamp() {\n logger.log('[mp4-remuxer]: reset next timestamp');\n this.isVideoContiguous = false;\n this.isAudioContiguous = false;\n }\n\n resetInitSegment() {\n logger.log('[mp4-remuxer]: ISGenerated flag reset');\n this.ISGenerated = false;\n this.videoTrackConfig = undefined;\n }\n\n getVideoStartPts(videoSamples) {\n let rolloverDetected = false;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n const delta = sample.pts - minPTS;\n if (delta < -4294967296) {\n // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n return normalizePts(minPTS, sample.pts);\n } else if (delta > 0) {\n return minPTS;\n } else {\n return sample.pts;\n }\n }, videoSamples[0].pts);\n if (rolloverDetected) {\n logger.debug('PTS rollover detected');\n }\n return startPTS;\n }\n\n remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedVideoTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n flush: boolean,\n playlistType: PlaylistLevelType,\n ): RemuxerResult {\n let video: RemuxedTrack | undefined;\n let audio: RemuxedTrack | undefined;\n let initSegment: InitSegmentData | undefined;\n let text: RemuxedUserdata | undefined;\n let id3: RemuxedMetadata | undefined;\n let independent: boolean | undefined;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n\n // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.\n // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the \"pid\"\n // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.\n // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),\n // then we can remux one track without waiting for the other.\n const hasAudio = audioTrack.pid > -1;\n const hasVideo = videoTrack.pid > -1;\n const length = videoTrack.samples.length;\n const enoughAudioSamples = audioTrack.samples.length > 0;\n const enoughVideoSamples = (flush && length > 0) || length > 1;\n const canRemuxAvc =\n ((!hasAudio || enoughAudioSamples) &&\n (!hasVideo || enoughVideoSamples)) ||\n this.ISGenerated ||\n flush;\n\n if (canRemuxAvc) {\n if (this.ISGenerated) {\n const config = this.videoTrackConfig;\n if (\n config &&\n (videoTrack.width !== config.width ||\n videoTrack.height !== config.height ||\n videoTrack.pixelRatio?.[0] !== config.pixelRatio?.[0] ||\n videoTrack.pixelRatio?.[1] !== config.pixelRatio?.[1])\n ) {\n this.resetInitSegment();\n }\n } else {\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset,\n );\n }\n\n const isVideoContiguous = this.isVideoContiguous;\n let firstKeyFrameIndex = -1;\n let firstKeyFramePTS;\n\n if (enoughVideoSamples) {\n firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);\n if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {\n independent = true;\n if (firstKeyFrameIndex > 0) {\n logger.warn(\n `[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`,\n );\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);\n videoTrack.dropped += firstKeyFrameIndex;\n videoTimeOffset +=\n (videoTrack.samples[0].pts - startPTS) /\n videoTrack.inputTimeScale;\n firstKeyFramePTS = videoTimeOffset;\n } else if (firstKeyFrameIndex === -1) {\n logger.warn(\n `[mp4-remuxer]: No keyframe found out of ${length} video samples`,\n );\n independent = false;\n }\n }\n }\n\n if (this.ISGenerated) {\n if (enoughAudioSamples && enoughVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n const tsDelta =\n normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;\n const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\n }\n\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.\n if (enoughAudioSamples) {\n // if initSegment was generated without audio samples, regenerate it again\n if (!audioTrack.samplerate) {\n logger.warn(\n '[mp4-remuxer]: regenerate InitSegment as audio detected',\n );\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset,\n );\n }\n audio = this.remuxAudio(\n audioTrack,\n audioTimeOffset,\n this.isAudioContiguous,\n accurateTimeOffset,\n hasVideo ||\n enoughVideoSamples ||\n playlistType === PlaylistLevelType.AUDIO\n ? videoTimeOffset\n : undefined,\n );\n if (enoughVideoSamples) {\n const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.inputTimeScale) {\n logger.warn(\n '[mp4-remuxer]: regenerate InitSegment as video detected',\n );\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset,\n );\n }\n video = this.remuxVideo(\n videoTrack,\n videoTimeOffset,\n isVideoContiguous,\n audioTrackLength,\n );\n }\n } else if (enoughVideoSamples) {\n video = this.remuxVideo(\n videoTrack,\n videoTimeOffset,\n isVideoContiguous,\n 0,\n );\n }\n if (video) {\n video.firstKeyFrame = firstKeyFrameIndex;\n video.independent = firstKeyFrameIndex !== -1;\n video.firstKeyFramePTS = firstKeyFramePTS;\n }\n }\n }\n\n // Allow ID3 and text to remux, even if more audio/video samples are required\n if (this.ISGenerated && this._initPTS && this._initDTS) {\n if (id3Track.samples.length) {\n id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n this._initPTS,\n this._initDTS,\n );\n }\n\n if (textTrack.samples.length) {\n text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n this._initPTS,\n );\n }\n }\n\n return {\n audio,\n video,\n initSegment,\n independent,\n text,\n id3,\n };\n }\n\n generateIS(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedVideoTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n ): InitSegmentData | undefined {\n const audioSamples = audioTrack.samples;\n const videoSamples = videoTrack.samples;\n const typeSupported = this.typeSupported;\n const tracks: TrackSet = {};\n const _initPTS = this._initPTS;\n let computePTSDTS = !_initPTS || accurateTimeOffset;\n let container = 'audio/mp4';\n let initPTS: number | undefined;\n let initDTS: number | undefined;\n let timescale: number | undefined;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n switch (audioTrack.segmentCodec) {\n case 'mp3':\n if (typeSupported.mpeg) {\n // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) {\n // Firefox\n audioTrack.codec = 'mp3';\n }\n break;\n\n case 'ac3':\n audioTrack.codec = 'ac-3';\n break;\n }\n tracks.audio = {\n id: 'audio',\n container: container,\n codec: audioTrack.codec,\n initSegment:\n audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg\n ? new Uint8Array(0)\n : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount,\n },\n };\n if (computePTSDTS) {\n timescale = audioTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS =\n audioSamples[0].pts - Math.round(timescale * timeOffset);\n } else {\n computePTSDTS = false;\n }\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n videoTrack.timescale = videoTrack.inputTimeScale;\n tracks.video = {\n id: 'main',\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height,\n },\n };\n if (computePTSDTS) {\n timescale = videoTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n const startPTS = this.getVideoStartPts(videoSamples);\n const startOffset = Math.round(timescale * timeOffset);\n initDTS = Math.min(\n initDTS as number,\n normalizePts(videoSamples[0].dts, startPTS) - startOffset,\n );\n initPTS = Math.min(initPTS as number, startPTS - startOffset);\n } else {\n computePTSDTS = false;\n }\n }\n this.videoTrackConfig = {\n width: videoTrack.width,\n height: videoTrack.height,\n pixelRatio: videoTrack.pixelRatio,\n };\n }\n\n if (Object.keys(tracks).length) {\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = {\n baseTime: initPTS as number,\n timescale: timescale as number,\n };\n this._initDTS = {\n baseTime: initDTS as number,\n timescale: timescale as number,\n };\n } else {\n initPTS = timescale = undefined;\n }\n\n return {\n tracks,\n initPTS,\n timescale,\n };\n }\n }\n\n remuxVideo(\n track: DemuxedVideoTrack,\n timeOffset: number,\n contiguous: boolean,\n audioTrackLength: number,\n ): RemuxedTrack | undefined {\n const timeScale: number = track.inputTimeScale;\n const inputSamples: Array<VideoSample> = track.samples;\n const outputSamples: Array<Mp4Sample> = [];\n const nbSamples = inputSamples.length;\n const initPTS = this._initPTS as RationalTimestamp;\n let nextAvcDts = this.nextAvcDts;\n let offset = 8;\n let mp4SampleDuration = this.videoSampleDuration;\n let firstDTS;\n let lastDTS;\n let minPTS: number = Number.POSITIVE_INFINITY;\n let maxPTS: number = Number.NEGATIVE_INFINITY;\n let sortSamples = false;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n if (!contiguous || nextAvcDts === null) {\n const pts = timeOffset * timeScale;\n const cts =\n inputSamples[0].pts -\n normalizePts(inputSamples[0].dts, inputSamples[0].pts);\n if (\n chromeVersion &&\n nextAvcDts !== null &&\n Math.abs(pts - cts - nextAvcDts) < 15000\n ) {\n // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome\n contiguous = true;\n } else {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\n }\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n const initTime = (initPTS.baseTime * timeScale) / initPTS.timescale;\n for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);\n sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || deltapts;\n });\n }\n\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[inputSamples.length - 1].dts;\n\n // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n const inputDuration = lastDTS - firstDTS;\n const averageSampleDuration = inputDuration\n ? Math.round(inputDuration / (nbSamples - 1))\n : mp4SampleDuration || track.inputTimeScale / 30;\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n delta,\n true,\n )} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(\n 3,\n )}`,\n );\n } else {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n -delta,\n true,\n )} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(\n 3,\n )}`,\n );\n }\n if (\n !foundOverlap ||\n nextAvcDts >= inputSamples[0].pts ||\n chromeVersion\n ) {\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n if (foundHole) {\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n } else {\n for (let i = 0; i < inputSamples.length; i++) {\n if (inputSamples[i].dts > firstPTS) {\n break;\n }\n inputSamples[i].dts -= delta;\n inputSamples[i].pts -= delta;\n }\n }\n logger.log(\n `Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(\n firstPTS,\n true,\n )}/${toMsFromMpegTsClock(\n firstDTS,\n true,\n )}, delta: ${toMsFromMpegTsClock(delta, true)} ms`,\n );\n }\n }\n }\n\n firstDTS = Math.max(0, firstDTS);\n\n let nbNalu = 0;\n let naluLen = 0;\n let dtsStep = firstDTS;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // ensure sample monotonic DTS\n if (sample.dts < dtsStep) {\n sample.dts = dtsStep;\n dtsStep += (averageSampleDuration / 4) | 0 || 1;\n } else {\n dtsStep = sample.dts;\n }\n\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n const mdatSize = naluLen + 4 * nbNalu + 8;\n let mdat;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating video mdat ${mdatSize}`,\n });\n return;\n }\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n let stretchedLastFrame = false;\n let minDtsDelta = Number.POSITIVE_INFINITY;\n let minPtsDelta = Number.POSITIVE_INFINITY;\n let maxDtsDelta = Number.NEGATIVE_INFINITY;\n let maxPtsDelta = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < nbSamples; i++) {\n const VideoSample = inputSamples[i];\n const VideoSampleUnits = VideoSample.units;\n let mp4SampleLength = 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {\n const unit = VideoSampleUnits[j];\n const unitData = unit.data;\n const unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n let ptsDelta;\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;\n ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;\n } else {\n const config = this.config;\n const lastFrameDuration =\n i > 0\n ? VideoSample.dts - inputSamples[i - 1].dts\n : averageSampleDuration;\n ptsDelta =\n i > 0\n ? VideoSample.pts - inputSamples[i - 1].pts\n : averageSampleDuration;\n if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n const gapTolerance = Math.floor(config.maxBufferHole * timeScale);\n const deltaToFrameEnd =\n (audioTrackLength\n ? minPTS + audioTrackLength * timeScale\n : this.nextAudioPts) - VideoSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n } else {\n stretchedLastFrame = true;\n }\n logger.log(\n `[mp4-remuxer]: It is approximately ${\n deltaToFrameEnd / 90\n } ms to the next segment; using duration ${\n mp4SampleDuration / 90\n } ms for the last video frame.`,\n );\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n const compositionTimeOffset = Math.round(\n VideoSample.pts - VideoSample.dts,\n );\n minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);\n maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);\n minPtsDelta = Math.min(minPtsDelta, ptsDelta);\n maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);\n\n outputSamples.push(\n new Mp4Sample(\n VideoSample.key,\n mp4SampleDuration,\n mp4SampleLength,\n compositionTimeOffset,\n ),\n );\n }\n\n if (outputSamples.length) {\n if (chromeVersion) {\n if (chromeVersion < 70) {\n // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n const flags = outputSamples[0].flags;\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n } else if (safariWebkitVersion) {\n // Fix for \"CNN special report, with CC\" in test-streams (Safari browser only)\n // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.\n if (\n maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta &&\n averageSampleDuration / maxDtsDelta < 0.025 &&\n outputSamples[0].cts === 0\n ) {\n logger.warn(\n 'Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.',\n );\n let dts = firstDTS;\n for (let i = 0, len = outputSamples.length; i < len; i++) {\n const nextDts = dts + outputSamples[i].duration;\n const pts = dts + outputSamples[i].cts;\n if (i < len - 1) {\n const nextPts = nextDts + outputSamples[i + 1].cts;\n outputSamples[i].duration = nextPts - pts;\n } else {\n outputSamples[i].duration = i\n ? outputSamples[i - 1].duration\n : averageSampleDuration;\n }\n outputSamples[i].cts = 0;\n dts = nextDts;\n }\n }\n }\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n mp4SampleDuration =\n stretchedLastFrame || !mp4SampleDuration\n ? averageSampleDuration\n : mp4SampleDuration;\n this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;\n this.videoSampleDuration = mp4SampleDuration;\n this.isVideoContiguous = true;\n const moof = MP4.moof(\n track.sequenceNumber++,\n firstDTS,\n Object.assign({}, track, {\n samples: outputSamples,\n }),\n );\n const type: SourceBufferName = 'video';\n const data = {\n data1: moof,\n data2: mdat,\n startPTS: minPTS / timeScale,\n endPTS: (maxPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: (nextAvcDts as number) / timeScale,\n type,\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: track.dropped,\n };\n track.samples = [];\n track.dropped = 0;\n return data;\n }\n\n getSamplesPerFrame(track: DemuxedAudioTrack) {\n switch (track.segmentCodec) {\n case 'mp3':\n return MPEG_AUDIO_SAMPLE_PER_FRAME;\n case 'ac3':\n return AC3_SAMPLES_PER_FRAME;\n default:\n return AAC_SAMPLES_PER_FRAME;\n }\n }\n\n remuxAudio(\n track: DemuxedAudioTrack,\n timeOffset: number,\n contiguous: boolean,\n accurateTimeOffset: boolean,\n videoTimeOffset?: number,\n ): RemuxedTrack | undefined {\n const inputTimeScale: number = track.inputTimeScale;\n const mp4timeScale: number = track.samplerate\n ? track.samplerate\n : inputTimeScale;\n const scaleFactor: number = inputTimeScale / mp4timeScale;\n const mp4SampleDuration: number = this.getSamplesPerFrame(track);\n const inputSampleDuration: number = mp4SampleDuration * scaleFactor;\n const initPTS = this._initPTS as RationalTimestamp;\n const rawMPEG: boolean =\n track.segmentCodec === 'mp3' && this.typeSupported.mpeg;\n const outputSamples: Array<Mp4Sample> = [];\n const alignedWithVideo = videoTimeOffset !== undefined;\n\n let inputSamples: Array<AudioSample> = track.samples;\n let offset: number = rawMPEG ? 0 : 8;\n let nextAudioPts: number = this.nextAudioPts || -1;\n\n // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n const timeOffsetMpegTS = timeOffset * inputTimeScale;\n const initTime = (initPTS.baseTime * inputTimeScale) / initPTS.timescale;\n this.isAudioContiguous = contiguous =\n contiguous ||\n ((inputSamples.length &&\n nextAudioPts > 0 &&\n ((accurateTimeOffset &&\n Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000) ||\n Math.abs(\n normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) -\n nextAudioPts,\n ) <\n 20 * inputSampleDuration)) as boolean);\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);\n });\n\n if (!contiguous || nextAudioPts < 0) {\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter((sample) => sample.pts >= 0);\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (!inputSamples.length) {\n return;\n }\n\n if (videoTimeOffset === 0) {\n // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence\n nextAudioPts = 0;\n } else if (accurateTimeOffset && !alignedWithVideo) {\n // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS\n nextAudioPts = Math.max(0, timeOffsetMpegTS);\n } else {\n // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n }\n }\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n if (track.segmentCodec === 'aac') {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {\n // First, let's see how far off this frame is from where we expect it to be\n const sample = inputSamples[i];\n const pts = sample.pts;\n const delta = pts - nextPts;\n const duration = Math.abs((1000 * delta) / inputTimeScale);\n\n // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync\n if (\n delta <= -maxAudioFramesDrift * inputSampleDuration &&\n alignedWithVideo\n ) {\n if (i === 0) {\n logger.warn(\n `Audio frame @ ${(pts / inputTimeScale).toFixed(\n 3,\n )}s overlaps nextAudioPts by ${Math.round(\n (1000 * delta) / inputTimeScale,\n )} ms.`,\n );\n this.nextAudioPts = nextAudioPts = nextPts = pts;\n }\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n // 4: remuxing with video (videoTimeOffset !== undefined)\n else if (\n delta >= maxAudioFramesDrift * inputSampleDuration &&\n duration < MAX_SILENT_FRAME_DURATION &&\n alignedWithVideo\n ) {\n let missing = Math.round(delta / inputSampleDuration);\n // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from\n // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.\n nextPts = pts - missing * inputSampleDuration;\n if (nextPts < 0) {\n missing--;\n nextPts += inputSampleDuration;\n }\n if (i === 0) {\n this.nextAudioPts = nextAudioPts = nextPts;\n }\n logger.warn(\n `[mp4-remuxer]: Injecting ${missing} audio frame @ ${(\n nextPts / inputTimeScale\n ).toFixed(3)}s due to ${Math.round(\n (1000 * delta) / inputTimeScale,\n )} ms gap.`,\n );\n for (let j = 0; j < missing; j++) {\n const newStamp = Math.max(nextPts as number, 0);\n let fillFrame = AAC.getSilentFrame(\n track.manifestCodec || track.codec,\n track.channelCount,\n );\n if (!fillFrame) {\n logger.log(\n '[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.',\n );\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, {\n unit: fillFrame,\n pts: newStamp,\n });\n nextPts += inputSampleDuration;\n i++;\n }\n }\n sample.pts = nextPts;\n nextPts += inputSampleDuration;\n }\n }\n let firstPTS: number | null = null;\n let lastPTS: number | null = null;\n let mdat: any;\n let mdatSize: number = 0;\n let sampleLength: number = inputSamples.length;\n while (sampleLength--) {\n mdatSize += inputSamples[sampleLength].unit.byteLength;\n }\n for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) {\n const audioSample = inputSamples[j];\n const unit = audioSample.unit;\n let pts = audioSample.pts;\n if (lastPTS !== null) {\n // If we have more than one sample, set the duration of the sample to the \"real\" duration; the PTS diff with\n // the previous sample\n const prevSample = outputSamples[j - 1];\n prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n if (contiguous && track.segmentCodec === 'aac') {\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n // remember first PTS of our audioSamples\n firstPTS = pts;\n if (mdatSize > 0) {\n /* concatenate the audio data and construct the mdat in place\n (need 8 more bytes to fill length and mdat type) */\n mdatSize += offset;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating audio mdat ${mdatSize}`,\n });\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n }\n mdat.set(unit, offset);\n const unitLen = unit.byteLength;\n offset += unitLen;\n // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG\n // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration\n // becomes the PTS diff with the previous sample\n outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));\n lastPTS = pts;\n }\n\n // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones\n const nbSamples = outputSamples.length;\n if (!nbSamples) {\n return;\n }\n\n // The next audio sample PTS should be equal to last sample PTS + duration\n const lastSample = outputSamples[outputSamples.length - 1];\n this.nextAudioPts = nextAudioPts =\n lastPTS! + scaleFactor * lastSample.duration;\n\n // Set the track samples from inputSamples to outputSamples before remuxing\n const moof = rawMPEG\n ? new Uint8Array(0)\n : MP4.moof(\n track.sequenceNumber++,\n firstPTS! / scaleFactor,\n Object.assign({}, track, { samples: outputSamples }),\n );\n\n // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared\n track.samples = [];\n const start = firstPTS! / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const type: SourceBufferName = 'audio';\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type,\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples,\n };\n\n this.isAudioContiguous = true;\n return audioData;\n }\n\n remuxEmptyAudio(\n track: DemuxedAudioTrack,\n timeOffset: number,\n contiguous: boolean,\n videoData: Fragment,\n ): RemuxedTrack | undefined {\n const inputTimeScale: number = track.inputTimeScale;\n const mp4timeScale: number = track.samplerate\n ? track.samplerate\n : inputTimeScale;\n const scaleFactor: number = inputTimeScale / mp4timeScale;\n const nextAudioPts: number | null = this.nextAudioPts;\n // sync with video's timestamp\n const initDTS = this._initDTS as RationalTimestamp;\n const init90kHz = (initDTS.baseTime * 90000) / initDTS.timescale;\n const startDTS: number =\n (nextAudioPts !== null\n ? nextAudioPts\n : videoData.startDTS * inputTimeScale) + init90kHz;\n const endDTS: number = videoData.endDTS * inputTimeScale + init90kHz;\n // one sample's duration value\n const frameDuration: number = scaleFactor * AAC_SAMPLES_PER_FRAME;\n // samples count of this segment's duration\n const nbSamples: number = Math.ceil((endDTS - startDTS) / frameDuration);\n // silent frame\n const silentFrame: Uint8Array | undefined = AAC.getSilentFrame(\n track.manifestCodec || track.codec,\n track.channelCount,\n );\n\n logger.warn('[mp4-remuxer]: remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace(\n '[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec',\n );\n return;\n }\n\n const samples: Array<any> = [];\n for (let i = 0; i < nbSamples; i++) {\n const stamp = startDTS + i * frameDuration;\n samples.push({ unit: silentFrame, pts: stamp, dts: stamp });\n }\n track.samples = samples;\n\n return this.remuxAudio(track, timeOffset, contiguous, false);\n }\n}\n\nexport function normalizePts(value: number, reference: number | null): number {\n let offset;\n if (reference === null) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n}\n\nfunction findKeyframeIndex(samples: Array<VideoSample>): number {\n for (let i = 0; i < samples.length; i++) {\n if (samples[i].key) {\n return i;\n }\n }\n return -1;\n}\n\nexport function flushTextTrackMetadataCueSamples(\n track: DemuxedMetadataTrack,\n timeOffset: number,\n initPTS: RationalTimestamp,\n initDTS: RationalTimestamp,\n): RemuxedMetadata | undefined {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts =\n normalizePts(\n sample.pts - (initPTS.baseTime * inputTimeScale) / initPTS.timescale,\n timeOffset * inputTimeScale,\n ) / inputTimeScale;\n sample.dts =\n normalizePts(\n sample.dts - (initDTS.baseTime * inputTimeScale) / initDTS.timescale,\n timeOffset * inputTimeScale,\n ) / inputTimeScale;\n }\n const samples = track.samples;\n track.samples = [];\n return {\n samples,\n };\n}\n\nexport function flushTextTrackUserdataCueSamples(\n track: DemuxedUserdataTrack,\n timeOffset: number,\n initPTS: RationalTimestamp,\n): RemuxedUserdata | undefined {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts =\n normalizePts(\n sample.pts - (initPTS.baseTime * inputTimeScale) / initPTS.timescale,\n timeOffset * inputTimeScale,\n ) / inputTimeScale;\n }\n track.samples.sort((a, b) => a.pts - b.pts);\n const samples = track.samples;\n track.samples = [];\n return {\n samples,\n };\n}\n\ntype Mp4SampleFlags = {\n isLeading: 0;\n isDependedOn: 0;\n hasRedundancy: 0;\n degradPrio: 0;\n dependsOn: 1 | 2;\n isNonSync: 0 | 1;\n};\n\nclass Mp4Sample {\n public size: number;\n public duration: number;\n public cts: number;\n public flags: Mp4SampleFlags;\n\n constructor(\n isKeyframe: boolean,\n duration: number,\n size: number,\n cts: number,\n ) {\n this.duration = duration;\n this.size = size;\n this.cts = cts;\n this.flags = {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: isKeyframe ? 2 : 1,\n isNonSync: isKeyframe ? 0 : 1,\n };\n }\n}\n","import type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from './audio/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer, { TypeSupported } from '../demux/tsdemuxer';\nimport MP3Demuxer from './audio/mp3demuxer';\nimport { AC3Demuxer } from './audio/ac3-demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\nimport { logger } from '../utils/logger';\nimport type { Demuxer, DemuxerResult, KeyData } from '../types/demuxer';\nimport type { Remuxer } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\nimport type { HlsConfig } from '../config';\nimport type { DecryptData } from '../loader/level-key';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\nimport { optionalSelf } from '../utils/global';\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = self.performance.now.bind(self.performance);\n} catch (err) {\n logger.debug('Unable to use Performance API on this environment');\n now = optionalSelf?.Date.now;\n}\n\ntype MuxConfig =\n | { demux: typeof MP4Demuxer; remux: typeof PassThroughRemuxer }\n | { demux: typeof TSDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof AC3Demuxer; remux: typeof MP4Remuxer }\n | { demux: typeof AACDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof MP3Demuxer; remux: typeof MP4Remuxer };\n\nconst muxConfig: MuxConfig[] = [\n { demux: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer },\n];\n\nif (__USE_M2TS_ADVANCED_CODECS__) {\n muxConfig.splice(2, 0, { demux: AC3Demuxer, remux: MP4Remuxer });\n}\n\nexport default class Transmuxer {\n public async: boolean = false;\n private observer: HlsEventEmitter;\n private typeSupported: TypeSupported;\n private config: HlsConfig;\n private vendor: string;\n private id: PlaylistLevelType;\n private demuxer?: Demuxer;\n private remuxer?: Remuxer;\n private decrypter?: Decrypter;\n private probe!: Function;\n private decryptionPromise: Promise<TransmuxerResult> | null = null;\n private transmuxConfig!: TransmuxConfig;\n private currentTransmuxState!: TransmuxState;\n\n constructor(\n observer: HlsEventEmitter,\n typeSupported: TypeSupported,\n config: HlsConfig,\n vendor: string,\n id: PlaylistLevelType,\n ) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n this.id = id;\n }\n\n configure(transmuxConfig: TransmuxConfig) {\n this.transmuxConfig = transmuxConfig;\n if (this.decrypter) {\n this.decrypter.reset();\n }\n }\n\n push(\n data: ArrayBuffer,\n decryptdata: DecryptData | null,\n chunkMeta: ChunkMetadata,\n state?: TransmuxState,\n ): TransmuxerResult | Promise<TransmuxerResult> {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n\n let uintData: Uint8Array = new Uint8Array(data);\n const { currentTransmuxState, transmuxConfig } = this;\n if (state) {\n this.currentTransmuxState = state;\n }\n\n const {\n contiguous,\n discontinuity,\n trackSwitch,\n accurateTimeOffset,\n timeOffset,\n initSegmentChange,\n } = state || currentTransmuxState;\n const {\n audioCodec,\n videoCodec,\n defaultInitPts,\n duration,\n initSegmentData,\n } = transmuxConfig;\n\n const keyData = getEncryptionType(uintData, decryptdata);\n if (keyData && keyData.method === 'AES-128') {\n const decrypter = this.getDecrypter();\n // Software decryption is synchronous; webCrypto is not\n if (decrypter.isSync()) {\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n let decryptedData = decrypter.softwareDecrypt(\n uintData,\n keyData.key.buffer,\n keyData.iv.buffer,\n );\n // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress\n const loadingParts = chunkMeta.part > -1;\n if (loadingParts) {\n decryptedData = decrypter.flush();\n }\n if (!decryptedData) {\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n uintData = new Uint8Array(decryptedData);\n } else {\n this.decryptionPromise = decrypter\n .webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer)\n .then((decryptedData): TransmuxerResult => {\n // Calling push here is important; if flush() is called while this is still resolving, this ensures that\n // the decrypted data has been transmuxed\n const result = this.push(\n decryptedData,\n null,\n chunkMeta,\n ) as TransmuxerResult;\n this.decryptionPromise = null;\n return result;\n });\n return this.decryptionPromise!;\n }\n }\n\n const resetMuxers = this.needsProbing(discontinuity, trackSwitch);\n if (resetMuxers) {\n const error = this.configureTransmuxer(uintData);\n if (error) {\n logger.warn(`[transmuxer] ${error.message}`);\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n reason: error.message,\n });\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n }\n\n if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {\n this.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n duration,\n decryptdata,\n );\n }\n\n if (discontinuity || initSegmentChange || resetMuxers) {\n this.resetInitialTimestamp(defaultInitPts);\n }\n\n if (!contiguous) {\n this.resetContiguity();\n }\n\n const result = this.transmux(\n uintData,\n keyData,\n timeOffset,\n accurateTimeOffset,\n chunkMeta,\n );\n const currentState = this.currentTransmuxState;\n\n currentState.contiguous = true;\n currentState.discontinuity = false;\n currentState.trackSwitch = false;\n\n stats.executeEnd = now();\n return result;\n }\n\n // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)\n flush(\n chunkMeta: ChunkMetadata,\n ): TransmuxerResult[] | Promise<TransmuxerResult[]> {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n\n const { decrypter, currentTransmuxState, decryptionPromise } = this;\n\n if (decryptionPromise) {\n // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore\n // only flushing is required for async decryption\n return decryptionPromise.then(() => {\n return this.flush(chunkMeta);\n });\n }\n\n const transmuxResults: TransmuxerResult[] = [];\n const { timeOffset } = currentTransmuxState;\n if (decrypter) {\n // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults\n // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,\n // or for progressive downloads with small segments)\n const decryptedData = decrypter.flush();\n if (decryptedData) {\n // Push always returns a TransmuxerResult if decryptdata is null\n transmuxResults.push(\n this.push(decryptedData, null, chunkMeta) as TransmuxerResult,\n );\n }\n }\n\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n // If probing failed, then Hls.js has been given content its not able to handle\n stats.executeEnd = now();\n return [emptyResult(chunkMeta)];\n }\n\n const demuxResultOrPromise = demuxer.flush(timeOffset);\n if (isPromise(demuxResultOrPromise)) {\n // Decrypt final SAMPLE-AES samples\n return demuxResultOrPromise.then((demuxResult) => {\n this.flushRemux(transmuxResults, demuxResult, chunkMeta);\n return transmuxResults;\n });\n }\n\n this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);\n return transmuxResults;\n }\n\n private flushRemux(\n transmuxResults: TransmuxerResult[],\n demuxResult: DemuxerResult,\n chunkMeta: ChunkMetadata,\n ) {\n const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult;\n const { accurateTimeOffset, timeOffset } = this.currentTransmuxState;\n logger.log(\n `[transmuxer.ts]: Flushed fragment ${chunkMeta.sn}${\n chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : ''\n } of level ${chunkMeta.level}`,\n );\n const remuxResult = this.remuxer!.remux(\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n timeOffset,\n accurateTimeOffset,\n true,\n this.id,\n );\n transmuxResults.push({\n remuxResult,\n chunkMeta,\n });\n\n chunkMeta.transmuxing.executeEnd = now();\n }\n\n resetInitialTimestamp(defaultInitPts: RationalTimestamp | null) {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetTimeStamp(defaultInitPts);\n remuxer.resetTimeStamp(defaultInitPts);\n }\n\n resetContiguity() {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetContiguity();\n remuxer.resetNextTimestamp();\n }\n\n resetInitSegment(\n initSegmentData: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n decryptdata: DecryptData | null,\n ) {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n trackDuration,\n );\n remuxer.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n decryptdata,\n );\n }\n\n destroy(): void {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = undefined;\n }\n if (this.remuxer) {\n this.remuxer.destroy();\n this.remuxer = undefined;\n }\n }\n\n private transmux(\n data: Uint8Array,\n keyData: KeyData | null,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n ): TransmuxerResult | Promise<TransmuxerResult> {\n let result: TransmuxerResult | Promise<TransmuxerResult>;\n if (keyData && keyData.method === 'SAMPLE-AES') {\n result = this.transmuxSampleAes(\n data,\n keyData,\n timeOffset,\n accurateTimeOffset,\n chunkMeta,\n );\n } else {\n result = this.transmuxUnencrypted(\n data,\n timeOffset,\n accurateTimeOffset,\n chunkMeta,\n );\n }\n return result;\n }\n\n private transmuxUnencrypted(\n data: Uint8Array,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n ): TransmuxerResult {\n const { audioTrack, videoTrack, id3Track, textTrack } = (\n this.demuxer as Demuxer\n ).demux(data, timeOffset, false, !this.config.progressive);\n const remuxResult = this.remuxer!.remux(\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n timeOffset,\n accurateTimeOffset,\n false,\n this.id,\n );\n return {\n remuxResult,\n chunkMeta,\n };\n }\n\n private transmuxSampleAes(\n data: Uint8Array,\n decryptData: KeyData,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n ): Promise<TransmuxerResult> {\n return (this.demuxer as Demuxer)\n .demuxSampleAes(data, decryptData, timeOffset)\n .then((demuxResult) => {\n const remuxResult = this.remuxer!.remux(\n demuxResult.audioTrack,\n demuxResult.videoTrack,\n demuxResult.id3Track,\n demuxResult.textTrack,\n timeOffset,\n accurateTimeOffset,\n false,\n this.id,\n );\n return {\n remuxResult,\n chunkMeta,\n };\n });\n }\n\n private configureTransmuxer(data: Uint8Array): void | Error {\n const { config, observer, typeSupported, vendor } = this;\n // probe for content type\n let mux;\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n if (muxConfig[i].demux?.probe(data)) {\n mux = muxConfig[i];\n break;\n }\n }\n if (!mux) {\n return new Error('Failed to find demuxer by probing fragment data');\n }\n // so let's check that current remuxer and demuxer are still valid\n const demuxer = this.demuxer;\n const remuxer = this.remuxer;\n const Remuxer: MuxConfig['remux'] = mux.remux;\n const Demuxer: MuxConfig['demux'] = mux.demux;\n if (!remuxer || !(remuxer instanceof Remuxer)) {\n this.remuxer = new Remuxer(observer, config, typeSupported, vendor);\n }\n if (!demuxer || !(demuxer instanceof Demuxer)) {\n this.demuxer = new Demuxer(observer, config, typeSupported);\n this.probe = Demuxer.probe;\n }\n }\n\n private needsProbing(discontinuity: boolean, trackSwitch: boolean): boolean {\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;\n }\n\n private getDecrypter(): Decrypter {\n let decrypter = this.decrypter;\n if (!decrypter) {\n decrypter = this.decrypter = new Decrypter(this.config);\n }\n return decrypter;\n }\n}\n\nfunction getEncryptionType(\n data: Uint8Array,\n decryptData: DecryptData | null,\n): KeyData | null {\n let encryptionType: KeyData | null = null;\n if (\n data.byteLength > 0 &&\n decryptData?.key != null &&\n decryptData.iv !== null &&\n decryptData.method != null\n ) {\n encryptionType = decryptData as KeyData;\n }\n return encryptionType;\n}\n\nconst emptyResult = (chunkMeta): TransmuxerResult => ({\n remuxResult: {},\n chunkMeta,\n});\n\nexport function isPromise<T>(p: Promise<T> | any): p is Promise<T> {\n return 'then' in p && p.then instanceof Function;\n}\n\nexport class TransmuxConfig {\n public audioCodec?: string;\n public videoCodec?: string;\n public initSegmentData?: Uint8Array;\n public duration: number;\n public defaultInitPts: RationalTimestamp | null;\n\n constructor(\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n initSegmentData: Uint8Array | undefined,\n duration: number,\n defaultInitPts?: RationalTimestamp,\n ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.initSegmentData = initSegmentData;\n this.duration = duration;\n this.defaultInitPts = defaultInitPts || null;\n }\n}\n\nexport class TransmuxState {\n public discontinuity: boolean;\n public contiguous: boolean;\n public accurateTimeOffset: boolean;\n public trackSwitch: boolean;\n public timeOffset: number;\n public initSegmentChange: boolean;\n\n constructor(\n discontinuity: boolean,\n contiguous: boolean,\n accurateTimeOffset: boolean,\n trackSwitch: boolean,\n timeOffset: number,\n initSegmentChange: boolean,\n ) {\n this.discontinuity = discontinuity;\n this.contiguous = contiguous;\n this.accurateTimeOffset = accurateTimeOffset;\n this.trackSwitch = trackSwitch;\n this.timeOffset = timeOffset;\n this.initSegmentChange = initSegmentChange;\n }\n}\n","import {\n flushTextTrackMetadataCueSamples,\n flushTextTrackUserdataCueSamples,\n} from './mp4-remuxer';\nimport {\n InitData,\n InitDataTrack,\n patchEncyptionData,\n} from '../utils/mp4-tools';\nimport {\n getDuration,\n getStartDTS,\n offsetStartDTS,\n parseInitSegment,\n} from '../utils/mp4-tools';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport { logger } from '../utils/logger';\nimport { getCodecCompatibleName } from '../utils/codecs';\nimport type { TrackSet } from '../types/track';\nimport type {\n InitSegmentData,\n RemuxedTrack,\n Remuxer,\n RemuxerResult,\n} from '../types/remuxer';\nimport type {\n DemuxedAudioTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n PassthroughTrack,\n} from '../types/demuxer';\nimport type { DecryptData } from '../loader/level-key';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nclass PassThroughRemuxer implements Remuxer {\n private emitInitSegment: boolean = false;\n private audioCodec?: string;\n private videoCodec?: string;\n private initData?: InitData;\n private initPTS: RationalTimestamp | null = null;\n private initTracks?: TrackSet;\n private lastEndTime: number | null = null;\n\n public destroy() {}\n\n public resetTimeStamp(defaultInitPTS: RationalTimestamp | null) {\n this.initPTS = defaultInitPTS;\n this.lastEndTime = null;\n }\n\n public resetNextTimestamp() {\n this.lastEndTime = null;\n }\n\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n decryptdata: DecryptData | null,\n ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));\n this.emitInitSegment = true;\n }\n\n private generateInitSegment(initSegment: Uint8Array | undefined): void {\n let { audioCodec, videoCodec } = this;\n if (!initSegment?.byteLength) {\n this.initTracks = undefined;\n this.initData = undefined;\n return;\n }\n const initData = (this.initData = parseInitSegment(initSegment));\n\n // Get codec from initSegment or fallback to default\n if (initData.audio) {\n audioCodec = getParsedTrackCodec(\n initData.audio,\n ElementaryStreamTypes.AUDIO,\n );\n }\n\n if (initData.video) {\n videoCodec = getParsedTrackCodec(\n initData.video,\n ElementaryStreamTypes.VIDEO,\n );\n }\n\n const tracks: TrackSet = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = {\n container: 'video/mp4',\n codec: audioCodec + ',' + videoCodec,\n initSegment,\n id: 'main',\n };\n } else if (initData.audio) {\n tracks.audio = {\n container: 'audio/mp4',\n codec: audioCodec,\n initSegment,\n id: 'audio',\n };\n } else if (initData.video) {\n tracks.video = {\n container: 'video/mp4',\n codec: videoCodec,\n initSegment,\n id: 'main',\n };\n } else {\n logger.warn(\n '[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.',\n );\n }\n this.initTracks = tracks;\n }\n\n public remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: PassthroughTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n ): RemuxerResult {\n let { initPTS, lastEndTime } = this;\n const result: RemuxerResult = {\n audio: undefined,\n video: undefined,\n text: textTrack,\n id3: id3Track,\n initSegment: undefined,\n };\n\n // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the\n // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update\n // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.\n if (!Number.isFinite(lastEndTime!)) {\n lastEndTime = this.lastEndTime = timeOffset || 0;\n }\n\n // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only\n // audio or video (or both); adding it to video was an arbitrary choice.\n const data = videoTrack.samples;\n if (!data?.length) {\n return result;\n }\n\n const initSegment: InitSegmentData = {\n initPTS: undefined,\n timescale: 1,\n };\n let initData = this.initData;\n if (!initData?.length) {\n this.generateInitSegment(data);\n initData = this.initData;\n }\n if (!initData?.length) {\n // We can't remux if the initSegment could not be generated\n logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');\n return result;\n }\n if (this.emitInitSegment) {\n initSegment.tracks = this.initTracks as TrackSet;\n this.emitInitSegment = false;\n }\n\n const duration = getDuration(data, initData);\n const startDTS = getStartDTS(initData, data);\n const decodeTime = startDTS === null ? timeOffset : startDTS;\n if (\n isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) ||\n (initSegment.timescale !== initPTS.timescale && accurateTimeOffset)\n ) {\n initSegment.initPTS = decodeTime - timeOffset;\n if (initPTS && initPTS.timescale === 1) {\n logger.warn(\n `Adjusting initPTS by ${initSegment.initPTS - initPTS.baseTime}`,\n );\n }\n this.initPTS = initPTS = {\n baseTime: initSegment.initPTS,\n timescale: 1,\n };\n }\n\n const startTime = audioTrack\n ? decodeTime - initPTS.baseTime / initPTS.timescale\n : (lastEndTime as number);\n const endTime = startTime + duration;\n offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);\n\n if (duration > 0) {\n this.lastEndTime = endTime;\n } else {\n logger.warn('Duration parsed from mp4 should be greater than zero');\n this.resetNextTimestamp();\n }\n\n const hasAudio = !!initData.audio;\n const hasVideo = !!initData.video;\n\n let type: any = '';\n if (hasAudio) {\n type += 'audio';\n }\n\n if (hasVideo) {\n type += 'video';\n }\n\n const track: RemuxedTrack = {\n data1: data,\n startPTS: startTime,\n startDTS: startTime,\n endPTS: endTime,\n endDTS: endTime,\n type,\n hasAudio,\n hasVideo,\n nb: 1,\n dropped: 0,\n };\n\n result.audio = track.type === 'audio' ? track : undefined;\n result.video = track.type !== 'audio' ? track : undefined;\n result.initSegment = initSegment;\n result.id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n initPTS,\n initPTS,\n );\n\n if (textTrack.samples.length) {\n result.text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n initPTS,\n );\n }\n\n return result;\n }\n}\n\nfunction isInvalidInitPts(\n initPTS: RationalTimestamp | null,\n startDTS: number,\n timeOffset: number,\n duration: number,\n): initPTS is null {\n if (initPTS === null) {\n return true;\n }\n // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second\n const minDuration = Math.max(duration, 1);\n const startTime = startDTS - initPTS.baseTime / initPTS.timescale;\n return Math.abs(startTime - timeOffset) > minDuration;\n}\n\nfunction getParsedTrackCodec(\n track: InitDataTrack,\n type: ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO,\n): string {\n const parsedCodec = track?.codec;\n if (parsedCodec && parsedCodec.length > 4) {\n return parsedCodec;\n }\n if (type === ElementaryStreamTypes.AUDIO) {\n if (\n parsedCodec === 'ec-3' ||\n parsedCodec === 'ac-3' ||\n parsedCodec === 'alac'\n ) {\n return parsedCodec;\n }\n if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {\n // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity\n const preferManagedMediaSource = false;\n return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);\n }\n const result = 'mp4a.40.5';\n logger.info(\n `Parsed audio codec \"${parsedCodec}\" or audio object type not handled. Using \"${result}\"`,\n );\n return result;\n }\n // Provide defaults based on codec type\n // This allows for some playback of some fmp4 playlists without CODECS defined in manifest\n logger.warn(`Unhandled video codec \"${parsedCodec}\"`);\n if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {\n return 'hvc1.1.6.L120.90';\n }\n if (parsedCodec === 'av01') {\n return 'av01.0.04M.08';\n }\n return 'avc1.42e01e';\n}\nexport default PassThroughRemuxer;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import Transmuxer, { isPromise } from '../demux/transmuxer';\nimport { Events } from '../events';\nimport { ILogFunction, enableLogs, logger } from '../utils/logger';\nimport { EventEmitter } from 'eventemitter3';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport type { RemuxedTrack, RemuxerResult } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\n\nif (typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {\n startWorker(self);\n}\n\nfunction startWorker(self) {\n const observer = new EventEmitter();\n const forwardMessage = (ev, data) => {\n self.postMessage({ event: ev, data: data });\n };\n\n // forward events to main thread\n observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n observer.on(Events.ERROR, forwardMessage);\n\n // forward logger events to main thread\n const forwardWorkerLogs = () => {\n for (const logFn in logger) {\n const func: ILogFunction = (message?) => {\n forwardMessage('workerLog', {\n logType: logFn,\n message,\n });\n };\n\n logger[logFn] = func;\n }\n };\n\n self.addEventListener('message', (ev) => {\n const data = ev.data;\n switch (data.cmd) {\n case 'init': {\n const config = JSON.parse(data.config);\n self.transmuxer = new Transmuxer(\n observer,\n data.typeSupported,\n config,\n '',\n data.id,\n );\n enableLogs(config.debug, data.id);\n forwardWorkerLogs();\n forwardMessage('init', null);\n break;\n }\n case 'configure': {\n self.transmuxer.configure(data.config);\n break;\n }\n case 'demux': {\n const transmuxResult: TransmuxerResult | Promise<TransmuxerResult> =\n self.transmuxer.push(\n data.data,\n data.decryptdata,\n data.chunkMeta,\n data.state,\n );\n if (isPromise(transmuxResult)) {\n self.transmuxer.async = true;\n transmuxResult\n .then((data) => {\n emitTransmuxComplete(self, data);\n })\n .catch((error) => {\n forwardMessage(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta: data.chunkMeta,\n fatal: false,\n error,\n err: error,\n reason: `transmuxer-worker push error`,\n });\n });\n } else {\n self.transmuxer.async = false;\n emitTransmuxComplete(self, transmuxResult);\n }\n break;\n }\n case 'flush': {\n const id = data.chunkMeta;\n let transmuxResult = self.transmuxer.flush(id);\n const asyncFlush = isPromise(transmuxResult);\n if (asyncFlush || self.transmuxer.async) {\n if (!isPromise(transmuxResult)) {\n transmuxResult = Promise.resolve(transmuxResult);\n }\n transmuxResult\n .then((results: Array<TransmuxerResult>) => {\n handleFlushResult(self, results as Array<TransmuxerResult>, id);\n })\n .catch((error) => {\n forwardMessage(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta: data.chunkMeta,\n fatal: false,\n error,\n err: error,\n reason: `transmuxer-worker flush error`,\n });\n });\n } else {\n handleFlushResult(\n self,\n transmuxResult as Array<TransmuxerResult>,\n id,\n );\n }\n break;\n }\n default:\n break;\n }\n });\n}\n\nfunction emitTransmuxComplete(\n self: any,\n transmuxResult: TransmuxerResult,\n): boolean {\n if (isEmptyResult(transmuxResult.remuxResult)) {\n return false;\n }\n const transferable: Array<ArrayBuffer> = [];\n const { audio, video } = transmuxResult.remuxResult;\n if (audio) {\n addToTransferable(transferable, audio);\n }\n if (video) {\n addToTransferable(transferable, video);\n }\n self.postMessage(\n { event: 'transmuxComplete', data: transmuxResult },\n transferable,\n );\n return true;\n}\n\n// Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)\n// in order to minimize message passing overhead\nfunction addToTransferable(\n transferable: Array<ArrayBuffer>,\n track: RemuxedTrack,\n) {\n if (track.data1) {\n transferable.push(track.data1.buffer);\n }\n if (track.data2) {\n transferable.push(track.data2.buffer);\n }\n}\n\nfunction handleFlushResult(\n self: any,\n results: Array<TransmuxerResult>,\n chunkMeta: ChunkMetadata,\n) {\n const parsed = results.reduce(\n (parsed, result) => emitTransmuxComplete(self, result) || parsed,\n false,\n );\n if (!parsed) {\n // Emit at least one \"transmuxComplete\" message even if media is not found to update stream-controller state to PARSING\n self.postMessage({ event: 'transmuxComplete', data: results[0] });\n }\n self.postMessage({ event: 'flush', data: chunkMeta });\n}\n\nfunction isEmptyResult(remuxResult: RemuxerResult) {\n return (\n !remuxResult.audio &&\n !remuxResult.video &&\n !remuxResult.text &&\n !remuxResult.id3 &&\n !remuxResult.initSegment\n );\n}\n","import {\n WorkerContext,\n hasUMDWorker,\n injectWorker,\n loadWorker,\n} from './inject-worker';\nimport { Events } from '../events';\nimport Transmuxer, {\n TransmuxConfig,\n TransmuxState,\n isPromise,\n} from '../demux/transmuxer';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { EventEmitter } from 'eventemitter3';\nimport { Fragment, Part } from '../loader/fragment';\nimport type { ChunkMetadata, TransmuxerResult } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { HlsEventEmitter, HlsListeners } from '../events';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { TypeSupported } from './tsdemuxer';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nexport default class TransmuxerInterface {\n public error: Error | null = null;\n private hls: Hls;\n private id: PlaylistLevelType;\n private observer: HlsEventEmitter;\n private frag: Fragment | null = null;\n private part: Part | null = null;\n private useWorker: boolean;\n private workerContext: WorkerContext | null = null;\n private onwmsg?: (\n event: MessageEvent<{ event: string; data?: any } | null>,\n ) => void;\n private transmuxer: Transmuxer | null = null;\n private onTransmuxComplete: (transmuxResult: TransmuxerResult) => void;\n private onFlush: (chunkMeta: ChunkMetadata) => void;\n\n constructor(\n hls: Hls,\n id: PlaylistLevelType,\n onTransmuxComplete: (transmuxResult: TransmuxerResult) => void,\n onFlush: (chunkMeta: ChunkMetadata) => void,\n ) {\n const config = hls.config;\n this.hls = hls;\n this.id = id;\n this.useWorker = !!config.enableWorker;\n this.onTransmuxComplete = onTransmuxComplete;\n this.onFlush = onFlush;\n\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n if (ev === Events.ERROR) {\n this.error = data.error;\n }\n this.hls.trigger(ev, data);\n };\n\n // forward events to main thread\n this.observer = new EventEmitter() as HlsEventEmitter;\n this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n this.observer.on(Events.ERROR, forwardMessage);\n\n const MediaSource = getMediaSource(config.preferManagedMediaSource) || {\n isTypeSupported: () => false,\n };\n const m2tsTypeSupported: TypeSupported = {\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n ac3: __USE_M2TS_ADVANCED_CODECS__\n ? MediaSource.isTypeSupported('audio/mp4; codecs=\"ac-3\"')\n : false,\n };\n\n if (this.useWorker && typeof Worker !== 'undefined') {\n const canCreateWorker = config.workerPath || hasUMDWorker();\n if (canCreateWorker) {\n try {\n if (config.workerPath) {\n logger.log(`loading Web Worker ${config.workerPath} for \"${id}\"`);\n this.workerContext = loadWorker(config.workerPath);\n } else {\n logger.log(`injecting Web Worker for \"${id}\"`);\n this.workerContext = injectWorker();\n }\n this.onwmsg = (event) => this.onWorkerMessage(event);\n const { worker } = this.workerContext;\n worker.addEventListener('message', this.onwmsg);\n worker.onerror = (event) => {\n const error = new Error(\n `${event.message} (${event.filename}:${event.lineno})`,\n );\n config.enableWorker = false;\n logger.warn(`Error in \"${id}\" Web Worker, fallback to inline`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal: false,\n event: 'demuxerWorker',\n error,\n });\n };\n worker.postMessage({\n cmd: 'init',\n typeSupported: m2tsTypeSupported,\n vendor: '',\n id: id,\n config: JSON.stringify(config),\n });\n } catch (err) {\n logger.warn(\n `Error setting up \"${id}\" Web Worker, fallback to inline`,\n err,\n );\n this.resetWorker();\n this.error = null;\n this.transmuxer = new Transmuxer(\n this.observer,\n m2tsTypeSupported,\n config,\n '',\n id,\n );\n }\n return;\n }\n }\n\n this.transmuxer = new Transmuxer(\n this.observer,\n m2tsTypeSupported,\n config,\n '',\n id,\n );\n }\n\n resetWorker() {\n if (this.workerContext) {\n const { worker, objectURL } = this.workerContext;\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n worker.removeEventListener('message', this.onwmsg as any);\n worker.onerror = null;\n worker.terminate();\n this.workerContext = null;\n }\n }\n\n destroy() {\n if (this.workerContext) {\n this.resetWorker();\n this.onwmsg = undefined;\n } else {\n const transmuxer = this.transmuxer;\n if (transmuxer) {\n transmuxer.destroy();\n this.transmuxer = null;\n }\n }\n const observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n }\n this.frag = null;\n // @ts-ignore\n this.observer = null;\n // @ts-ignore\n this.hls = null;\n }\n\n push(\n data: ArrayBuffer,\n initSegmentData: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n frag: Fragment,\n part: Part | null,\n duration: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n defaultInitPTS?: RationalTimestamp,\n ) {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer } = this;\n const timeOffset = part ? part.start : frag.start;\n // TODO: push \"clear-lead\" decrypt data for unencrypted fragments in streams with encrypted ones\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n\n const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);\n const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);\n const snDiff = lastFrag ? chunkMeta.sn - (lastFrag.sn as number) : -1;\n const partDiff = this.part ? chunkMeta.part - this.part.index : -1;\n const progressive =\n snDiff === 0 &&\n chunkMeta.id > 1 &&\n chunkMeta.id === lastFrag?.stats.chunkCount;\n const contiguous =\n !trackSwitch &&\n (snDiff === 1 ||\n (snDiff === 0 && (partDiff === 1 || (progressive && partDiff <= 0))));\n const now = self.performance.now();\n\n if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {\n frag.stats.parsing.start = now;\n }\n if (part && (partDiff || !contiguous)) {\n part.stats.parsing.start = now;\n }\n const initSegmentChange = !(\n lastFrag && frag.initSegment?.url === lastFrag.initSegment?.url\n );\n const state = new TransmuxState(\n discontinuity,\n contiguous,\n accurateTimeOffset,\n trackSwitch,\n timeOffset,\n initSegmentChange,\n );\n if (!contiguous || discontinuity || initSegmentChange) {\n logger.log(`[transmuxer-interface, ${frag.type}]: Starting new transmux session for sn: ${chunkMeta.sn} p: ${chunkMeta.part} level: ${chunkMeta.level} id: ${chunkMeta.id}\n discontinuity: ${discontinuity}\n trackSwitch: ${trackSwitch}\n contiguous: ${contiguous}\n accurateTimeOffset: ${accurateTimeOffset}\n timeOffset: ${timeOffset}\n initSegmentChange: ${initSegmentChange}`);\n const config = new TransmuxConfig(\n audioCodec,\n videoCodec,\n initSegmentData,\n duration,\n defaultInitPTS,\n );\n this.configureTransmuxer(config);\n }\n\n this.frag = frag;\n this.part = part;\n\n // Frags with sn of 'initSegment' are not transmuxed\n if (this.workerContext) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n this.workerContext.worker.postMessage(\n {\n cmd: 'demux',\n data,\n decryptdata,\n chunkMeta,\n state,\n },\n data instanceof ArrayBuffer ? [data] : [],\n );\n } else if (transmuxer) {\n const transmuxResult = transmuxer.push(\n data,\n decryptdata,\n chunkMeta,\n state,\n );\n if (isPromise(transmuxResult)) {\n transmuxer.async = true;\n transmuxResult\n .then((data) => {\n this.handleTransmuxComplete(data);\n })\n .catch((error) => {\n this.transmuxerError(\n error,\n chunkMeta,\n 'transmuxer-interface push error',\n );\n });\n } else {\n transmuxer.async = false;\n this.handleTransmuxComplete(transmuxResult as TransmuxerResult);\n }\n }\n }\n\n flush(chunkMeta: ChunkMetadata) {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer } = this;\n if (this.workerContext) {\n 1;\n this.workerContext.worker.postMessage({\n cmd: 'flush',\n chunkMeta,\n });\n } else if (transmuxer) {\n let transmuxResult = transmuxer.flush(chunkMeta);\n const asyncFlush = isPromise(transmuxResult);\n if (asyncFlush || transmuxer.async) {\n if (!isPromise(transmuxResult)) {\n transmuxResult = Promise.resolve(transmuxResult);\n }\n transmuxResult\n .then((data) => {\n this.handleFlushResult(data, chunkMeta);\n })\n .catch((error) => {\n this.transmuxerError(\n error,\n chunkMeta,\n 'transmuxer-interface flush error',\n );\n });\n } else {\n this.handleFlushResult(\n transmuxResult as Array<TransmuxerResult>,\n chunkMeta,\n );\n }\n }\n }\n\n private transmuxerError(\n error: Error,\n chunkMeta: ChunkMetadata,\n reason: string,\n ) {\n if (!this.hls) {\n return;\n }\n this.error = error;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta,\n frag: this.frag || undefined,\n fatal: false,\n error,\n err: error,\n reason,\n });\n }\n\n private handleFlushResult(\n results: Array<TransmuxerResult>,\n chunkMeta: ChunkMetadata,\n ) {\n results.forEach((result) => {\n this.handleTransmuxComplete(result);\n });\n this.onFlush(chunkMeta);\n }\n\n private onWorkerMessage(\n event: MessageEvent<{ event: string; data?: any } | null>,\n ) {\n const data = event.data;\n if (!data?.event) {\n logger.warn(\n `worker message received with no ${data ? 'event name' : 'data'}`,\n );\n return;\n }\n const hls = this.hls;\n if (!this.hls) {\n return;\n }\n switch (data.event) {\n case 'init': {\n const objectURL = this.workerContext?.objectURL;\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n break;\n }\n\n case 'transmuxComplete': {\n this.handleTransmuxComplete(data.data);\n break;\n }\n\n case 'flush': {\n this.onFlush(data.data);\n break;\n }\n\n // pass logs from the worker thread to the main logger\n case 'workerLog':\n if (logger[data.data.logType]) {\n logger[data.data.logType](data.data.message);\n }\n break;\n\n default: {\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event as keyof HlsListeners, data.data);\n break;\n }\n }\n }\n\n private configureTransmuxer(config: TransmuxConfig) {\n const { transmuxer } = this;\n if (this.workerContext) {\n this.workerContext.worker.postMessage({\n cmd: 'configure',\n config,\n });\n } else if (transmuxer) {\n transmuxer.configure(config);\n }\n }\n\n private handleTransmuxComplete(result: TransmuxerResult) {\n result.chunkMeta.transmuxing.end = self.performance.now();\n this.onTransmuxComplete(result);\n }\n}\n","// ensure the worker ends up in the bundle\n// If the worker should not be included this gets aliased to empty.js\nimport './transmuxer-worker';\n\nexport function hasUMDWorker(): boolean {\n return typeof __HLS_WORKER_BUNDLE__ === 'function';\n}\n\nexport type WorkerContext = {\n worker: Worker;\n objectURL?: string;\n scriptURL?: string;\n};\n\nexport function injectWorker(): WorkerContext {\n const blob = new self.Blob(\n [\n `var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`,\n ],\n {\n type: 'text/javascript',\n },\n );\n const objectURL = self.URL.createObjectURL(blob);\n const worker = new self.Worker(objectURL);\n\n return {\n worker,\n objectURL,\n };\n}\n\nexport function loadWorker(path: string): WorkerContext {\n const scriptURL = new self.URL(path, self.location.href).href;\n const worker = new self.Worker(scriptURL);\n\n return {\n worker,\n scriptURL,\n };\n}\n","import type { 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 !mediaAttributesIdentical(\n trackList1[i].attrs as MediaAttributes,\n trackList2[i].attrs,\n )\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function mediaAttributesIdentical(\n attrs1: MediaAttributes,\n attrs2: MediaAttributes,\n customAttributes?: string[],\n): boolean {\n // Media options with the same rendition ID must be bit identical\n const stableRenditionId = attrs1['STABLE-RENDITION-ID'];\n if (stableRenditionId && !customAttributes) {\n return stableRenditionId === attrs2['STABLE-RENDITION-ID'];\n }\n // When rendition ID is not present, compare attributes\n return !(\n customAttributes || [\n 'LANGUAGE',\n 'NAME',\n 'CHARACTERISTICS',\n 'AUTOSELECT',\n 'DEFAULT',\n 'FORCED',\n 'ASSOC-LANGUAGE',\n ]\n ).some(\n (subtitleAttribute) =>\n attrs1[subtitleAttribute] !== attrs2[subtitleAttribute],\n );\n}\n\nexport function subtitleTrackMatchesTextTrack(\n subtitleTrack: Pick<MediaPlaylist, 'name' | 'lang' | 'attrs'>,\n textTrack: TextTrack,\n) {\n return (\n textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() &&\n (!textTrack.language ||\n textTrack.language.toLowerCase() ===\n (subtitleTrack.lang || '').toLowerCase())\n );\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 { mediaAttributesIdentical } from '../utils/media-option-attributes';\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 BufferFlushingData,\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 flushing: boolean = false;\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 super.onHandlerDestroying();\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_FLUSHING, this.onBufferFlushing, 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_FLUSHING, this.onBufferFlushing, 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 const { levels, trackId } = this;\n this.log('RetryDate reached, switch back to IDLE state');\n this.resetStartWhenNotLoaded(levels?.[trackId] || null);\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 // 1. if video not attached AND\n // start fragment already requested OR start frag prefetch not enabled\n // 2. if tracks or track not loaded and selected\n // then 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 (\n (!media && (this.startFragRequested || !config.startFragPrefetch)) ||\n !levels?.[trackId]\n ) {\n return;\n }\n\n const levelInfo = levels[trackId];\n\n const trackDetails = levelInfo.details;\n if (\n !trackDetails ||\n (trackDetails.live && this.levelLastLoaded !== levelInfo) ||\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 const fragments = trackDetails.fragments;\n const start = fragments[0].start;\n let targetBufferTime = this.flushing\n ? this.getLoadPosition()\n : bufferInfo.end;\n\n if (switchingTrack && media) {\n const pos = this.getLoadPosition();\n // STABLE\n if (\n bufferedTrack &&\n !mediaAttributesIdentical(switchingTrack.attrs, bufferedTrack.attrs)\n ) {\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 // if buffer length is less than maxBufLen, or near the end, find a fragment to load\n if (\n bufferLen >= maxBufLen &&\n !switchingTrack &&\n targetBufferTime < fragments[fragments.length - 1].start\n ) {\n return;\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 this.bufferFlushed = this.flushing = false;\n super.onMediaDetaching();\n }\n\n onAudioTracksUpdated(\n event: Events.AUDIO_TRACKS_UPDATED,\n { audioTracks }: AudioTracksUpdatedData,\n ) {\n // Reset tranxmuxer is essential for large context switches (Content Steering)\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 this.flushAudioIfNeeded(data);\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 = this.flushing = 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 `Audio track ${trackId} loaded [${newDetails.startSN},${\n newDetails.endSN\n }]${\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(\n newDetails,\n track.details,\n this.levelLastLoaded?.details,\n );\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = track;\n\n // compute start position if we are aligned with the main playlist\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(this.mainDetails || newDetails, 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_APPEND_ERROR:\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (!data.parent || data.parent !== 'audio') {\n return;\n }\n if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {\n this.resetLoadingState();\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 onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { type }: BufferFlushingData,\n ) {\n if (type !== ElementaryStreamTypes.VIDEO) {\n this.flushing = true;\n }\n }\n\n private onBufferFlushed(\n event: Events.BUFFER_FLUSHED,\n { type }: BufferFlushedData,\n ) {\n if (type !== ElementaryStreamTypes.VIDEO) {\n this.flushing = false;\n this.bufferFlushed = true;\n if (this.state === State.ENDED) {\n this.state = State.IDLE;\n }\n const mediaBuffer = this.mediaBuffer || this.media;\n if (mediaBuffer) {\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);\n this.tick();\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(\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 // 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 currentLevel: Level,\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.id = 'audio';\n\n const variantAudioCodecs = currentLevel.audioCodec;\n this.log(\n `Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`,\n );\n // SourceBuffer will use track.levelCodec if defined\n if (variantAudioCodecs && variantAudioCodecs.split(',').length === 1) {\n track.levelCodec = variantAudioCodecs;\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.tickImmediate();\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 const mainDetails = this.mainDetails;\n if (\n mainDetails &&\n mainDetails.fragments[0].start !== track.details.fragments[0].start\n ) {\n alignMediaPlaylistByPDT(track.details, mainDetails);\n }\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, track, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n\n private flushAudioIfNeeded(switchingTrack: MediaPlaylist) {\n const { 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 bufferedTrack.name !== switchingTrack.name ||\n bufferedTrack.lang !== switchingTrack.lang)\n ) {\n this.log('Switching audio track : flushing all audio');\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n this.bufferedTrack = null;\n }\n }\n\n private completeAudioSwitch(switchingTrack: MediaPlaylist) {\n const { hls } = this;\n this.flushAudioIfNeeded(switchingTrack);\n this.bufferedTrack = switchingTrack;\n this.switchingTrack = null;\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, { ...switchingTrack });\n }\n}\nexport default AudioStreamController;\n","import BasePlaylistController from './base-playlist-controller';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { PlaylistContextType } from '../types/loader';\nimport { mediaAttributesIdentical } from '../utils/media-option-attributes';\nimport {\n audioMatchPredicate,\n findClosestLevelWithAudioGroup,\n findMatchingOption,\n matchesOption,\n} from '../utils/rendition-helper';\nimport type Hls from '../hls';\nimport type {\n AudioSelectionOption,\n MediaPlaylist,\n} from '../types/media-playlist';\nimport type { HlsUrlParameters } from '../types/level';\nimport type {\n ManifestParsedData,\n AudioTracksUpdatedData,\n ErrorData,\n LevelLoadingData,\n AudioTrackLoadedData,\n LevelSwitchingData,\n} from '../types/events';\n\nclass AudioTrackController extends BasePlaylistController {\n private tracks: MediaPlaylist[] = [];\n private groupIds: (string | undefined)[] | 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.tracksInGroup = [];\n this.groupIds = null;\n this.currentTrack = null;\n this.trackId = -1;\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 `Audio 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 if (!levelInfo) {\n return;\n }\n const audioGroups = levelInfo.audioGroups || null;\n const currentGroups = this.groupIds;\n let currentTrack = this.currentTrack;\n if (\n !audioGroups ||\n currentGroups?.length !== audioGroups?.length ||\n audioGroups?.some((groupId) => currentGroups?.indexOf(groupId) === -1)\n ) {\n this.groupIds = audioGroups;\n this.trackId = -1;\n this.currentTrack = null;\n\n const audioTracks = this.tracks.filter(\n (track): boolean =>\n !audioGroups || audioGroups.indexOf(track.groupId) !== -1,\n );\n if (audioTracks.length) {\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 // track.id should match hls.audioTracks index\n audioTracks.forEach((track, i) => {\n track.id = i;\n });\n } else if (!currentTrack && !this.tracksInGroup.length) {\n // Do not dispatch AUDIO_TRACKS_UPDATED when there were and are no tracks\n return;\n }\n this.tracksInGroup = audioTracks;\n\n // Find preferred track\n const audioPreference = this.hls.config.audioPreference;\n if (!currentTrack && audioPreference) {\n const groupIndex = findMatchingOption(\n audioPreference,\n audioTracks,\n audioMatchPredicate,\n );\n if (groupIndex > -1) {\n currentTrack = audioTracks[groupIndex];\n } else {\n const allIndex = findMatchingOption(audioPreference, this.tracks);\n currentTrack = this.tracks[allIndex];\n }\n }\n\n // Select initial track\n let trackId = this.findTrackId(currentTrack);\n if (trackId === -1 && currentTrack) {\n trackId = this.findTrackId(null);\n }\n\n // Dispatch events and load track if needed\n const audioTracksUpdated: AudioTracksUpdatedData = { audioTracks };\n this.log(\n `Updating audio tracks, ${\n audioTracks.length\n } track(s) found in group(s): ${audioGroups?.join(',')}`,\n );\n this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);\n\n const selectedTrackId = this.trackId;\n if (trackId !== -1 && selectedTrackId === -1) {\n this.setAudioTrack(trackId);\n } else if (audioTracks.length && selectedTrackId === -1) {\n const error = new Error(\n `No audio track selected for current audio group-ID(s): ${this.groupIds?.join(\n ',',\n )} 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 } else if (this.shouldReloadPlaylist(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 (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)\n ) {\n this.requestScheduled = -1;\n this.checkRetry(data);\n }\n }\n\n get allAudioTracks(): MediaPlaylist[] {\n return this.tracks;\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 public setAudioOption(\n audioOption: MediaPlaylist | AudioSelectionOption | undefined,\n ): MediaPlaylist | null {\n const hls = this.hls;\n hls.config.audioPreference = audioOption;\n if (audioOption) {\n const allAudioTracks = this.allAudioTracks;\n this.selectDefaultTrack = false;\n if (allAudioTracks.length) {\n // First see if current option matches (no switch op)\n const currentTrack = this.currentTrack;\n if (\n currentTrack &&\n matchesOption(audioOption, currentTrack, audioMatchPredicate)\n ) {\n return currentTrack;\n }\n // Find option in available tracks (tracksInGroup)\n const groupIndex = findMatchingOption(\n audioOption,\n this.tracksInGroup,\n audioMatchPredicate,\n );\n if (groupIndex > -1) {\n const track = this.tracksInGroup[groupIndex];\n this.setAudioTrack(groupIndex);\n return track;\n } else if (currentTrack) {\n // Find option in nearest level audio group\n let searchIndex = hls.loadLevel;\n if (searchIndex === -1) {\n searchIndex = hls.firstAutoLevel;\n }\n const switchIndex = findClosestLevelWithAudioGroup(\n audioOption,\n hls.levels,\n allAudioTracks,\n searchIndex,\n audioMatchPredicate,\n );\n if (switchIndex === -1) {\n // could not find matching variant\n return null;\n }\n // and switch level to acheive the audio group switch\n hls.nextLoadLevel = switchIndex;\n }\n if (audioOption.channels || audioOption.audioCodec) {\n // Could not find a match with codec / channels predicate\n // Find a match without channels or codec\n const withoutCodecAndChannelsMatch = findMatchingOption(\n audioOption,\n allAudioTracks,\n );\n if (withoutCodecAndChannelsMatch > -1) {\n return allAudioTracks[withoutCodecAndChannelsMatch];\n }\n }\n }\n }\n return null;\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 audio track id: ${newId}`);\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n this.selectDefaultTrack = false;\n const lastTrack = this.currentTrack;\n const track = tracks[newId];\n const trackLoaded = track.details && !track.details.live;\n if (newId === this.trackId && track === lastTrack && trackLoaded) {\n return;\n }\n this.log(\n `Switching to audio-track ${newId} \"${track.name}\" lang:${track.lang} group:${track.groupId} channels:${track.channels}`,\n );\n this.trackId = newId;\n this.currentTrack = track;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, { ...track });\n // Do not reload track unless live\n if (trackLoaded) {\n return;\n }\n const hlsUrlParameters = this.switchParams(\n track.url,\n lastTrack?.details,\n track.details,\n );\n this.loadPlaylist(hlsUrlParameters);\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 continue;\n }\n if (\n !currentTrack ||\n matchesOption(currentTrack, track, audioMatchPredicate)\n ) {\n return i;\n }\n }\n if (currentTrack) {\n const { name, lang, assocLang, characteristics, audioCodec, channels } =\n currentTrack;\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (\n matchesOption(\n { name, lang, assocLang, characteristics, audioCodec, channels },\n track,\n audioMatchPredicate,\n )\n ) {\n return i;\n }\n }\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (\n mediaAttributesIdentical(currentTrack.attrs, track.attrs, [\n 'LANGUAGE',\n 'ASSOC-LANGUAGE',\n 'CHARACTERISTICS',\n ])\n ) {\n return i;\n }\n }\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (\n mediaAttributesIdentical(currentTrack.attrs, track.attrs, [\n 'LANGUAGE',\n ])\n ) {\n return i;\n }\n }\n }\n return -1;\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n const audioTrack = this.currentTrack;\n if (this.shouldLoadPlaylist(audioTrack) && audioTrack) {\n super.loadPlaylist();\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 { Events } from '../events';\nimport { Bufferable, BufferHelper } from '../utils/buffer-helper';\nimport { findFragmentByPTS } from './fragment-finders';\nimport { alignMediaPlaylistByPDT } from '../utils/discontinuities';\nimport { addSliding } from '../utils/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 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 super.onHandlerDestroying();\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 this.fragBufferedComplete(frag, null);\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 (data.details === ErrorDetails.FRAG_GAP) {\n this.fragmentTracker.fragBuffered(frag, true);\n }\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 (this.levels && 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 { currentTrackId, levels } = this;\n const { details: newDetails, id: trackId } = data;\n if (!levels) {\n this.warn(`Subtitle tracks were reset while loading level ${trackId}`);\n return;\n }\n const track: Level = levels[trackId];\n if (trackId >= levels.length || !track) {\n return;\n }\n this.log(\n `Subtitle track ${trackId} loaded [${newDetails.startSN},${\n newDetails.endSN\n }]${\n newDetails.lastPartSn\n ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]`\n : ''\n },duration:${newDetails.totalduration}`,\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(\n newDetails,\n track.details,\n this.levelLastLoaded?.details,\n );\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 = track;\n\n if (trackId !== currentTrackId) {\n return;\n }\n\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(this.mainDetails || newDetails, 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?.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 (!track || !levels.length || !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 BasePlaylistController from './base-playlist-controller';\nimport { Events } from '../events';\nimport {\n clearCurrentCues,\n filterSubtitleTracks,\n} from '../utils/texttrack-utils';\nimport { PlaylistContextType } from '../types/loader';\nimport {\n mediaAttributesIdentical,\n subtitleTrackMatchesTextTrack,\n} from '../utils/media-option-attributes';\nimport { findMatchingOption, matchesOption } from '../utils/rendition-helper';\nimport type Hls from '../hls';\nimport type {\n MediaPlaylist,\n SubtitleSelectionOption,\n} from '../types/media-playlist';\nimport type { HlsUrlParameters } from '../types/level';\nimport type {\n ErrorData,\n LevelLoadingData,\n MediaAttachedData,\n SubtitleTracksUpdatedData,\n ManifestParsedData,\n TrackLoadedData,\n LevelSwitchingData,\n} from '../types/events';\n\nclass SubtitleTrackController extends BasePlaylistController {\n private media: HTMLMediaElement | null = null;\n private tracks: MediaPlaylist[] = [];\n private groupIds: (string | undefined)[] | null = null;\n private tracksInGroup: MediaPlaylist[] = [];\n private trackId: number = -1;\n private currentTrack: MediaPlaylist | null = null;\n private selectDefaultTrack: boolean = true;\n private queuedDefaultTrack: number = -1;\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.currentTrack = null;\n this.onTextTracksChanged = 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();\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.onTextTracksChanged,\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.groupIds = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.currentTrack = null;\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, groupId, details } = data;\n const trackInActiveGroup = this.tracksInGroup[id];\n\n if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {\n this.warn(\n `Subtitle 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 `Subtitle 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 if (!levelInfo) {\n return;\n }\n const subtitleGroups = levelInfo.subtitleGroups || null;\n const currentGroups = this.groupIds;\n let currentTrack = this.currentTrack;\n if (\n !subtitleGroups ||\n currentGroups?.length !== subtitleGroups?.length ||\n subtitleGroups?.some((groupId) => currentGroups?.indexOf(groupId) === -1)\n ) {\n this.groupIds = subtitleGroups;\n this.trackId = -1;\n this.currentTrack = null;\n\n const subtitleTracks = this.tracks.filter(\n (track): boolean =>\n !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1,\n );\n if (subtitleTracks.length) {\n // Disable selectDefaultTrack if there are no default tracks\n if (\n this.selectDefaultTrack &&\n !subtitleTracks.some((track) => track.default)\n ) {\n this.selectDefaultTrack = false;\n }\n // track.id should match hls.audioTracks index\n subtitleTracks.forEach((track, i) => {\n track.id = i;\n });\n } else if (!currentTrack && !this.tracksInGroup.length) {\n // Do not dispatch SUBTITLE_TRACKS_UPDATED when there were and are no tracks\n return;\n }\n this.tracksInGroup = subtitleTracks;\n\n // Find preferred track\n const subtitlePreference = this.hls.config.subtitlePreference;\n if (!currentTrack && subtitlePreference) {\n this.selectDefaultTrack = false;\n const groupIndex = findMatchingOption(\n subtitlePreference,\n subtitleTracks,\n );\n if (groupIndex > -1) {\n currentTrack = subtitleTracks[groupIndex];\n } else {\n const allIndex = findMatchingOption(subtitlePreference, this.tracks);\n currentTrack = this.tracks[allIndex];\n }\n }\n\n // Select initial track\n let trackId = this.findTrackId(currentTrack);\n if (trackId === -1 && currentTrack) {\n trackId = this.findTrackId(null);\n }\n\n // Dispatch events and load track if needed\n const subtitleTracksUpdated: SubtitleTracksUpdatedData = {\n subtitleTracks,\n };\n this.log(\n `Updating subtitle tracks, ${\n subtitleTracks.length\n } track(s) found in \"${subtitleGroups?.join(',')}\" group-id`,\n );\n this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);\n\n if (trackId !== -1 && this.trackId === -1) {\n this.setSubtitleTrack(trackId);\n }\n } else if (this.shouldReloadPlaylist(currentTrack)) {\n // Retry playlist loading if no playlist is or has been loaded yet\n this.setSubtitleTrack(this.trackId);\n }\n }\n\n private findTrackId(currentTrack: MediaPlaylist | null): number {\n const tracks = this.tracksInGroup;\n const selectDefault = this.selectDefaultTrack;\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (\n (selectDefault && !track.default) ||\n (!selectDefault && !currentTrack)\n ) {\n continue;\n }\n if (!currentTrack || matchesOption(track, currentTrack)) {\n return i;\n }\n }\n if (currentTrack) {\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (\n mediaAttributesIdentical(currentTrack.attrs, track.attrs, [\n 'LANGUAGE',\n 'ASSOC-LANGUAGE',\n 'CHARACTERISTICS',\n ])\n ) {\n return i;\n }\n }\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (\n mediaAttributesIdentical(currentTrack.attrs, track.attrs, [\n 'LANGUAGE',\n ])\n ) {\n return i;\n }\n }\n }\n return -1;\n }\n\n private findTrackForTextTrack(textTrack: TextTrack | null): number {\n if (textTrack) {\n const tracks = this.tracksInGroup;\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (subtitleTrackMatchesTextTrack(track, textTrack)) {\n return i;\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 (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)\n ) {\n this.checkRetry(data);\n }\n }\n\n get allSubtitleTracks(): MediaPlaylist[] {\n return this.tracks;\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 this.setSubtitleTrack(newId);\n }\n\n public setSubtitleOption(\n subtitleOption: MediaPlaylist | SubtitleSelectionOption | undefined,\n ): MediaPlaylist | null {\n this.hls.config.subtitlePreference = subtitleOption;\n if (subtitleOption) {\n const allSubtitleTracks = this.allSubtitleTracks;\n this.selectDefaultTrack = false;\n if (allSubtitleTracks.length) {\n // First see if current option matches (no switch op)\n const currentTrack = this.currentTrack;\n if (currentTrack && matchesOption(subtitleOption, currentTrack)) {\n return currentTrack;\n }\n // Find option in current group\n const groupIndex = findMatchingOption(\n subtitleOption,\n this.tracksInGroup,\n );\n if (groupIndex > -1) {\n const track = this.tracksInGroup[groupIndex];\n this.setSubtitleTrack(groupIndex);\n return track;\n } else if (currentTrack) {\n // If this is not the initial selection return null\n // option should have matched one in active group\n return null;\n } else {\n // Find the option in all tracks for initial selection\n const allIndex = findMatchingOption(\n subtitleOption,\n allSubtitleTracks,\n );\n if (allIndex > -1) {\n return allSubtitleTracks[allIndex];\n }\n }\n }\n }\n return null;\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n super.loadPlaylist();\n const currentTrack = this.currentTrack;\n if (this.shouldLoadPlaylist(currentTrack) && 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(): void {\n const { media } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n const currentTrack = this.currentTrack;\n let nextTrack;\n if (currentTrack) {\n nextTrack = textTracks.filter((textTrack) =>\n subtitleTrackMatchesTextTrack(currentTrack, textTrack),\n )[0];\n if (!nextTrack) {\n this.warn(\n `Unable to find subtitle TextTrack with name \"${currentTrack.name}\" and language \"${currentTrack.lang}\"`,\n );\n }\n }\n [].slice.call(textTracks).forEach((track) => {\n if (track.mode !== 'disabled' && track !== nextTrack) {\n track.mode = 'disabled';\n }\n });\n if (nextTrack) {\n const mode = this.subtitleDisplay ? 'showing' : 'hidden';\n if (nextTrack.mode !== mode) {\n nextTrack.mode = mode;\n }\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(newId: number): 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 // exit if track id as already set or invalid\n if (newId < -1 || newId >= tracks.length || !Number.isFinite(newId)) {\n this.warn(`Invalid subtitle track id: ${newId}`);\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n this.selectDefaultTrack = false;\n const lastTrack = this.currentTrack;\n const track: MediaPlaylist | null = tracks[newId] || null;\n this.trackId = newId;\n this.currentTrack = track;\n this.toggleTrackModes();\n if (!track) {\n // switch to -1\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, { id: newId });\n return;\n }\n const trackLoaded = !!track.details && !track.details.live;\n if (newId === this.trackId && track === lastTrack && trackLoaded) {\n return;\n }\n this.log(\n `Switching to subtitle-track ${newId}` +\n (track\n ? ` \"${track.name}\" lang:${track.lang} group:${track.groupId}`\n : ''),\n );\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(\n track.url,\n lastTrack?.details,\n track.details,\n );\n this.loadPlaylist(hlsUrlParameters);\n }\n\n private onTextTracksChanged = () => {\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 textTrack: TextTrack | null = null;\n const tracks = filterSubtitleTracks(this.media.textTracks);\n for (let i = 0; i < tracks.length; i++) {\n if (tracks[i].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n textTrack = tracks[i];\n } else if (tracks[i].mode === 'showing') {\n textTrack = tracks[i];\n break;\n }\n }\n\n // Find internal track index for TextTrack\n const trackId = this.findTrackForTextTrack(textTrack);\n if (this.subtitleTrack !== trackId) {\n this.setSubtitleTrack(trackId);\n }\n };\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(\n operation: BufferOperation,\n type: SourceBufferName,\n pending?: boolean,\n ) {\n const queue = this.queues[type];\n queue.push(operation);\n if (queue.length === 1 && !pending) {\n this.executeNext(type);\n }\n }\n\n public insertAbort(operation: BufferOperation, type: SourceBufferName) {\n const queue = this.queues[type];\n queue.unshift(operation);\n this.executeNext(type);\n }\n\n public appendBlocker(type: SourceBufferName): Promise<{}> {\n let execute;\n const promise: Promise<{}> = new Promise((resolve) => {\n execute = resolve;\n });\n const operation: BufferOperation = {\n execute,\n onStart: () => {},\n onComplete: () => {},\n onError: () => {},\n };\n\n this.append(operation, type);\n return promise;\n }\n\n public executeNext(type: SourceBufferName) {\n const queue = this.queues[type];\n if (queue.length) {\n const operation: BufferOperation = queue[0];\n try {\n // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations\n // which do not end with this event must call _onSBUpdateEnd manually\n operation.execute();\n } catch (error) {\n logger.warn(\n `[buffer-operation-queue]: Exception executing \"${type}\" SourceBuffer operation: ${error}`,\n );\n operation.onError(error);\n\n // Only shift the current operation off, otherwise the updateend handler will do this for us\n const sb = this.buffers[type];\n if (!sb?.updating) {\n this.shiftAndExecuteNext(type);\n }\n }\n }\n }\n\n public shiftAndExecuteNext(type: SourceBufferName) {\n this.queues[type].shift();\n this.executeNext(type);\n }\n\n public current(type: SourceBufferName) {\n return this.queues[type][0];\n }\n}\n","import { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport {\n getCodecCompatibleName,\n pickMostCompleteCodecName,\n} from '../utils/codecs';\nimport {\n getMediaSource,\n isManagedMediaSource,\n} from '../utils/mediasource-helper';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport type { TrackSet } from '../types/track';\nimport BufferOperationQueue from './buffer-operation-queue';\nimport {\n BufferOperation,\n SourceBuffers,\n SourceBufferName,\n SourceBufferListeners,\n} from '../types/buffer';\nimport type {\n LevelUpdatedData,\n BufferAppendingData,\n MediaAttachingData,\n ManifestParsedData,\n BufferCodecsData,\n BufferEOSData,\n BufferFlushingData,\n FragParsedData,\n FragChangedData,\n ErrorData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { ChunkMetadata } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { HlsConfig } from '../config';\n\nconst VIDEO_CODEC_PROFILE_REPLACE =\n /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\\.[^.,]+)+/;\n\ninterface BufferedChangeEvent extends Event {\n readonly addedRanges?: TimeRanges;\n readonly removedRanges?: TimeRanges;\n}\n\nexport default class BufferController implements ComponentAPI {\n // The level details used to determine duration, target-duration and live\n private details: LevelDetails | null = null;\n // cache the self generated object url to detect hijack of video tag\n private _objectUrl: string | null = null;\n // A queue of buffer operations which require the SourceBuffer to not be updating upon execution\n private operationQueue!: BufferOperationQueue;\n // References to event listeners for each SourceBuffer, so that they can be referenced for event removal\n private listeners!: SourceBufferListeners;\n\n private hls: Hls;\n\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n public bufferCodecEventsExpected: number = 0;\n\n // The total number of BUFFER_CODEC events received\n private _bufferCodecEventsTotal: number = 0;\n\n // A reference to the attached media element\n public media: HTMLMediaElement | null = null;\n\n // A reference to the active media source\n public mediaSource: MediaSource | null = null;\n\n // Last MP3 audio chunk appended\n private lastMpegAudioChunk: ChunkMetadata | null = null;\n\n private appendSource: boolean;\n\n // counters\n public appendErrors = {\n audio: 0,\n video: 0,\n audiovideo: 0,\n };\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer!: SourceBuffers;\n\n protected log: (msg: any) => void;\n protected warn: (msg: any, obj?: any) => void;\n protected error: (msg: any, obj?: any) => void;\n\n constructor(hls: Hls) {\n this.hls = hls;\n const logPrefix = '[buffer-controller]';\n this.appendSource = isManagedMediaSource(\n getMediaSource(hls.config.preferManagedMediaSource),\n );\n this.log = logger.log.bind(logger, logPrefix);\n this.warn = logger.warn.bind(logger, logPrefix);\n this.error = logger.error.bind(logger, logPrefix);\n this._initSourceBuffer();\n this.registerListeners();\n }\n\n public hasSourceTypes(): boolean {\n return (\n this.getSourceBufferTypes().length > 0 ||\n Object.keys(this.pendingTracks).length > 0\n );\n }\n\n public destroy() {\n this.unregisterListeners();\n this.details = null;\n this.lastMpegAudioChunk = null;\n // @ts-ignore\n this.hls = null;\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.on(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);\n }\n\n protected unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.off(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);\n }\n\n private _initSourceBuffer() {\n this.sourceBuffer = {};\n this.operationQueue = new BufferOperationQueue(this.sourceBuffer);\n this.listeners = {\n audio: [],\n video: [],\n audiovideo: [],\n };\n this.appendErrors = {\n audio: 0,\n video: 0,\n audiovideo: 0,\n };\n this.lastMpegAudioChunk = null;\n }\n\n private onManifestLoading() {\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;\n this.details = null;\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n let codecEvents: number = 2;\n if ((data.audio && !data.video) || !data.altAudio || !__USE_ALT_AUDIO__) {\n codecEvents = 1;\n }\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) {\n const media = (this.media = data.media);\n const MediaSource = getMediaSource(this.appendSource);\n\n if (media && MediaSource) {\n const ms = (this.mediaSource = new MediaSource());\n this.log(`created media source: ${ms.constructor?.name}`);\n // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\n if (this.appendSource) {\n ms.addEventListener('startstreaming', this._onStartStreaming);\n ms.addEventListener('endstreaming', this._onEndStreaming);\n }\n\n // cache the locally generated object url\n const objectUrl = (this._objectUrl = self.URL.createObjectURL(ms));\n // link video and media Source\n if (this.appendSource) {\n try {\n media.removeAttribute('src');\n // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives\n const MMS = (self as any).ManagedMediaSource;\n media.disableRemotePlayback =\n media.disableRemotePlayback || (MMS && ms instanceof MMS);\n removeSourceChildren(media);\n addSource(media, objectUrl);\n media.load();\n } catch (error) {\n media.src = objectUrl;\n }\n } else {\n media.src = objectUrl;\n }\n media.addEventListener('emptied', this._onMediaEmptied);\n }\n }\n private _onEndStreaming = (event) => {\n if (!this.hls) {\n return;\n }\n this.hls.pauseBuffering();\n };\n private _onStartStreaming = (event) => {\n if (!this.hls) {\n return;\n }\n this.hls.resumeBuffering();\n };\n\n protected onMediaDetaching() {\n const { media, mediaSource, _objectUrl } = this;\n if (mediaSource) {\n this.log('media source detaching');\n if (mediaSource.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n mediaSource.endOfStream();\n } catch (err) {\n this.warn(\n `onMediaDetaching: ${err.message} while calling endOfStream`,\n );\n }\n }\n // Clean up the SourceBuffers by invoking onBufferReset\n this.onBufferReset();\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);\n mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);\n if (this.appendSource) {\n mediaSource.removeEventListener(\n 'startstreaming',\n this._onStartStreaming,\n );\n mediaSource.removeEventListener('endstreaming', this._onEndStreaming);\n }\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n if (_objectUrl) {\n self.URL.revokeObjectURL(_objectUrl);\n }\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.mediaSrc === _objectUrl) {\n media.removeAttribute('src');\n if (this.appendSource) {\n removeSourceChildren(media);\n }\n media.load();\n } else {\n this.warn(\n 'media|source.src was changed by a third party - skip cleanup',\n );\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = null;\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n this.pendingTracks = {};\n this.tracks = {};\n }\n\n this.hls.trigger(Events.MEDIA_DETACHED, undefined);\n }\n\n protected onBufferReset() {\n this.getSourceBufferTypes().forEach((type) => {\n this.resetBuffer(type);\n });\n this._initSourceBuffer();\n }\n\n private resetBuffer(type: SourceBufferName) {\n const sb = this.sourceBuffer[type];\n try {\n if (sb) {\n this.removeBufferListeners(type);\n // Synchronously remove the SB from the map before the next call in order to prevent an async function from\n // accessing it\n this.sourceBuffer[type] = undefined;\n if (this.mediaSource?.sourceBuffers.length) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n }\n } catch (err) {\n this.warn(`onBufferReset ${type}`, err);\n }\n }\n\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData,\n ) {\n const sourceBufferCount = this.getSourceBufferTypes().length;\n const trackNames = Object.keys(data);\n trackNames.forEach((trackName) => {\n if (sourceBufferCount) {\n // check if SourceBuffer codec needs to change\n const track = this.tracks[trackName];\n if (track && typeof track.buffer.changeType === 'function') {\n const { id, codec, levelCodec, container, metadata } =\n data[trackName];\n const currentCodecFull = pickMostCompleteCodecName(\n track.codec,\n track.levelCodec,\n );\n const currentCodec = currentCodecFull?.replace(\n VIDEO_CODEC_PROFILE_REPLACE,\n '$1',\n );\n let trackCodec = pickMostCompleteCodecName(codec, levelCodec);\n const nextCodec = trackCodec?.replace(\n VIDEO_CODEC_PROFILE_REPLACE,\n '$1',\n );\n if (trackCodec && currentCodec !== nextCodec) {\n if (trackName.slice(0, 5) === 'audio') {\n trackCodec = getCodecCompatibleName(\n trackCodec,\n this.appendSource,\n );\n }\n const mimeType = `${container};codecs=${trackCodec}`;\n this.appendChangeType(trackName, mimeType);\n this.log(`switching codec ${currentCodecFull} to ${trackCodec}`);\n this.tracks[trackName] = {\n buffer: track.buffer,\n codec,\n container,\n levelCodec,\n metadata,\n id,\n };\n }\n }\n } else {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n this.pendingTracks[trackName] = data[trackName];\n }\n });\n\n // if sourcebuffers already created, do nothing ...\n if (sourceBufferCount) {\n return;\n }\n\n const bufferCodecEventsExpected = Math.max(\n this.bufferCodecEventsExpected - 1,\n 0,\n );\n if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) {\n this.log(\n `${bufferCodecEventsExpected} bufferCodec event(s) expected ${trackNames.join(\n ',',\n )}`,\n );\n this.bufferCodecEventsExpected = bufferCodecEventsExpected;\n }\n if (this.mediaSource && this.mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n protected appendChangeType(type, mimeType) {\n const { operationQueue } = this;\n const operation: BufferOperation = {\n execute: () => {\n const sb = this.sourceBuffer[type];\n if (sb) {\n this.log(`changing ${type} sourceBuffer type to ${mimeType}`);\n sb.changeType(mimeType);\n }\n operationQueue.shiftAndExecuteNext(type);\n },\n onStart: () => {},\n onComplete: () => {},\n onError: (error: Error) => {\n this.warn(`Failed to change ${type} SourceBuffer type`, error);\n },\n };\n\n operationQueue.append(operation, type, !!this.pendingTracks[type]);\n }\n\n protected onBufferAppending(\n event: Events.BUFFER_APPENDING,\n eventData: BufferAppendingData,\n ) {\n const { hls, operationQueue, tracks } = this;\n const { data, type, frag, part, chunkMeta } = eventData;\n const chunkStats = chunkMeta.buffering[type];\n\n const bufferAppendingStart = self.performance.now();\n chunkStats.start = bufferAppendingStart;\n const fragBuffering = frag.stats.buffering;\n const partBuffering = part ? part.stats.buffering : null;\n if (fragBuffering.start === 0) {\n fragBuffering.start = bufferAppendingStart;\n }\n if (partBuffering && partBuffering.start === 0) {\n partBuffering.start = bufferAppendingStart;\n }\n\n // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n const audioTrack = tracks.audio;\n let checkTimestampOffset = false;\n if (type === 'audio' && audioTrack?.container === 'audio/mpeg') {\n checkTimestampOffset =\n !this.lastMpegAudioChunk ||\n chunkMeta.id === 1 ||\n this.lastMpegAudioChunk.sn !== chunkMeta.sn;\n this.lastMpegAudioChunk = chunkMeta;\n }\n\n const fragStart = frag.start;\n const operation: BufferOperation = {\n execute: () => {\n chunkStats.executeStart = self.performance.now();\n if (checkTimestampOffset) {\n const sb = this.sourceBuffer[type];\n if (sb) {\n const delta = fragStart - sb.timestampOffset;\n if (Math.abs(delta) >= 0.1) {\n this.log(\n `Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${frag.sn})`,\n );\n sb.timestampOffset = fragStart;\n }\n }\n }\n this.appendExecutor(data, type);\n },\n onStart: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);\n const end = self.performance.now();\n chunkStats.executeEnd = chunkStats.end = end;\n if (fragBuffering.first === 0) {\n fragBuffering.first = end;\n }\n if (partBuffering && partBuffering.first === 0) {\n partBuffering.first = end;\n }\n\n const { sourceBuffer } = this;\n const timeRanges = {};\n for (const type in sourceBuffer) {\n timeRanges[type] = BufferHelper.getBuffered(sourceBuffer[type]);\n }\n this.appendErrors[type] = 0;\n if (type === 'audio' || type === 'video') {\n this.appendErrors.audiovideo = 0;\n } else {\n this.appendErrors.audio = 0;\n this.appendErrors.video = 0;\n }\n this.hls.trigger(Events.BUFFER_APPENDED, {\n type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n timeRanges,\n });\n },\n onError: (error: Error) => {\n // in case any error occured while appending, put back segment in segments table\n const event: ErrorData = {\n type: ErrorTypes.MEDIA_ERROR,\n parent: frag.type,\n details: ErrorDetails.BUFFER_APPEND_ERROR,\n sourceBufferName: type,\n frag,\n part,\n chunkMeta,\n error,\n err: error,\n fatal: false,\n };\n\n if ((error as DOMException).code === DOMException.QUOTA_EXCEEDED_ERR) {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n } else {\n const appendErrorCount = ++this.appendErrors[type];\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. Retrying can help recover.\n */\n this.warn(\n `Failed ${appendErrorCount}/${hls.config.appendErrorMaxRetry} times to append segment in \"${type}\" sourceBuffer`,\n );\n if (appendErrorCount >= hls.config.appendErrorMaxRetry) {\n event.fatal = true;\n }\n }\n hls.trigger(Events.ERROR, event);\n },\n };\n operationQueue.append(operation, type, !!this.pendingTracks[type]);\n }\n\n protected onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData,\n ) {\n const { operationQueue } = this;\n const flushOperation = (type: SourceBufferName): BufferOperation => ({\n execute: this.removeExecutor.bind(\n this,\n type,\n data.startOffset,\n data.endOffset,\n ),\n onStart: () => {\n // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n this.hls.trigger(Events.BUFFER_FLUSHED, { type });\n },\n onError: (error: Error) => {\n this.warn(`Failed to remove from ${type} SourceBuffer`, error);\n },\n });\n\n if (data.type) {\n operationQueue.append(flushOperation(data.type), data.type);\n } else {\n this.getSourceBufferTypes().forEach((type: SourceBufferName) => {\n operationQueue.append(flushOperation(type), type);\n });\n }\n }\n\n protected onFragParsed(event: Events.FRAG_PARSED, data: FragParsedData) {\n const { frag, part } = data;\n const buffersAppendedTo: Array<SourceBufferName> = [];\n const elementaryStreams = part\n ? part.elementaryStreams\n : frag.elementaryStreams;\n if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {\n buffersAppendedTo.push('audiovideo');\n } else {\n if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {\n buffersAppendedTo.push('audio');\n }\n if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {\n buffersAppendedTo.push('video');\n }\n }\n\n const onUnblocked = () => {\n const now = self.performance.now();\n frag.stats.buffering.end = now;\n if (part) {\n part.stats.buffering.end = now;\n }\n const stats = part ? part.stats : frag.stats;\n this.hls.trigger(Events.FRAG_BUFFERED, {\n frag,\n part,\n stats,\n id: frag.type,\n });\n };\n\n if (buffersAppendedTo.length === 0) {\n this.warn(\n `Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`,\n );\n }\n\n this.blockBuffers(onUnblocked, buffersAppendedTo);\n }\n\n private onFragChanged(event: Events.FRAG_CHANGED, data: FragChangedData) {\n this.trimBuffers();\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n // an undefined data.type will mark all buffers as EOS.\n protected onBufferEos(event: Events.BUFFER_EOS, data: BufferEOSData) {\n const ended = this.getSourceBufferTypes().reduce((acc, type) => {\n const sb = this.sourceBuffer[type];\n if (sb && (!data.type || data.type === type)) {\n sb.ending = true;\n if (!sb.ended) {\n sb.ended = true;\n this.log(`${type} sourceBuffer now EOS`);\n }\n }\n return acc && !!(!sb || sb.ended);\n }, true);\n\n if (ended) {\n this.log(`Queueing mediaSource.endOfStream()`);\n this.blockBuffers(() => {\n this.getSourceBufferTypes().forEach((type) => {\n const sb = this.sourceBuffer[type];\n if (sb) {\n sb.ending = false;\n }\n });\n const { mediaSource } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n if (mediaSource) {\n this.log(\n `Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`,\n );\n }\n return;\n }\n this.log(`Calling mediaSource.endOfStream()`);\n // Allow this to throw and be caught by the enqueueing function\n mediaSource.endOfStream();\n });\n }\n }\n\n protected onLevelUpdated(\n event: Events.LEVEL_UPDATED,\n { details }: LevelUpdatedData,\n ) {\n if (!details.fragments.length) {\n return;\n }\n this.details = details;\n\n if (this.getSourceBufferTypes().length) {\n this.blockBuffers(this.updateMediaElementDuration.bind(this));\n } else {\n this.updateMediaElementDuration();\n }\n }\n\n trimBuffers() {\n const { hls, details, media } = this;\n if (!media || details === null) {\n return;\n }\n\n const sourceBufferTypes = this.getSourceBufferTypes();\n if (!sourceBufferTypes.length) {\n return;\n }\n\n const config: Readonly<HlsConfig> = hls.config;\n const currentTime = media.currentTime;\n const targetDuration = details.levelTargetDuration;\n\n // Support for deprecated liveBackBufferLength\n const backBufferLength =\n details.live && config.liveBackBufferLength !== null\n ? config.liveBackBufferLength\n : config.backBufferLength;\n\n if (Number.isFinite(backBufferLength) && backBufferLength > 0) {\n const maxBackBufferLength = Math.max(backBufferLength, targetDuration);\n const targetBackBufferPosition =\n Math.floor(currentTime / targetDuration) * targetDuration -\n maxBackBufferLength;\n\n this.flushBackBuffer(\n currentTime,\n targetDuration,\n targetBackBufferPosition,\n );\n }\n\n if (\n Number.isFinite(config.frontBufferFlushThreshold) &&\n config.frontBufferFlushThreshold > 0\n ) {\n const frontBufferLength = Math.max(\n config.maxBufferLength,\n config.frontBufferFlushThreshold,\n );\n\n const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);\n const targetFrontBufferPosition =\n Math.floor(currentTime / targetDuration) * targetDuration +\n maxFrontBufferLength;\n\n this.flushFrontBuffer(\n currentTime,\n targetDuration,\n targetFrontBufferPosition,\n );\n }\n }\n\n flushBackBuffer(\n currentTime: number,\n targetDuration: number,\n targetBackBufferPosition: number,\n ) {\n const { details, sourceBuffer } = this;\n const sourceBufferTypes = this.getSourceBufferTypes();\n\n sourceBufferTypes.forEach((type: SourceBufferName) => {\n const sb = sourceBuffer[type];\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n // when target buffer start exceeds actual buffer start\n if (\n buffered.length > 0 &&\n targetBackBufferPosition > buffered.start(0)\n ) {\n this.hls.trigger(Events.BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n\n // Support for deprecated event:\n if (details?.live) {\n this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n } else if (\n sb.ended &&\n buffered.end(buffered.length - 1) - currentTime < targetDuration * 2\n ) {\n this.log(\n `Cannot flush ${type} back buffer while SourceBuffer is in ended state`,\n );\n return;\n }\n\n this.hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: targetBackBufferPosition,\n type,\n });\n }\n }\n });\n }\n\n flushFrontBuffer(\n currentTime: number,\n targetDuration: number,\n targetFrontBufferPosition: number,\n ) {\n const { sourceBuffer } = this;\n const sourceBufferTypes = this.getSourceBufferTypes();\n\n sourceBufferTypes.forEach((type: SourceBufferName) => {\n const sb = sourceBuffer[type];\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n const numBufferedRanges = buffered.length;\n // The buffer is either empty or contiguous\n if (numBufferedRanges < 2) {\n return;\n }\n const bufferStart = buffered.start(numBufferedRanges - 1);\n const bufferEnd = buffered.end(numBufferedRanges - 1);\n // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position\n if (\n targetFrontBufferPosition > bufferStart ||\n (currentTime >= bufferStart && currentTime <= bufferEnd)\n ) {\n return;\n } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) {\n this.log(\n `Cannot flush ${type} front buffer while SourceBuffer is in ended state`,\n );\n return;\n }\n\n this.hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: bufferStart,\n endOffset: Infinity,\n type,\n });\n }\n });\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n private updateMediaElementDuration() {\n if (\n !this.details ||\n !this.media ||\n !this.mediaSource ||\n this.mediaSource.readyState !== 'open'\n ) {\n return;\n }\n const { details, hls, media, mediaSource } = this;\n const levelDuration = details.fragments[0].start + details.totalduration;\n const mediaDuration = media.duration;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : 0;\n\n if (details.live && hls.config.liveDurationInfinity) {\n // Override duration to Infinity\n mediaSource.duration = Infinity;\n this.updateSeekableRange(details);\n } else if (\n (levelDuration > msDuration && levelDuration > mediaDuration) ||\n !Number.isFinite(mediaDuration)\n ) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n this.log(`Updating Media Source duration to ${levelDuration.toFixed(3)}`);\n mediaSource.duration = levelDuration;\n }\n }\n\n updateSeekableRange(levelDetails) {\n const mediaSource = this.mediaSource;\n const fragments = levelDetails.fragments;\n const len = fragments.length;\n if (len && levelDetails.live && mediaSource?.setLiveSeekableRange) {\n const start = Math.max(0, fragments[0].start);\n const end = Math.max(start, start + levelDetails.totalduration);\n this.log(\n `Media Source duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`,\n );\n mediaSource.setLiveSeekableRange(start, end);\n }\n }\n\n protected checkPendingTracks() {\n const { bufferCodecEventsExpected, operationQueue, pendingTracks } = this;\n\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n const pendingTracksCount = Object.keys(pendingTracks).length;\n if (\n pendingTracksCount &&\n (!bufferCodecEventsExpected ||\n pendingTracksCount === 2 ||\n 'audiovideo' in pendingTracks)\n ) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n const buffers = this.getSourceBufferTypes();\n if (buffers.length) {\n this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks });\n buffers.forEach((type: SourceBufferName) => {\n operationQueue.executeNext(type);\n });\n } else {\n const error = new Error(\n 'could not create source buffer for media codec(s)',\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n error,\n reason: error.message,\n });\n }\n }\n }\n\n protected createSourceBuffers(tracks: TrackSet) {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource) {\n throw Error('createSourceBuffers called when mediaSource was null');\n }\n for (const trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n const track = tracks[trackName as keyof TrackSet];\n if (!track) {\n throw Error(\n `source buffer exists for track ${trackName}, however track does not`,\n );\n }\n // use levelCodec as first priority unless it contains multiple comma-separated codec values\n let codec =\n track.levelCodec?.indexOf(',') === -1\n ? track.levelCodec\n : track.codec;\n if (codec) {\n if (trackName.slice(0, 5) === 'audio') {\n codec = getCodecCompatibleName(codec, this.appendSource);\n }\n }\n const mimeType = `${track.container};codecs=${codec}`;\n this.log(`creating sourceBuffer(${mimeType})`);\n try {\n const sb = (sourceBuffer[trackName] =\n mediaSource.addSourceBuffer(mimeType));\n const sbName = trackName as SourceBufferName;\n this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);\n this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);\n this.addBufferListener(sbName, 'error', this._onSBUpdateError);\n // ManagedSourceBuffer bufferedchange event\n if (this.appendSource) {\n this.addBufferListener(\n sbName,\n 'bufferedchange',\n (type: SourceBufferName, event: BufferedChangeEvent) => {\n // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.\n const removedRanges = event.removedRanges;\n if (removedRanges?.length) {\n this.hls.trigger(Events.BUFFER_FLUSHED, {\n type: trackName as SourceBufferName,\n });\n }\n },\n );\n }\n\n this.tracks[trackName] = {\n buffer: sb,\n codec: codec,\n container: track.container,\n levelCodec: track.levelCodec,\n metadata: track.metadata,\n id: track.id,\n };\n } catch (err) {\n this.error(`error while trying to add sourceBuffer: ${err.message}`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,\n fatal: false,\n error: err,\n sourceBufferName: trackName as SourceBufferName,\n mimeType: mimeType,\n });\n }\n }\n }\n }\n\n // Keep as arrow functions so that we can directly reference these functions directly as event listeners\n private _onMediaSourceOpen = () => {\n const { media, mediaSource } = this;\n this.log('Media source opened');\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n this.updateMediaElementDuration();\n this.hls.trigger(Events.MEDIA_ATTACHED, {\n media,\n mediaSource: mediaSource as MediaSource,\n });\n }\n\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n }\n this.checkPendingTracks();\n };\n\n private _onMediaSourceClose = () => {\n this.log('Media source closed');\n };\n\n private _onMediaSourceEnded = () => {\n this.log('Media source ended');\n };\n\n private _onMediaEmptied = () => {\n const { mediaSrc, _objectUrl } = this;\n if (mediaSrc !== _objectUrl) {\n logger.error(\n `Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`,\n );\n }\n };\n\n private get mediaSrc(): string | undefined {\n const media = this.media?.querySelector?.('source') || this.media;\n return media?.src;\n }\n\n private _onSBUpdateStart(type: SourceBufferName) {\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onStart();\n }\n\n private _onSBUpdateEnd(type: SourceBufferName) {\n if (this.mediaSource?.readyState === 'closed') {\n this.resetBuffer(type);\n return;\n }\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onComplete();\n operationQueue.shiftAndExecuteNext(type);\n }\n\n private _onSBUpdateError(type: SourceBufferName, event: Event) {\n const error = new Error(\n `${type} SourceBuffer error. MediaSource readyState: ${this.mediaSource?.readyState}`,\n );\n this.error(`${error}`, event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_APPENDING_ERROR,\n sourceBufferName: type,\n error,\n fatal: false,\n });\n // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue\n const operation = this.operationQueue.current(type);\n if (operation) {\n operation.onError(error);\n }\n }\n\n // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually\n private removeExecutor(\n type: SourceBufferName,\n startOffset: number,\n endOffset: number,\n ) {\n const { media, mediaSource, operationQueue, sourceBuffer } = this;\n const sb = sourceBuffer[type];\n if (!media || !mediaSource || !sb) {\n this.warn(\n `Attempting to remove from the ${type} SourceBuffer, but it does not exist`,\n );\n operationQueue.shiftAndExecuteNext(type);\n return;\n }\n const mediaDuration = Number.isFinite(media.duration)\n ? media.duration\n : Infinity;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : Infinity;\n const removeStart = Math.max(0, startOffset);\n const removeEnd = Math.min(endOffset, mediaDuration, msDuration);\n if (removeEnd > removeStart && (!sb.ending || sb.ended)) {\n sb.ended = false;\n this.log(\n `Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`,\n );\n sb.remove(removeStart, removeEnd);\n } else {\n // Cycle the queue\n operationQueue.shiftAndExecuteNext(type);\n }\n }\n\n // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually\n private appendExecutor(data: Uint8Array, type: SourceBufferName) {\n const sb = this.sourceBuffer[type];\n if (!sb) {\n if (!this.pendingTracks[type]) {\n throw new Error(\n `Attempting to append to the ${type} SourceBuffer, but it does not exist`,\n );\n }\n return;\n }\n\n sb.ended = false;\n sb.appendBuffer(data);\n }\n\n // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises\n // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue\n // upon completion, since we already do it here\n private blockBuffers(\n onUnblocked: () => void,\n buffers: Array<SourceBufferName> = this.getSourceBufferTypes(),\n ) {\n if (!buffers.length) {\n this.log('Blocking operation requested, but no SourceBuffers exist');\n Promise.resolve().then(onUnblocked);\n return;\n }\n const { operationQueue } = this;\n\n // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);\n const blockingOperations = buffers.map((type) =>\n operationQueue.appendBlocker(type as SourceBufferName),\n );\n Promise.all(blockingOperations).then(() => {\n // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);\n onUnblocked();\n buffers.forEach((type) => {\n const sb = this.sourceBuffer[type];\n // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to\n // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)\n // While this is a workaround, it's probably useful to have around\n if (!sb?.updating) {\n operationQueue.shiftAndExecuteNext(type);\n }\n });\n });\n }\n\n private getSourceBufferTypes(): Array<SourceBufferName> {\n return Object.keys(this.sourceBuffer) as Array<SourceBufferName>;\n }\n\n private addBufferListener(\n type: SourceBufferName,\n event: string,\n fn: Function,\n ) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n const listener = fn.bind(this, type);\n this.listeners[type].push({ event, listener });\n buffer.addEventListener(event, listener);\n }\n\n private removeBufferListeners(type: SourceBufferName) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n this.listeners[type].forEach((l) => {\n buffer.removeEventListener(l.event, l.listener);\n });\n }\n}\n\nfunction removeSourceChildren(node: HTMLElement) {\n const sourceChildren = node.querySelectorAll('source');\n [].slice.call(sourceChildren).forEach((source) => {\n node.removeChild(source);\n });\n}\n\nfunction addSource(media: HTMLMediaElement, url: string) {\n const source = self.document.createElement('source');\n source.type = 'video/mp4';\n source.src = url;\n media.appendChild(source);\n}\n","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 = (byte: number) =>\n String.fromCharCode(specialCea608CharsCodes[byte] || byte);\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 = 'white';\n public underline: boolean = false;\n public italics: boolean = false;\n public background: string = 'black';\n public flash: boolean = false;\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 = new PenState();\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 = 0;\n public currPenState: PenState = new PenState();\n public cueStartTime: number | null = null;\n private logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n this.logger = logger;\n }\n\n equals(other: Row) {\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].equals(other.chars[i])) {\n return false;\n }\n }\n return true;\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 = NR_ROWS - 1;\n nrRollUpRows: number | null = null;\n lastOutputScreen: CaptionScreen | null = null;\n logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row(logger));\n }\n this.logger = logger;\n }\n\n reset() {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\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 !== null && 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 = createCmdHistory();\n logger: CaptionsLogger;\n\n constructor(field: SupportedField, out1: OutputFilter, out2: OutputFilter) {\n const logger = (this.logger = new CaptionsLogger());\n this.channels = [\n null,\n new Cea608Channel(field, out1, logger),\n new Cea608Channel(field + 1, out2, logger),\n ];\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 this.logger.time = time;\n for (let i = 0; i < byteList.length; i += 2) {\n const a = byteList[i] & 0x7f;\n const b = byteList[i + 1] & 0x7f;\n let cmdFound: boolean = false;\n let charsFound: number[] | null = null;\n\n if (a === 0 && b === 0) {\n continue;\n } else {\n this.logger.log(\n VerboseLevel.DATA,\n () =>\n '[' +\n numArrayToHexArray([byteList[i], byteList[i + 1]]) +\n '] -> (' +\n numArrayToHexArray([a, b]) +\n ')',\n );\n }\n\n const cmdHistory = this.cmdHistory;\n const isControlCode = a >= 0x10 && a <= 0x1f;\n if (isControlCode) {\n // Skip redundant control codes\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n this.logger.log(\n VerboseLevel.DEBUG,\n () =>\n 'Repeated command (' +\n numArrayToHexArray([a, b]) +\n ') is dropped',\n );\n continue;\n }\n setLastCmd(a, b, this.cmdHistory);\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 } else {\n setLastCmd(null, null, cmdHistory);\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 () =>\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 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 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 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\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 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 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 () =>\n \"Special char '\" +\n getCharForByte(oneCode) +\n \"' in channel \" +\n channelNr,\n );\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = b === 0 ? [a] : [a, b];\n }\n if (charCodes) {\n this.logger.log(\n VerboseLevel.DEBUG,\n () =>\n 'Char codes = ' +\n numArrayToHexArray(charCodes as number[]).join(','),\n );\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 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 setLastCmd(null, null, this.cmdHistory);\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\nimport { optionalSelf } from './global';\n\ndeclare interface VTTCuePolyfill extends VTTCue {\n new (...args): VTTCuePolyfill;\n hasBeenReset: boolean;\n displayState: void;\n}\n\nexport default (function () {\n if (optionalSelf?.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 '-->'): \" +\n 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 filterSubtitleTracks,\n} from '../utils/texttrack-utils';\nimport {\n subtitleOptionsIdentical,\n subtitleTrackMatchesTextTrack,\n} 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 type {\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 lastCc: number = -1; // Last video (CEA-608) fragment CC\n private lastSn: number = -1; // Last video (CEA-608) fragment MSN\n private lastPartIndex: number = -1; // Last video (CEA-608) fragment Part Index\n private prevCC: number = -1; // Last subtitle fragment CC\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 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 = null;\n this.cea608Parser1 = this.cea608Parser2 = undefined;\n }\n\n private initCea608Parsers() {\n if (\n this.config.enableCEA708Captions &&\n (!this.cea608Parser1 || !this.cea608Parser2)\n ) {\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\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(label: string, language: 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 (\n canReuseVttTextTrack(textTrack, {\n name: label,\n lang: language,\n attrs: {} as any,\n })\n ) {\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(label, languageCode);\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 // Detect discontinuity in video fragment (CEA-608) parsing\n this.lastCc = -1;\n this.lastSn = -1;\n this.lastPartIndex = -1;\n // Detect discontinuity in subtitle manifests\n this.prevCC = -1;\n this.vttCCs = newVTTCCs();\n // Reset tracks\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 media = this.media;\n const inUseTracks: (TextTrack | null)[] | null = media\n ? filterSubtitleTracks(media.textTracks)\n : null;\n\n this.tracks.forEach((track, index) => {\n // Reuse tracks with the same label and lang, but do not reuse 608/708 tracks\n let textTrack: TextTrack | undefined;\n if (inUseTracks) {\n let inUseTrack: TextTrack | null = null;\n for (let i = 0; i < inUseTracks.length; i++) {\n if (\n inUseTracks[i] &&\n canReuseVttTextTrack(inUseTracks[i], track)\n ) {\n inUseTrack = inUseTracks[i];\n inUseTracks[i] = null;\n break;\n }\n }\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (textTrack) {\n clearCurrentCues(textTrack);\n } else {\n const textTrackKind = 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 this.textTracks.push(textTrack);\n }\n });\n // Warn when video element has captions or subtitle TextTracks carried over from another source\n if (inUseTracks?.length) {\n const unusedTextTracks = inUseTracks\n .filter((t) => t !== null)\n .map((t) => (t as TextTrack).label);\n if (unusedTextTracks.length) {\n logger.warn(\n `Media element contains unused subtitle tracks: ${unusedTextTracks.join(\n ', ',\n )}. Replace media element for each source to clear TextTracks and captions menu.`,\n );\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 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 // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {\n const { cea608Parser1, cea608Parser2, lastSn } = this;\n const { cc, sn } = data.frag;\n const partIndex = data.part?.index ?? -1;\n if (cea608Parser1 && cea608Parser2) {\n if (\n sn !== lastSn + 1 ||\n (sn === lastSn && partIndex !== this.lastPartIndex + 1) ||\n cc !== this.lastCc\n ) {\n cea608Parser1.reset();\n cea608Parser2.reset();\n }\n }\n this.lastCc = cc as number;\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 this.initCea608Parsers();\n const { cea608Parser1, cea608Parser2 } = this;\n if (!this.enabled || !cea608Parser1 || !cea608Parser2) {\n return;\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 captionsOrSubtitlesFromCharacteristics(\n track: Pick<MediaPlaylist, 'name' | 'lang' | 'attrs' | 'characteristics'>,\n): TextTrackKind {\n if (track.characteristics) {\n if (\n /transcribes-spoken-dialog/gi.test(track.characteristics) &&\n /describes-music-and-sound/gi.test(track.characteristics)\n ) {\n return 'captions';\n }\n }\n\n return 'subtitles';\n}\n\nfunction canReuseVttTextTrack(\n inUseTrack: TextTrack | null,\n manifestTrack: Pick<\n MediaPlaylist,\n 'name' | 'lang' | 'attrs' | 'characteristics'\n >,\n): boolean {\n return (\n !!inUseTrack &&\n inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) &&\n subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack)\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 LevelsUpdatedData,\n} from '../types/events';\nimport StreamController from './stream-controller';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\n\ntype RestrictedLevel = { width: number; height: number; bitrate: number };\nclass CapLevelController implements ComponentAPI {\n private hls: Hls;\n private autoLevelCapping: number;\n private firstLevel: number;\n private media: HTMLVideoElement | null;\n private restrictedLevels: RestrictedLevel[];\n private timer: number | undefined;\n private clientRect: { width: number; height: number } | null;\n private streamController?: StreamController;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = -1;\n this.media = null;\n this.restrictedLevels = [];\n this.timer = undefined;\n this.clientRect = null;\n\n this.registerListeners();\n }\n\n public setStreamController(streamController: StreamController) {\n this.streamController = streamController;\n }\n\n public destroy() {\n if (this.hls) {\n this.unregisterListener();\n }\n if (this.timer) {\n this.stopCapping();\n }\n this.media = null;\n this.clientRect = null;\n // @ts-ignore\n this.hls = this.streamController = null;\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected unregisterListener() {\n const { hls } = this;\n hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected onFpsDropLevelCapping(\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData,\n ) {\n // Don't add a restricted level more than once\n const level = this.hls.levels[data.droppedLevel];\n if (this.isLevelAllowed(level)) {\n this.restrictedLevels.push({\n bitrate: level.bitrate,\n height: level.height,\n width: level.width,\n });\n }\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) {\n this.media = data.media instanceof HTMLVideoElement ? data.media : null;\n this.clientRect = null;\n if (this.timer && this.hls.levels.length) {\n this.detectPlayerSize();\n }\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData,\n ) {\n if (this.timer && Number.isFinite(this.autoLevelCapping)) {\n this.detectPlayerSize();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData,\n ) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n\n protected onMediaDetaching() {\n this.stopCapping();\n }\n\n detectPlayerSize() {\n if (this.media) {\n if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {\n this.clientRect = null;\n return;\n }\n const levels = this.hls.levels;\n if (levels.length) {\n const hls = this.hls;\n const maxLevel = this.getMaxLevel(levels.length - 1);\n if (maxLevel !== this.autoLevelCapping) {\n logger.log(\n `Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`,\n );\n }\n hls.autoLevelCapping = maxLevel;\n if (\n hls.autoLevelCapping > this.autoLevelCapping &&\n this.streamController\n ) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n this.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel(capLevelIndex: number): number {\n const levels = this.hls.levels;\n if (!levels.length) {\n return -1;\n }\n\n const validLevels = levels.filter(\n (level, index) => this.isLevelAllowed(level) && index <= capLevelIndex,\n );\n\n this.clientRect = null;\n return CapLevelController.getMaxLevelByMediaSize(\n validLevels,\n this.mediaWidth,\n this.mediaHeight,\n );\n }\n\n startCapping() {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n self.clearInterval(this.timer);\n this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n stopCapping() {\n this.restrictedLevels = [];\n this.firstLevel = -1;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n self.clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n\n getDimensions(): { width: number; height: number } {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0,\n };\n\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width =\n clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height =\n clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n\n get mediaWidth(): number {\n return this.getDimensions().width * this.contentScaleFactor;\n }\n\n get mediaHeight(): number {\n return this.getDimensions().height * this.contentScaleFactor;\n }\n\n get contentScaleFactor(): number {\n let pixelRatio = 1;\n if (!this.hls.config.ignoreDevicePixelRatio) {\n try {\n pixelRatio = self.devicePixelRatio;\n } catch (e) {\n /* no-op */\n }\n }\n\n return pixelRatio;\n }\n\n private isLevelAllowed(level: Level): boolean {\n const restrictedLevels = this.restrictedLevels;\n return !restrictedLevels.some((restrictedLevel) => {\n return (\n level.bitrate === restrictedLevel.bitrate &&\n level.width === restrictedLevel.width &&\n level.height === restrictedLevel.height\n );\n });\n }\n\n static getMaxLevelByMediaSize(\n levels: Array<Level>,\n width: number,\n height: number,\n ): number {\n if (!levels?.length) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandwidth = (\n curLevel: Level,\n nextLevel: Level | undefined,\n ) => {\n if (!nextLevel) {\n return true;\n }\n\n return (\n curLevel.width !== nextLevel.width ||\n curLevel.height !== nextLevel.height\n );\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n // Prevent changes in aspect-ratio from causing capping to toggle back and forth\n const squareSize = Math.max(width, height);\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if (\n (level.width >= squareSize || level.height >= squareSize) &&\n atGreatestBandwidth(level, levels[i + 1])\n ) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","import { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { MediaAttachingData } from '../types/events';\nimport StreamController from './stream-controller';\n\nclass FPSController implements ComponentAPI {\n private hls: Hls;\n private isVideoPlaybackQualityAvailable: boolean = false;\n private timer?: number;\n private media: HTMLVideoElement | null = null;\n private lastTime: any;\n private lastDroppedFrames: number = 0;\n private lastDecodedFrames: number = 0;\n // stream controller must be provided as a dependency!\n private streamController!: StreamController;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n this.registerListeners();\n }\n\n public setStreamController(streamController: StreamController) {\n this.streamController = streamController;\n }\n\n protected registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n }\n\n protected unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n }\n\n destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.unregisterListeners();\n this.isVideoPlaybackQualityAvailable = false;\n this.media = null;\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData,\n ) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const media =\n data.media instanceof self.HTMLVideoElement ? data.media : null;\n this.media = media;\n if (media && typeof media.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n self.clearInterval(this.timer);\n this.timer = self.setInterval(\n this.checkFPSInterval.bind(this),\n config.fpsDroppedMonitoringPeriod,\n );\n }\n }\n\n checkFPS(\n video: HTMLVideoElement,\n decodedFrames: number,\n droppedFrames: number,\n ) {\n const currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n const currentPeriod = currentTime - this.lastTime;\n const currentDropped = droppedFrames - this.lastDroppedFrames;\n const currentDecoded = decodedFrames - this.lastDecodedFrames;\n const droppedFPS = (1000 * currentDropped) / currentPeriod;\n const hls = this.hls;\n hls.trigger(Events.FPS_DROP, {\n currentDropped: currentDropped,\n currentDecoded: currentDecoded,\n totalDroppedFrames: droppedFrames,\n });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (\n currentDropped >\n hls.config.fpsDroppedMonitoringThreshold * currentDecoded\n ) {\n let currentLevel = hls.currentLevel;\n logger.warn(\n 'drop FPS ratio greater than max allowed value for currentLevel: ' +\n currentLevel,\n );\n if (\n currentLevel > 0 &&\n (hls.autoLevelCapping === -1 ||\n hls.autoLevelCapping >= currentLevel)\n ) {\n currentLevel = currentLevel - 1;\n hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {\n level: currentLevel,\n droppedLevel: hls.currentLevel,\n });\n hls.autoLevelCapping = currentLevel;\n this.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval() {\n const video = this.media;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n const videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(\n video,\n videoPlaybackQuality.totalVideoFrames,\n videoPlaybackQuality.droppedVideoFrames,\n );\n } else {\n // HTMLVideoElement doesn't include the webkit types\n this.checkFPS(\n video,\n (video as any).webkitDecodedFrameCount as number,\n (video as any).webkitDroppedFrameCount as number,\n );\n }\n }\n }\n}\n\nexport default FPSController;\n","/**\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 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 {\n bin2str,\n parseMultiPssh,\n parseSinf,\n PsshData,\n PsshInvalidResult,\n} 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 _onmessage?: (this: MediaKeySession, ev: MediaKeyMessageEvent) => any;\n _onkeystatuseschange?: (this: MediaKeySession, ev: Event) => any;\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 const logMessage = `\"${event.type}\" event: init data type: \"${initDataType}\"`;\n this.debug(logMessage);\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 throw new Error(\n `'schm' box missing or not cbcs/cenc with schi > tenc`,\n );\n }\n keyId = tenc.subarray(8, 24);\n keySystemDomain = KeySystems.FAIRPLAY;\n } catch (error) {\n this.warn(`${logMessage} Failed to parse sinf: ${error}`);\n return;\n }\n } else {\n // Support Widevine clear-lead key-session creation (otherwise depend on playlist keys)\n const psshResults = parseMultiPssh(initData);\n const psshInfo = psshResults.filter(\n (pssh): pssh is PsshData => pssh.systemId === KeySystemIds.WIDEVINE,\n )[0];\n if (!psshInfo) {\n if (\n psshResults.length === 0 ||\n psshResults.some((pssh): pssh is PsshInvalidResult => !pssh.systemId)\n ) {\n this.warn(`${logMessage} contains incomplete or invalid pssh data`);\n } else {\n this.log(\n `ignoring ${logMessage} for ${(psshResults as PsshData[])\n .map((pssh) => keySystemIdToKeySystemDomain(pssh.systemId))\n .join(',')} pssh data in favor of playlist keys`,\n );\n }\n return;\n }\n keySystemDomain = keySystemIdToKeySystemDomain(psshInfo.systemId);\n if (psshInfo.version === 0 && psshInfo.data) {\n const offset = psshInfo.data.length - 22;\n keyId = psshInfo.data.subarray(offset, offset + 16);\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.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 if (decryptdata.pssh) {\n break;\n }\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 const onmessage = (context._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 const onkeystatuseschange = (context._onkeystatuseschange = (\n event: Event,\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 context.mediaKeysSession.addEventListener('message', onmessage);\n context.mediaKeysSession.addEventListener(\n 'keystatuseschange',\n onkeystatuseschange,\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 server certificate 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 unpackPlayReadyKeyMessage(\n xhr: XMLHttpRequest,\n licenseChallenge: Uint8Array,\n ): Uint8Array {\n // On Edge, the raw license message is UTF-16-encoded XML. We need\n // to unpack the Challenge element (base64-encoded string containing the\n // actual license request) and any HttpHeader elements (sent as request\n // headers).\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n const xmlString = String.fromCharCode.apply(\n null,\n new Uint16Array(licenseChallenge.buffer),\n );\n if (!xmlString.includes('PlayReadyKeyMessage')) {\n // This does not appear to be a wrapped message as on Edge. Some\n // clients do not need this unwrapping, so we will assume this is one of\n // them. Note that \"xml\" at this point probably looks like random\n // garbage, since we interpreted UTF-8 as UTF-16.\n xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');\n return licenseChallenge;\n }\n const keyMessageXml = new DOMParser().parseFromString(\n xmlString,\n 'application/xml',\n );\n // Set request headers.\n const headers = keyMessageXml.querySelectorAll('HttpHeader');\n if (headers.length > 0) {\n let header: Element;\n for (let i = 0, len = headers.length; i < len; i++) {\n header = headers[i];\n const name = header.querySelector('name')?.textContent;\n const value = header.querySelector('value')?.textContent;\n if (name && value) {\n xhr.setRequestHeader(name, value);\n }\n }\n }\n const challengeElement = keyMessageXml.querySelector('Challenge');\n const challengeText = challengeElement?.textContent;\n if (!challengeText) {\n throw new Error(`Cannot find <Challenge> in key message`);\n }\n return strToUtf8array(atob(challengeText));\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 if (keySessionContext.keySystem == KeySystems.PLAYREADY) {\n licenseChallenge = this.unpackPlayReadyKeyMessage(\n xhr,\n licenseChallenge,\n );\n }\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(`Could not clear media keys: ${error}`);\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(`Could not close sessions and clear media keys: ${error}`);\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 if (mediaKeySessionContext._onmessage) {\n mediaKeysSession.removeEventListener(\n 'message',\n mediaKeySessionContext._onmessage,\n );\n mediaKeySessionContext._onmessage = undefined;\n }\n if (mediaKeySessionContext._onkeystatuseschange) {\n mediaKeysSession.removeEventListener(\n 'keystatuseschange',\n mediaKeySessionContext._onkeystatuseschange,\n );\n mediaKeySessionContext._onkeystatuseschange = undefined;\n }\n\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 * Common Media Object Type\n *\n * @group CMCD\n * @group CMSD\n *\n * @beta\n */\nexport var CmObjectType;\n(function (CmObjectType) {\n /**\n * text file, such as a manifest or playlist\n */\n CmObjectType[\"MANIFEST\"] = \"m\";\n /**\n * audio only\n */\n CmObjectType[\"AUDIO\"] = \"a\";\n /**\n * video only\n */\n CmObjectType[\"VIDEO\"] = \"v\";\n /**\n * muxed audio and video\n */\n CmObjectType[\"MUXED\"] = \"av\";\n /**\n * init segment\n */\n CmObjectType[\"INIT\"] = \"i\";\n /**\n * caption or subtitle\n */\n CmObjectType[\"CAPTION\"] = \"c\";\n /**\n * ISOBMFF timed text track\n */\n CmObjectType[\"TIMED_TEXT\"] = \"tt\";\n /**\n * cryptographic key, license or certificate.\n */\n CmObjectType[\"KEY\"] = \"k\";\n /**\n * other\n */\n CmObjectType[\"OTHER\"] = \"o\";\n})(CmObjectType || (CmObjectType = {}));\n//# sourceMappingURL=CmObjectType.js.map","/**\n * Common Media Streaming Format\n *\n * @group CMCD\n * @group CMSD\n *\n * @beta\n */\nexport var CmStreamingFormat;\n(function (CmStreamingFormat) {\n /**\n * MPEG DASH\n */\n CmStreamingFormat[\"DASH\"] = \"d\";\n /**\n * HTTP Live Streaming (HLS)\n */\n CmStreamingFormat[\"HLS\"] = \"h\";\n /**\n * Smooth Streaming\n */\n CmStreamingFormat[\"SMOOTH\"] = \"s\";\n /**\n * Other\n */\n CmStreamingFormat[\"OTHER\"] = \"o\";\n})(CmStreamingFormat || (CmStreamingFormat = {}));\n//# sourceMappingURL=CmStreamingFormat.js.map","/**\n * CMCD header fields.\n *\n * @group CMCD\n *\n * @beta\n */\nexport var CmcdHeaderField;\n(function (CmcdHeaderField) {\n /**\n * keys whose values vary with the object being requested.\n */\n CmcdHeaderField[\"OBJECT\"] = \"CMCD-Object\";\n /**\n * keys whose values vary with each request.\n */\n CmcdHeaderField[\"REQUEST\"] = \"CMCD-Request\";\n /**\n * keys whose values are expected to be invariant over the life of the session.\n */\n CmcdHeaderField[\"SESSION\"] = \"CMCD-Session\";\n /**\n * keys whose values do not vary with every request or object.\n */\n CmcdHeaderField[\"STATUS\"] = \"CMCD-Status\";\n})(CmcdHeaderField || (CmcdHeaderField = {}));\n//# sourceMappingURL=CmcdHeaderField.js.map","import { CmcdHeaderField } from './CmcdHeaderField.js';\n/**\n * The map of CMCD header fields to official CMCD keys.\n *\n * @internal\n *\n * @group CMCD\n */\nexport const CmcdHeaderMap = {\n [CmcdHeaderField.OBJECT]: ['br', 'd', 'ot', 'tb'],\n [CmcdHeaderField.REQUEST]: ['bl', 'dl', 'mtp', 'nor', 'nrr', 'su'],\n [CmcdHeaderField.SESSION]: ['cid', 'pr', 'sf', 'sid', 'st', 'v'],\n [CmcdHeaderField.STATUS]: ['bs', 'rtp'],\n};\n//# sourceMappingURL=CmcdHeaderMap.js.map","/**\n * Structured Field Item\n *\n * @group Structured Field\n *\n * @beta\n */\nexport class SfItem {\n value;\n params;\n constructor(value, params) {\n if (Array.isArray(value)) {\n value = value.map((v) => (v instanceof SfItem) ? v : new SfItem(v));\n }\n this.value = value;\n this.params = params;\n }\n}\n//# sourceMappingURL=SfItem.js.map","/**\n * A class to represent structured field tokens when `Symbol` is not available.\n *\n * @group Structured Field\n *\n * @beta\n */\nexport class SfToken {\n description;\n constructor(description) {\n this.description = description;\n }\n}\n//# sourceMappingURL=SfToken.js.map","export const DICT = 'Dict';\n//# sourceMappingURL=DICT.js.map","function format(value) {\n if (Array.isArray(value)) {\n return JSON.stringify(value);\n }\n if (value instanceof Map) {\n return 'Map{}';\n }\n if (value instanceof Set) {\n return 'Set{}';\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return String(value);\n}\nexport function throwError(action, src, type, cause) {\n return new Error(`failed to ${action} \"${format(src)}\" as ${type}`, { cause });\n}\n//# sourceMappingURL=throwError.js.map","export const BARE_ITEM = 'Bare Item';\n//# sourceMappingURL=BARE_ITEM.js.map","export const BOOLEAN = 'Boolean';\n//# sourceMappingURL=BOOLEAN.js.map","export const BYTES = 'Byte Sequence';\n//# sourceMappingURL=BYTES.js.map","export const DECIMAL = 'Decimal';\n//# sourceMappingURL=DECIMAL.js.map","export const INTEGER = 'Integer';\n//# sourceMappingURL=INTEGER.js.map","export const STRING_REGEX = /[\\x00-\\x1f\\x7f]+/; // eslint-disable-line no-control-regex\n//# sourceMappingURL=STRING_REGEX.js.map","export const TOKEN = 'Token';\n//# sourceMappingURL=TOKEN.js.map","export const KEY = 'Key';\n//# sourceMappingURL=KEY.js.map","import { throwError } from '../utils/throwError.js';\nexport function serializeError(src, type, cause) {\n return throwError('serialize', src, type, cause);\n}\n//# sourceMappingURL=serializeError.js.map","import { base64encode } from '../../utils/base64encode.js';\nimport { BYTES } from '../utils/BYTES.js';\nimport { serializeError } from './serializeError.js';\n// 4.1.8. Serializing a Byte Sequence\n//\n// Given a Byte Sequence as input_bytes, return an ASCII string suitable\n// for use in a HTTP field value.\n//\n// 1. If input_bytes is not a sequence of bytes, fail serialization.\n//\n// 2. Let output be an empty string.\n//\n// 3. Append \":\" to output.\n//\n// 4. Append the result of base64-encoding input_bytes as per\n// [RFC4648], Section 4, taking account of the requirements below.\n//\n// 5. Append \":\" to output.\n//\n// 6. Return output.\n//\n// The encoded data is required to be padded with \"=\", as per [RFC4648],\n// Section 3.2.\n//\n// Likewise, encoded data SHOULD have pad bits set to zero, as per\n// [RFC4648], Section 3.5, unless it is not possible to do so due to\n// implementation constraints.\nexport function serializeByteSequence(value) {\n if (ArrayBuffer.isView(value) === false) {\n throw serializeError(value, BYTES);\n }\n return `:${base64encode(value)}:`;\n}\n//# sourceMappingURL=serializeByteSequence.js.map","/**\n * Encodes binary data to base64\n *\n * @param binary - The binary data to encode\n * @returns The base64 encoded string\n *\n * @group Utils\n *\n * @beta\n */\nexport function base64encode(binary) {\n return btoa(String.fromCharCode(...binary));\n}\n//# sourceMappingURL=base64encode.js.map","import { INTEGER } from '../utils/INTEGER.js';\nimport { isInvalidInt } from '../utils/isInvalidInt.js';\nimport { serializeError } from './serializeError.js';\n// 4.1.4. Serializing an Integer\n//\n// Given an Integer as input_integer, return an ASCII string suitable\n// for use in a HTTP field value.\n//\n// 1. If input_integer is not an integer in the range of\n// -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail\n// serialization.\n//\n// 2. Let output be an empty string.\n//\n// 3. If input_integer is less than (but not equal to) 0, append \"-\" to\n// output.\n//\n// 4. Append input_integer's numeric value represented in base 10 using\n// only decimal digits to output.\n//\n// 5. Return output.\nexport function serializeInteger(value) {\n if (isInvalidInt(value)) {\n throw serializeError(value, INTEGER);\n }\n return value.toString();\n}\n//# sourceMappingURL=serializeInteger.js.map","export function isInvalidInt(value) {\n return value < -999999999999999 || 999999999999999 < value;\n}\n//# sourceMappingURL=isInvalidInt.js.map","/**\n * This implements the rounding procedure described in step 2 of the \"Serializing a Decimal\" specification.\n * This rounding style is known as \"even rounding\", \"banker's rounding\", or \"commercial rounding\".\n *\n * @param value - The value to round\n * @param precision - The number of decimal places to round to\n * @returns The rounded value\n *\n * @group Utils\n *\n * @beta\n */\nexport function roundToEven(value, precision) {\n if (value < 0) {\n return -roundToEven(-value, precision);\n }\n const decimalShift = Math.pow(10, precision);\n const isEquidistant = Math.abs(((value * decimalShift) % 1) - 0.5) < Number.EPSILON;\n if (isEquidistant) {\n // If the tail of the decimal place is 'equidistant' we round to the nearest even value\n const flooredValue = Math.floor(value * decimalShift);\n return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;\n }\n else {\n // Otherwise, proceed as normal\n return Math.round(value * decimalShift) / decimalShift;\n }\n}\n//# sourceMappingURL=roundToEven.js.map","import { roundToEven } from '../../utils/roundToEven.js';\nimport { DECIMAL } from '../utils/DECIMAL.js';\nimport { serializeError } from './serializeError.js';\n// 4.1.5. Serializing a Decimal\n//\n// Given a decimal number as input_decimal, return an ASCII string\n// suitable for use in a HTTP field value.\n//\n// 1. If input_decimal is not a decimal number, fail serialization.\n//\n// 2. If input_decimal has more than three significant digits to the\n// right of the decimal point, round it to three decimal places,\n// rounding the final digit to the nearest value, or to the even\n// value if it is equidistant.\n//\n// 3. If input_decimal has more than 12 significant digits to the left\n// of the decimal point after rounding, fail serialization.\n//\n// 4. Let output be an empty string.\n//\n// 5. If input_decimal is less than (but not equal to) 0, append \"-\"\n// to output.\n//\n// 6. Append input_decimal's integer component represented in base 10\n// (using only decimal digits) to output; if it is zero, append\n// \"0\".\n//\n// 7. Append \".\" to output.\n//\n// 8. If input_decimal's fractional component is zero, append \"0\" to\n// output.\n//\n// 9. Otherwise, append the significant digits of input_decimal's\n// fractional component represented in base 10 (using only decimal\n// digits) to output.\n//\n// 10. Return output.\nexport function serializeDecimal(value) {\n const roundedValue = roundToEven(value, 3); // round to 3 decimal places\n if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {\n throw serializeError(value, DECIMAL);\n }\n const stringValue = roundedValue.toString();\n return stringValue.includes('.') ? stringValue : `${stringValue}.0`;\n}\n//# sourceMappingURL=serializeDecimal.js.map","export const STRING = 'String';\n//# sourceMappingURL=STRING.js.map","import { symbolToStr } from '../../cta/utils/symbolToStr.js';\nimport { TOKEN } from '../utils/TOKEN.js';\nimport { serializeError } from './serializeError.js';\nexport function serializeToken(token) {\n const value = symbolToStr(token);\n if (/^([a-zA-Z*])([!#$%&'*+\\-.^_`|~\\w:/]*)$/.test(value) === false) {\n throw serializeError(value, TOKEN);\n }\n return value;\n}\n//# sourceMappingURL=serializeToken.js.map","export function symbolToStr(symbol) {\n return symbol.description || symbol.toString().slice(7, -1);\n}\n//# sourceMappingURL=symbolToStr.js.map","import { SfToken } from '../SfToken.js';\nimport { BARE_ITEM } from '../utils/BARE_ITEM.js';\nimport { serializeBoolean } from './serializeBoolean.js';\nimport { serializeByteSequence } from './serializeByteSequence.js';\nimport { serializeDate } from './serializeDate.js';\nimport { serializeDecimal } from './serializeDecimal.js';\nimport { serializeError } from './serializeError.js';\nimport { serializeInteger } from './serializeInteger.js';\nimport { serializeString } from './serializeString.js';\nimport { serializeToken } from './serializeToken.js';\n// 4.1.3.1. Serializing a Bare Item\n//\n// Given an Item as input_item, return an ASCII string suitable for use\n// in a HTTP field value.\n//\n// 1. If input_item is an Integer, return the result of running\n// Serializing an Integer (Section 4.1.4) with input_item.\n//\n// 2. If input_item is a Decimal, return the result of running\n// Serializing a Decimal (Section 4.1.5) with input_item.\n//\n// 3. If input_item is a String, return the result of running\n// Serializing a String (Section 4.1.6) with input_item.\n//\n// 4. If input_item is a Token, return the result of running\n// Serializing a Token (Section 4.1.7) with input_item.\n//\n// 5. If input_item is a Boolean, return the result of running\n// Serializing a Boolean (Section 4.1.9) with input_item.\n//\n// 6. If input_item is a Byte Sequence, return the result of running\n// Serializing a Byte Sequence (Section 4.1.8) with input_item.\n//\n// 7. If input_item is a Date, return the result of running Serializing\n// a Date (Section 4.1.10) with input_item.\n//\n// 8. Otherwise, fail serialization.\nexport function serializeBareItem(value) {\n switch (typeof value) {\n case 'number':\n if (!Number.isFinite(value)) {\n throw serializeError(value, BARE_ITEM);\n }\n if (Number.isInteger(value)) {\n return serializeInteger(value);\n }\n return serializeDecimal(value);\n case 'string':\n return serializeString(value);\n case 'symbol':\n return serializeToken(value);\n case 'boolean':\n return serializeBoolean(value);\n case 'object':\n if (value instanceof Date) {\n return serializeDate(value);\n }\n if (value instanceof Uint8Array) {\n return serializeByteSequence(value);\n }\n if (value instanceof SfToken) {\n return serializeToken(value);\n }\n default:\n // fail\n throw serializeError(value, BARE_ITEM);\n }\n}\n//# sourceMappingURL=serializeBareItem.js.map","import { STRING } from '../utils/STRING.js';\nimport { STRING_REGEX } from '../utils/STRING_REGEX.js';\nimport { serializeError } from './serializeError.js';\n// 4.1.6. Serializing a String\n//\n// Given a String as input_string, return an ASCII string suitable for\n// use in a HTTP field value.\n//\n// 1. Convert input_string into a sequence of ASCII characters; if\n// conversion fails, fail serialization.\n//\n// 2. If input_string contains characters in the range %x00-1f or %x7f\n// (i.e., not in VCHAR or SP), fail serialization.\n//\n// 3. Let output be the string DQUOTE.\n//\n// 4. For each character char in input_string:\n//\n// 1. If char is \"\\\" or DQUOTE:\n//\n// 1. Append \"\\\" to output.\n//\n// 2. Append char to output.\n//\n// 5. Append DQUOTE to output.\n//\n// 6. Return output.\nexport function serializeString(value) {\n if (STRING_REGEX.test(value)) {\n throw serializeError(value, STRING);\n }\n return `\"${value.replace(/\\\\/g, `\\\\\\\\`).replace(/\"/g, `\\\\\"`)}\"`;\n}\n//# sourceMappingURL=serializeString.js.map","import { BOOLEAN } from '../utils/BOOLEAN.js';\nimport { serializeError } from './serializeError.js';\n// 4.1.9. Serializing a Boolean\n//\n// Given a Boolean as input_boolean, return an ASCII string suitable for\n// use in a HTTP field value.\n//\n// 1. If input_boolean is not a boolean, fail serialization.\n//\n// 2. Let output be an empty string.\n//\n// 3. Append \"?\" to output.\n//\n// 4. If input_boolean is true, append \"1\" to output.\n//\n// 5. If input_boolean is false, append \"0\" to output.\n//\n// 6. Return output.\nexport function serializeBoolean(value) {\n if (typeof value !== 'boolean') {\n throw serializeError(value, BOOLEAN);\n }\n return value ? '?1' : '?0';\n}\n//# sourceMappingURL=serializeBoolean.js.map","import { serializeInteger } from './serializeInteger.js';\n// 4.1.10. Serializing a Date\n//\n// Given a Date as input_integer, return an ASCII string suitable for\n// use in an HTTP field value.\n// 1. Let output be \"@\".\n// 2. Append to output the result of running Serializing an Integer\n// with input_date (Section 4.1.4).\n// 3. Return output.\nexport function serializeDate(value) {\n return `@${serializeInteger(value.getTime() / 1000)}`;\n}\n//# sourceMappingURL=serializeDate.js.map","import { KEY } from '../utils/KEY.js';\nimport { serializeError } from './serializeError.js';\n// 4.1.1.3. Serializing a Key\n//\n// Given a key as input_key, return an ASCII string suitable for use in\n// a HTTP field value.\n//\n// 1. Convert input_key into a sequence of ASCII characters; if\n// conversion fails, fail serialization.\n//\n// 2. If input_key contains characters not in lcalpha, DIGIT, \"_\", \"-\",\n// \".\", or \"*\" fail serialization.\n//\n// 3. If the first character of input_key is not lcalpha or \"*\", fail\n// serialization.\n//\n// 4. Let output be an empty string.\n//\n// 5. Append input_key to output.\n//\n// 6. Return output.\nexport function serializeKey(value) {\n if (/^[a-z*][a-z0-9\\-_.*]*$/.test(value) === false) {\n throw serializeError(value, KEY);\n }\n return value;\n}\n//# sourceMappingURL=serializeKey.js.map","import { serializeBareItem } from './serializeBareItem.js';\nimport { serializeKey } from './serializeKey.js';\n// 4.1.1.2. Serializing Parameters\n//\n// Given an ordered Dictionary as input_parameters (each member having a\n// param_name and a param_value), return an ASCII string suitable for\n// use in a HTTP field value.\n//\n// 1. Let output be an empty string.\n//\n// 2. For each param_name with a value of param_value in\n// input_parameters:\n//\n// 1. Append \";\" to output.\n//\n// 2. Append the result of running Serializing a Key\n// (Section 4.1.1.3) with param_name to output.\n//\n// 3. If param_value is not Boolean true:\n//\n// 1. Append \"=\" to output.\n//\n// 2. Append the result of running Serializing a bare Item\n// (Section 4.1.3.1) with param_value to output.\n//\n// 3. Return output.\nexport function serializeParams(params) {\n if (params == null) {\n return '';\n }\n return Object.entries(params)\n .map(([key, value]) => {\n if (value === true) {\n return `;${serializeKey(key)}`; // omit true\n }\n return `;${serializeKey(key)}=${serializeBareItem(value)}`;\n })\n .join('');\n}\n//# sourceMappingURL=serializeParams.js.map","import { SfItem } from '../SfItem.js';\nimport { serializeBareItem } from './serializeBareItem.js';\nimport { serializeParams } from './serializeParams.js';\n// 4.1.3. Serializing an Item\n//\n// Given an Item as bare_item and Parameters as item_parameters, return\n// an ASCII string suitable for use in a HTTP field value.\n//\n// 1. Let output be an empty string.\n//\n// 2. Append the result of running Serializing a Bare Item\n// Section 4.1.3.1 with bare_item to output.\n//\n// 3. Append the result of running Serializing Parameters\n// Section 4.1.1.2 with item_parameters to output.\n//\n// 4. Return output.\nexport function serializeItem(value) {\n if (value instanceof SfItem) {\n return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;\n }\n else {\n return serializeBareItem(value);\n }\n}\n//# sourceMappingURL=serializeItem.js.map","import { SfItem } from '../SfItem.js';\nimport { DICT } from '../utils/DICT.js';\nimport { serializeError } from './serializeError.js';\nimport { serializeInnerList } from './serializeInnerList.js';\nimport { serializeItem } from './serializeItem.js';\nimport { serializeKey } from './serializeKey.js';\nimport { serializeParams } from './serializeParams.js';\n// 4.1.2. Serializing a Dictionary\n//\n// Given an ordered Dictionary as input_dictionary (each member having a\n// member_name and a tuple value of (member_value, parameters)), return\n// an ASCII string suitable for use in a HTTP field value.\n//\n// 1. Let output be an empty string.\n//\n// 2. For each member_name with a value of (member_value, parameters)\n// in input_dictionary:\n//\n// 1. Append the result of running Serializing a Key\n// (Section 4.1.1.3) with member's member_name to output.\n//\n// 2. If member_value is Boolean true:\n//\n// 1. Append the result of running Serializing Parameters\n// (Section 4.1.1.2) with parameters to output.\n//\n// 3. Otherwise:\n//\n// 1. Append \"=\" to output.\n//\n// 2. If member_value is an array, append the result of running\n// Serializing an Inner List (Section 4.1.1.1) with\n// (member_value, parameters) to output.\n//\n// 3. Otherwise, append the result of running Serializing an\n// Item (Section 4.1.3) with (member_value, parameters) to\n// output.\n//\n// 4. If more members remain in input_dictionary:\n//\n// 1. Append \",\" to output.\n//\n// 2. Append a single SP to output.\n//\n// 3. Return output.\nexport function serializeDict(dict, options = { whitespace: true }) {\n if (typeof dict !== 'object') {\n throw serializeError(dict, DICT);\n }\n const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);\n const optionalWhiteSpace = options?.whitespace ? ' ' : '';\n return Array.from(entries)\n .map(([key, item]) => {\n if (item instanceof SfItem === false) {\n item = new SfItem(item);\n }\n let output = serializeKey(key);\n if (item.value === true) {\n output += serializeParams(item.params);\n }\n else {\n output += '=';\n if (Array.isArray(item.value)) {\n output += serializeInnerList(item);\n }\n else {\n output += serializeItem(item);\n }\n }\n return output;\n })\n .join(`,${optionalWhiteSpace}`);\n}\n//# sourceMappingURL=serializeDict.js.map","import { serializeItem } from './serializeItem.js';\nimport { serializeParams } from './serializeParams.js';\n// 4.1.1.1. Serializing an Inner List\n//\n// Given an array of (member_value, parameters) tuples as inner_list,\n// and parameters as list_parameters, return an ASCII string suitable\n// for use in a HTTP field value.\n//\n// 1. Let output be the string \"(\".\n//\n// 2. For each (member_value, parameters) of inner_list:\n//\n// 1. Append the result of running Serializing an Item\n// (Section 4.1.3) with (member_value, parameters) to output.\n//\n// 2. If more values remain in inner_list, append a single SP to\n// output.\n//\n// 3. Append \")\" to output.\n//\n// 4. Append the result of running Serializing Parameters\n// (Section 4.1.1.2) with list_parameters to output.\n//\n// 5. Return output.\nexport function serializeInnerList(value) {\n return `(${value.value.map(serializeItem).join(' ')})${serializeParams(value.params)}`;\n}\n//# sourceMappingURL=serializeInnerList.js.map","/**\n * Checks if the given key is a token field.\n *\n * @param key - The key to check.\n *\n * @returns `true` if the key is a token field.\n *\n * @internal\n *\n * @group CMCD\n */\nexport const isTokenField = (key) => key === 'ot' || key === 'sf' || key === 'st';\n//# sourceMappingURL=isTokenField.js.map","export const isValid = (value) => {\n if (typeof value === 'number') {\n return Number.isFinite(value);\n }\n return value != null && value !== '' && value !== false;\n};\n//# sourceMappingURL=isValid.js.map","import { urlToRelativePath } from '../utils.js';\nconst toRounded = (value) => Math.round(value);\nconst toUrlSafe = (value, options) => {\n if (options?.baseUrl) {\n value = urlToRelativePath(value, options.baseUrl);\n }\n return encodeURIComponent(value);\n};\nconst toHundred = (value) => toRounded(value / 100) * 100;\n/**\n * The default formatters for CMCD values.\n *\n * @group CMCD\n *\n * @beta\n */\nexport const CmcdFormatters = {\n /**\n * Bitrate (kbps) rounded integer\n */\n br: toRounded,\n /**\n * Duration (milliseconds) rounded integer\n */\n d: toRounded,\n /**\n * Buffer Length (milliseconds) rounded nearest 100ms\n */\n bl: toHundred,\n /**\n * Deadline (milliseconds) rounded nearest 100ms\n */\n dl: toHundred,\n /**\n * Measured Throughput (kbps) rounded nearest 100kbps\n */\n mtp: toHundred,\n /**\n * Next Object Request URL encoded\n */\n nor: toUrlSafe,\n /**\n * Requested maximum throughput (kbps) rounded nearest 100kbps\n */\n rtp: toHundred,\n /**\n * Top Bitrate (kbps) rounded integer\n */\n tb: toRounded,\n};\n//# sourceMappingURL=CmcdFormatters.js.map","/**\n * Constructs a relative path from a URL.\n *\n * @param url - The destination URL\n * @param base - The base URL\n * @returns The relative path\n *\n * @group Utils\n *\n * @beta\n */\nexport function urlToRelativePath(url, base) {\n const to = new URL(url);\n const from = new URL(base);\n if (to.origin !== from.origin) {\n return url;\n }\n const toPath = to.pathname.split('/').slice(1);\n const fromPath = from.pathname.split('/').slice(1, -1);\n // remove common parents\n while (toPath[0] === fromPath[0]) {\n toPath.shift();\n fromPath.shift();\n }\n // add back paths\n while (fromPath.length) {\n fromPath.shift();\n toPath.unshift('..');\n }\n return toPath.join('/');\n}\n//# sourceMappingURL=urlToRelativePath.js.map","import { encodeSfDict } from '../structuredfield.js';\nimport { processCmcd } from './utils/processCmcd.js';\n/**\n * Encode a CMCD object to a string.\n *\n * @param cmcd - The CMCD object to encode.\n * @param options - Options for encoding.\n *\n * @returns The encoded CMCD string.\n *\n * @group CMCD\n *\n * @beta\n */\nexport function encodeCmcd(cmcd, options = {}) {\n if (!cmcd) {\n return '';\n }\n return encodeSfDict(processCmcd(cmcd, options), Object.assign({ whitespace: false }, options));\n}\n//# sourceMappingURL=encodeCmcd.js.map","import { serializeDict } from './serialize/serializeDict.js';\n/**\n * Encode an object into a structured field dictionary\n *\n * @param input - The structured field dictionary to encode\n * @returns The structured field string\n *\n * @group Structured Field\n *\n * @beta\n */\nexport function encodeSfDict(value, options) {\n return serializeDict(value, options);\n}\n//# sourceMappingURL=encodeSfDict.js.map","import { isTokenField } from '../../cta/utils/isTokenField.js';\nimport { isValid } from '../../cta/utils/isValid.js';\nimport { SfToken } from '../../structuredfield/SfToken.js';\nimport { CmcdFormatters } from '../CmcdFormatters.js';\n/**\n * Internal CMCD processing function.\n *\n * @param obj - The CMCD object to process.\n * @param map - The mapping function to use.\n * @param options - Options for encoding.\n *\n * @internal\n *\n * @group CMCD\n */\nexport function processCmcd(obj, options) {\n const results = {};\n if (obj == null || typeof obj !== 'object') {\n return results;\n }\n const keys = Object.keys(obj).sort();\n const formatters = Object.assign({}, CmcdFormatters, options?.formatters);\n const filter = options?.filter;\n keys.forEach(key => {\n if (filter?.(key)) {\n return;\n }\n let value = obj[key];\n const formatter = formatters[key];\n if (formatter) {\n value = formatter(value, options);\n }\n // Version should only be reported if not equal to 1.\n if (key === 'v' && value === 1) {\n return;\n }\n // Playback rate should only be sent if not equal to 1.\n if (key == 'pr' && value === 1) {\n return;\n }\n // ignore invalid values\n if (!isValid(value)) {\n return;\n }\n if (isTokenField(key) && typeof value === 'string') {\n value = new SfToken(value);\n }\n results[key] = value;\n });\n return results;\n}\n//# sourceMappingURL=processCmcd.js.map","import { toCmcdHeaders } from './toCmcdHeaders.js';\n/**\n * Append CMCD query args to a header object.\n *\n * @param headers - The headers to append to.\n * @param cmcd - The CMCD object to append.\n * @param customHeaderMap - A map of custom CMCD keys to header fields.\n *\n * @returns The headers with the CMCD header shards appended.\n *\n * @group CMCD\n *\n * @beta\n */\nexport function appendCmcdHeaders(headers, cmcd, options) {\n return Object.assign(headers, toCmcdHeaders(cmcd, options));\n}\n//# sourceMappingURL=appendCmcdHeaders.js.map","import { CmcdHeaderField } from './CmcdHeaderField.js';\nimport { CmcdHeaderMap } from './CmcdHeaderMap.js';\nimport { encodeCmcd } from './encodeCmcd.js';\n/**\n * Convert a CMCD data object to request headers\n *\n * @param cmcd - The CMCD data object to convert.\n * @param options - Options for encoding the CMCD object.\n *\n * @returns The CMCD header shards.\n *\n * @group CMCD\n *\n * @beta\n */\nexport function toCmcdHeaders(cmcd, options = {}) {\n if (!cmcd) {\n return {};\n }\n const entries = Object.entries(cmcd);\n const headerMap = Object.entries(CmcdHeaderMap)\n .concat(Object.entries(options?.customHeaderMap || {}));\n const shards = entries.reduce((acc, entry) => {\n const [key, value] = entry;\n const field = headerMap.find(entry => entry[1].includes(key))?.[0] || CmcdHeaderField.REQUEST;\n acc[field] ??= {};\n acc[field][key] = value;\n return acc;\n }, {});\n return Object.entries(shards)\n .reduce((acc, [field, value]) => {\n acc[field] = encodeCmcd(value, options);\n return acc;\n }, {});\n}\n//# sourceMappingURL=toCmcdHeaders.js.map","/**\n * CMCD parameter name.\n *\n * @group CMCD\n *\n * @beta\n */\nexport const CMCD_PARAM = 'CMCD';\n//# sourceMappingURL=CMCD_PARAM.js.map","import { toCmcdQuery } from './toCmcdQuery.js';\nconst REGEX = /CMCD=[^&#]+/;\n/**\n * Append CMCD query args to a URL.\n *\n * @param url - The URL to append to.\n * @param cmcd - The CMCD object to append.\n * @param options - Options for encoding the CMCD object.\n *\n * @returns The URL with the CMCD query args appended.\n *\n * @group CMCD\n *\n * @beta\n */\nexport function appendCmcdQuery(url, cmcd, options) {\n // TODO: Replace with URLSearchParams once we drop Safari < 10.1 & Chrome < 49 support.\n // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\n const query = toCmcdQuery(cmcd, options);\n if (!query) {\n return url;\n }\n if (REGEX.test(url)) {\n return url.replace(REGEX, query);\n }\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}${query}`;\n}\n//# sourceMappingURL=appendCmcdQuery.js.map","import { CMCD_PARAM } from './CMCD_PARAM.js';\nimport { encodeCmcd } from './encodeCmcd.js';\n/**\n * Convert a CMCD data object to a query arg.\n *\n * @param cmcd - The CMCD object to convert.\n * @param options - Options for encoding the CMCD object.\n *\n * @returns The CMCD query arg.\n *\n * @group CMCD\n *\n * @beta\n */\nexport function toCmcdQuery(cmcd, options = {}) {\n if (!cmcd) {\n return '';\n }\n const params = encodeCmcd(cmcd, options);\n return `${CMCD_PARAM}=${encodeURIComponent(params)}`;\n}\n//# sourceMappingURL=toCmcdQuery.js.map","import { Events } from '../events';\nimport Hls from '../hls';\nimport { Cmcd } from '@svta/common-media-library/cmcd/Cmcd';\nimport { CmcdObjectType } from '@svta/common-media-library/cmcd/CmcdObjectType';\nimport { CmcdStreamingFormat } from '@svta/common-media-library/cmcd/CmcdStreamingFormat';\nimport { appendCmcdHeaders } from '@svta/common-media-library/cmcd/appendCmcdHeaders';\nimport { appendCmcdQuery } from '@svta/common-media-library/cmcd/appendCmcdQuery';\nimport { uuid } from '@svta/common-media-library/utils/uuid';\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 includeKeys?: string[];\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 || uuid();\n this.cid = cmcd.contentId;\n this.useHeaders = cmcd.useHeaders === true;\n this.includeKeys = cmcd.includeKeys;\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 // @ts-ignore\n this.onWaiting = this.onPlaying = 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: 1,\n sf: CmcdStreamingFormat.HLS,\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 const { includeKeys } = this;\n if (includeKeys) {\n data = Object.keys(data).reduce((acc, key) => {\n includeKeys.includes(key) && (acc[key] = data[key]);\n return acc;\n }, {});\n }\n\n if (this.useHeaders) {\n if (!context.headers) {\n context.headers = {};\n }\n\n appendCmcdHeaders(context.headers, data);\n } else {\n context.url = appendCmcdQuery(context.url, data);\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 UUID\n *\n * @returns A random v4 UUID\n *\n * @group Utils\n *\n * @beta\n */\nexport function uuid() {\n try {\n return crypto.randomUUID();\n }\n catch (error) {\n try {\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 catch (error) {\n let dt = new Date().getTime();\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (dt + Math.random() * 16) % 16 | 0;\n dt = Math.floor(dt / 16);\n return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);\n });\n return uuid;\n }\n }\n}\n//# sourceMappingURL=uuid.js.map","import { Events } from '../events';\nimport { Level } from '../types/level';\nimport { reassignFragmentLevelIndexes } from '../utils/level-helper';\nimport { AttrList } from '../utils/attr-list';\nimport { ErrorActionFlags, NetworkErrorAction } from './error-controller';\nimport { logger } from '../utils/logger';\nimport {\n PlaylistContextType,\n type Loader,\n type LoaderCallbacks,\n type LoaderConfiguration,\n type LoaderContext,\n type LoaderResponse,\n type LoaderStats,\n} from '../types/loader';\nimport type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type {\n SteeringManifestLoadedData,\n ErrorData,\n ManifestLoadedData,\n ManifestParsedData,\n} from '../types/events';\nimport type { RetryConfig } from '../config';\n\nimport type { MediaAttributes, MediaPlaylist } from '../types/media-playlist';\n\nexport type SteeringManifest = {\n VERSION: 1;\n TTL: number;\n 'RELOAD-URI'?: string;\n 'PATHWAY-PRIORITY': string[];\n 'PATHWAY-CLONES'?: PathwayClone[];\n};\n\nexport type PathwayClone = {\n 'BASE-ID': string;\n ID: string;\n 'URI-REPLACEMENT': UriReplacement;\n};\n\nexport type UriReplacement = {\n HOST?: string;\n PARAMS?: { [queryParameter: string]: string };\n 'PER-VARIANT-URIS'?: { [stableVariantId: string]: string };\n 'PER-RENDITION-URIS'?: { [stableRenditionId: string]: string };\n};\n\nconst PATHWAY_PENALTY_DURATION_MS = 300000;\n\nexport default class ContentSteeringController implements NetworkComponentAPI {\n private readonly hls: Hls;\n private log: (msg: any) => void;\n private loader: Loader<LoaderContext> | null = null;\n private uri: string | null = null;\n private pathwayId: string = '.';\n private pathwayPriority: string[] | null = null;\n private timeToLoad: number = 300;\n private reloadTimer: number = -1;\n private updated: number = 0;\n private started: boolean = false;\n private enabled: boolean = true;\n private levels: Level[] | null = null;\n private audioTracks: MediaPlaylist[] | null = null;\n private subtitleTracks: MediaPlaylist[] | null = null;\n private penalizedPathways: { [pathwayId: string]: number } = {};\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.log = logger.log.bind(logger, `[content-steering]:`);\n this.registerListeners();\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n startLoad() {\n this.started = true;\n this.clearTimeout();\n if (this.enabled && this.uri) {\n if (this.updated) {\n const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);\n if (ttl > 0) {\n this.scheduleRefresh(this.uri, ttl);\n return;\n }\n }\n this.loadSteeringManifest(this.uri);\n }\n }\n\n stopLoad() {\n this.started = false;\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n this.clearTimeout();\n }\n\n clearTimeout() {\n if (this.reloadTimer !== -1) {\n self.clearTimeout(this.reloadTimer);\n this.reloadTimer = -1;\n }\n }\n\n destroy() {\n this.unregisterListeners();\n this.stopLoad();\n // @ts-ignore\n this.hls = null;\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n\n removeLevel(levelToRemove: Level) {\n const levels = this.levels;\n if (levels) {\n this.levels = levels.filter((level) => level !== levelToRemove);\n }\n }\n\n private onManifestLoading() {\n this.stopLoad();\n this.enabled = true;\n this.timeToLoad = 300;\n this.updated = 0;\n this.uri = null;\n this.pathwayId = '.';\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ) {\n const { contentSteering } = data;\n if (contentSteering === null) {\n return;\n }\n this.pathwayId = contentSteering.pathwayId;\n this.uri = contentSteering.uri;\n if (this.started) {\n this.startLoad();\n }\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n this.audioTracks = data.audioTracks;\n this.subtitleTracks = data.subtitleTracks;\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n const { errorAction } = data;\n if (\n errorAction?.action === NetworkErrorAction.SendAlternateToPenaltyBox &&\n errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost\n ) {\n const levels = this.levels;\n let pathwayPriority = this.pathwayPriority;\n let errorPathway = this.pathwayId;\n if (data.context) {\n const { groupId, pathwayId, type } = data.context;\n if (groupId && levels) {\n errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);\n } else if (pathwayId) {\n errorPathway = pathwayId;\n }\n }\n if (!(errorPathway in this.penalizedPathways)) {\n this.penalizedPathways[errorPathway] = performance.now();\n }\n if (!pathwayPriority && levels) {\n // If PATHWAY-PRIORITY was not provided, list pathways for error handling\n pathwayPriority = levels.reduce((pathways, level) => {\n if (pathways.indexOf(level.pathwayId) === -1) {\n pathways.push(level.pathwayId);\n }\n return pathways;\n }, [] as string[]);\n }\n if (pathwayPriority && pathwayPriority.length > 1) {\n this.updatePathwayPriority(pathwayPriority);\n errorAction.resolved = this.pathwayId !== errorPathway;\n }\n if (!errorAction.resolved) {\n logger.warn(\n `Could not resolve ${data.details} (\"${\n data.error.message\n }\") with content-steering for Pathway: ${errorPathway} levels: ${\n levels ? levels.length : levels\n } priorities: ${JSON.stringify(\n pathwayPriority,\n )} penalized: ${JSON.stringify(this.penalizedPathways)}`,\n );\n }\n }\n }\n\n public filterParsedLevels(levels: Level[]): Level[] {\n // Filter levels to only include those that are in the initial pathway\n this.levels = levels;\n let pathwayLevels = this.getLevelsForPathway(this.pathwayId);\n if (pathwayLevels.length === 0) {\n const pathwayId = levels[0].pathwayId;\n this.log(\n `No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to \"${pathwayId}\"`,\n );\n pathwayLevels = this.getLevelsForPathway(pathwayId);\n this.pathwayId = pathwayId;\n }\n if (pathwayLevels.length !== levels.length) {\n this.log(\n `Found ${pathwayLevels.length}/${levels.length} levels in Pathway \"${this.pathwayId}\"`,\n );\n return pathwayLevels;\n }\n return levels;\n }\n\n private getLevelsForPathway(pathwayId: string): Level[] {\n if (this.levels === null) {\n return [];\n }\n return this.levels.filter((level) => pathwayId === level.pathwayId);\n }\n\n private updatePathwayPriority(pathwayPriority: string[]) {\n this.pathwayPriority = pathwayPriority;\n let levels: Level[] | undefined;\n\n // Evaluate if we should remove the pathway from the penalized list\n const penalizedPathways = this.penalizedPathways;\n const now = performance.now();\n Object.keys(penalizedPathways).forEach((pathwayId) => {\n if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {\n delete penalizedPathways[pathwayId];\n }\n });\n for (let i = 0; i < pathwayPriority.length; i++) {\n const pathwayId = pathwayPriority[i];\n if (pathwayId in penalizedPathways) {\n continue;\n }\n if (pathwayId === this.pathwayId) {\n return;\n }\n const selectedIndex = this.hls.nextLoadLevel;\n const selectedLevel: Level = this.hls.levels[selectedIndex];\n levels = this.getLevelsForPathway(pathwayId);\n if (levels.length > 0) {\n this.log(`Setting Pathway to \"${pathwayId}\"`);\n this.pathwayId = pathwayId;\n reassignFragmentLevelIndexes(levels);\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed\n const levelAfterChange = this.hls.levels[selectedIndex];\n if (selectedLevel && levelAfterChange && this.levels) {\n if (\n levelAfterChange.attrs['STABLE-VARIANT-ID'] !==\n selectedLevel.attrs['STABLE-VARIANT-ID'] &&\n levelAfterChange.bitrate !== selectedLevel.bitrate\n ) {\n this.log(\n `Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`,\n );\n }\n this.hls.nextLoadLevel = selectedIndex;\n }\n break;\n }\n }\n }\n\n private getPathwayForGroupId(\n groupId: string,\n type: PlaylistContextType,\n defaultPathway: string,\n ): string {\n const levels = this.getLevelsForPathway(defaultPathway).concat(\n this.levels || [],\n );\n for (let i = 0; i < levels.length; i++) {\n if (\n (type === PlaylistContextType.AUDIO_TRACK &&\n levels[i].hasAudioGroup(groupId)) ||\n (type === PlaylistContextType.SUBTITLE_TRACK &&\n levels[i].hasSubtitleGroup(groupId))\n ) {\n return levels[i].pathwayId;\n }\n }\n return defaultPathway;\n }\n\n private clonePathways(pathwayClones: PathwayClone[]) {\n const levels = this.levels;\n if (!levels) {\n return;\n }\n const audioGroupCloneMap: Record<string, string> = {};\n const subtitleGroupCloneMap: Record<string, string> = {};\n pathwayClones.forEach((pathwayClone) => {\n const {\n ID: cloneId,\n 'BASE-ID': baseId,\n 'URI-REPLACEMENT': uriReplacement,\n } = pathwayClone;\n if (levels.some((level) => level.pathwayId === cloneId)) {\n return;\n }\n const clonedVariants = this.getLevelsForPathway(baseId).map(\n (baseLevel) => {\n const attributes = new AttrList(baseLevel.attrs);\n attributes['PATHWAY-ID'] = cloneId;\n const clonedAudioGroupId: string | undefined =\n attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;\n const clonedSubtitleGroupId: string | undefined =\n attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;\n if (clonedAudioGroupId) {\n audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;\n attributes.AUDIO = clonedAudioGroupId;\n }\n if (clonedSubtitleGroupId) {\n subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;\n attributes.SUBTITLES = clonedSubtitleGroupId;\n }\n const url = performUriReplacement(\n baseLevel.uri,\n attributes['STABLE-VARIANT-ID'],\n 'PER-VARIANT-URIS',\n uriReplacement,\n );\n const clonedLevel = new Level({\n attrs: attributes,\n audioCodec: baseLevel.audioCodec,\n bitrate: baseLevel.bitrate,\n height: baseLevel.height,\n name: baseLevel.name,\n url,\n videoCodec: baseLevel.videoCodec,\n width: baseLevel.width,\n });\n if (baseLevel.audioGroups) {\n for (let i = 1; i < baseLevel.audioGroups.length; i++) {\n clonedLevel.addGroupId(\n 'audio',\n `${baseLevel.audioGroups[i]}_clone_${cloneId}`,\n );\n }\n }\n if (baseLevel.subtitleGroups) {\n for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {\n clonedLevel.addGroupId(\n 'text',\n `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`,\n );\n }\n }\n return clonedLevel;\n },\n );\n levels.push(...clonedVariants);\n cloneRenditionGroups(\n this.audioTracks,\n audioGroupCloneMap,\n uriReplacement,\n cloneId,\n );\n cloneRenditionGroups(\n this.subtitleTracks,\n subtitleGroupCloneMap,\n uriReplacement,\n cloneId,\n );\n });\n }\n\n private loadSteeringManifest(uri: string) {\n const config = this.hls.config;\n const Loader = config.loader;\n if (this.loader) {\n this.loader.destroy();\n }\n this.loader = new Loader(config) as Loader<LoaderContext>;\n\n let url: URL;\n try {\n url = new self.URL(uri);\n } catch (error) {\n this.enabled = false;\n this.log(`Failed to parse Steering Manifest URI: ${uri}`);\n return;\n }\n if (url.protocol !== 'data:') {\n const throughput =\n (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;\n url.searchParams.set('_HLS_pathway', this.pathwayId);\n url.searchParams.set('_HLS_throughput', '' + throughput);\n }\n const context: LoaderContext = {\n responseType: 'json',\n url: url.href,\n };\n\n const loadPolicy = config.steeringManifestLoadPolicy.default;\n const legacyRetryCompatibility: RetryConfig | Record<string, void> =\n loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0,\n };\n\n const callbacks: LoaderCallbacks<LoaderContext> = {\n onSuccess: (\n response: LoaderResponse,\n stats: LoaderStats,\n context: LoaderContext,\n networkDetails: any,\n ) => {\n this.log(`Loaded steering manifest: \"${url}\"`);\n const steeringData = response.data as SteeringManifest;\n if (steeringData.VERSION !== 1) {\n this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);\n return;\n }\n this.updated = performance.now();\n this.timeToLoad = steeringData.TTL;\n const {\n 'RELOAD-URI': reloadUri,\n 'PATHWAY-CLONES': pathwayClones,\n 'PATHWAY-PRIORITY': pathwayPriority,\n } = steeringData;\n if (reloadUri) {\n try {\n this.uri = new self.URL(reloadUri, url).href;\n } catch (error) {\n this.enabled = false;\n this.log(\n `Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`,\n );\n return;\n }\n }\n this.scheduleRefresh(this.uri || context.url);\n if (pathwayClones) {\n this.clonePathways(pathwayClones);\n }\n\n const loadedSteeringData: SteeringManifestLoadedData = {\n steeringManifest: steeringData,\n url: url.toString(),\n };\n this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);\n\n if (pathwayPriority) {\n this.updatePathwayPriority(pathwayPriority);\n }\n },\n\n onError: (\n error: { code: number; text: string },\n context: LoaderContext,\n networkDetails: any,\n stats: LoaderStats,\n ) => {\n this.log(\n `Error loading steering manifest: ${error.code} ${error.text} (${context.url})`,\n );\n this.stopLoad();\n if (error.code === 410) {\n this.enabled = false;\n this.log(`Steering manifest ${context.url} no longer available`);\n return;\n }\n let ttl = this.timeToLoad * 1000;\n if (error.code === 429) {\n const loader = this.loader;\n if (typeof loader?.getResponseHeader === 'function') {\n const retryAfter = loader.getResponseHeader('Retry-After');\n if (retryAfter) {\n ttl = parseFloat(retryAfter) * 1000;\n }\n }\n this.log(`Steering manifest ${context.url} rate limited`);\n return;\n }\n this.scheduleRefresh(this.uri || context.url, ttl);\n },\n\n onTimeout: (\n stats: LoaderStats,\n context: LoaderContext,\n networkDetails: any,\n ) => {\n this.log(`Timeout loading steering manifest (${context.url})`);\n this.scheduleRefresh(this.uri || context.url);\n },\n };\n\n this.log(`Requesting steering manifest: ${url}`);\n this.loader.load(context, loaderConfig, callbacks);\n }\n\n private scheduleRefresh(uri: string, ttlMs: number = this.timeToLoad * 1000) {\n this.clearTimeout();\n this.reloadTimer = self.setTimeout(() => {\n const media = this.hls?.media;\n if (media && !media.ended) {\n this.loadSteeringManifest(uri);\n return;\n }\n this.scheduleRefresh(uri, this.timeToLoad * 1000);\n }, ttlMs);\n }\n}\n\nfunction cloneRenditionGroups(\n tracks: MediaPlaylist[] | null,\n groupCloneMap: Record<string, string>,\n uriReplacement: UriReplacement,\n cloneId: string,\n) {\n if (!tracks) {\n return;\n }\n Object.keys(groupCloneMap).forEach((audioGroupId) => {\n const clonedTracks = tracks\n .filter((track) => track.groupId === audioGroupId)\n .map((track) => {\n const clonedTrack = Object.assign({}, track);\n clonedTrack.details = undefined;\n clonedTrack.attrs = new AttrList(clonedTrack.attrs) as MediaAttributes;\n clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(\n track.url,\n track.attrs['STABLE-RENDITION-ID'],\n 'PER-RENDITION-URIS',\n uriReplacement,\n );\n clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] =\n groupCloneMap[audioGroupId];\n clonedTrack.attrs['PATHWAY-ID'] = cloneId;\n return clonedTrack;\n });\n tracks.push(...clonedTracks);\n });\n}\n\nfunction performUriReplacement(\n uri: string,\n stableId: string | undefined,\n perOptionKey: 'PER-VARIANT-URIS' | 'PER-RENDITION-URIS',\n uriReplacement: UriReplacement,\n): string {\n const {\n HOST: host,\n PARAMS: params,\n [perOptionKey]: perOptionUris,\n } = uriReplacement;\n let perVariantUri;\n if (stableId) {\n perVariantUri = perOptionUris?.[stableId];\n if (perVariantUri) {\n uri = perVariantUri;\n }\n }\n const url = new self.URL(uri);\n if (host && !perVariantUri) {\n url.host = host;\n }\n if (params) {\n Object.keys(params)\n .sort()\n .forEach((key) => {\n if (key) {\n url.searchParams.set(key, params[key]);\n }\n });\n }\n return url.href;\n}\n","import { logger } from '../utils/logger';\nimport type {\n LoaderCallbacks,\n LoaderContext,\n LoaderStats,\n Loader,\n LoaderConfiguration,\n LoaderResponse,\n} from '../types/loader';\nimport { LoadStats } from '../loader/load-stats';\nimport { type HlsConfig, RetryConfig } from '../config';\nimport { getRetryDelay, shouldRetry } from './error-helper';\n\nconst AGE_HEADER_LINE_REGEX = /^age:\\s*[\\d.]+\\s*$/im;\n\nclass XhrLoader implements Loader<LoaderContext> {\n private xhrSetup:\n | ((xhr: XMLHttpRequest, url: string) => Promise<void> | void)\n | null;\n private requestTimeout?: number;\n private retryTimeout?: number;\n private retryDelay: number;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public context: LoaderContext | null = null;\n\n private loader: XMLHttpRequest | null = null;\n public stats: LoaderStats;\n\n constructor(config: HlsConfig) {\n this.xhrSetup = config ? config.xhrSetup || null : null;\n this.stats = new LoadStats();\n this.retryDelay = 0;\n }\n\n destroy() {\n this.callbacks = null;\n this.abortInternal();\n this.loader = null;\n this.config = null;\n this.context = null;\n this.xhrSetup = null;\n }\n\n abortInternal() {\n const loader = this.loader;\n self.clearTimeout(this.requestTimeout);\n self.clearTimeout(this.retryTimeout);\n if (loader) {\n loader.onreadystatechange = null;\n loader.onprogress = null;\n if (loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n }\n }\n\n abort() {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(\n this.stats,\n this.context as LoaderContext,\n this.loader,\n );\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>,\n ) {\n if (this.stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n this.stats.loading.start = self.performance.now();\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.loadInternal();\n }\n\n loadInternal() {\n const { config, context } = this;\n if (!config || !context) {\n return;\n }\n const xhr = (this.loader = new self.XMLHttpRequest());\n\n const stats = this.stats;\n stats.loading.first = 0;\n stats.loaded = 0;\n stats.aborted = false;\n const xhrSetup = this.xhrSetup;\n\n if (xhrSetup) {\n Promise.resolve()\n .then(() => {\n if (this.loader !== xhr || this.stats.aborted) return;\n return xhrSetup(xhr, context.url);\n })\n .catch((error: Error) => {\n if (this.loader !== xhr || this.stats.aborted) return;\n xhr.open('GET', context.url, true);\n return xhrSetup(xhr, context.url);\n })\n .then(() => {\n if (this.loader !== xhr || this.stats.aborted) return;\n this.openAndSendXhr(xhr, context, config);\n })\n .catch((error: Error) => {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks!.onError(\n { code: xhr.status, text: error.message },\n context,\n xhr,\n stats,\n );\n return;\n });\n } else {\n this.openAndSendXhr(xhr, context, config);\n }\n }\n\n openAndSendXhr(\n xhr: XMLHttpRequest,\n context: LoaderContext,\n config: LoaderConfiguration,\n ) {\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n\n const headers = context.headers;\n const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy;\n if (headers) {\n for (const header in headers) {\n xhr.setRequestHeader(header, headers[header]);\n }\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader(\n 'Range',\n 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1),\n );\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType as XMLHttpRequestResponseType;\n // setup timeout before we perform request\n self.clearTimeout(this.requestTimeout);\n config.timeout =\n maxTimeToFirstByteMs && Number.isFinite(maxTimeToFirstByteMs)\n ? maxTimeToFirstByteMs\n : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.timeout,\n );\n xhr.send();\n }\n\n readystatechange() {\n const { context, loader: xhr, stats } = this;\n if (!context || !xhr) {\n return;\n }\n const readyState = xhr.readyState;\n const config = this.config as LoaderConfiguration;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n if (stats.loading.first === 0) {\n stats.loading.first = Math.max(\n self.performance.now(),\n stats.loading.start,\n );\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {\n self.clearTimeout(this.requestTimeout);\n config.timeout = config.loadPolicy.maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.loadPolicy.maxLoadTimeMs -\n (stats.loading.first - stats.loading.start),\n );\n }\n }\n\n if (readyState === 4) {\n self.clearTimeout(this.requestTimeout);\n xhr.onreadystatechange = null;\n xhr.onprogress = null;\n const status = xhr.status;\n // http status between 200 to 299 are all successful\n const useResponse = xhr.responseType !== 'text';\n if (\n status >= 200 &&\n status < 300 &&\n ((useResponse && xhr.response) || xhr.responseText !== null)\n ) {\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first,\n );\n const data = useResponse ? xhr.response : xhr.responseText;\n const len =\n xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;\n stats.loaded = stats.total = len;\n stats.bwEstimate =\n (stats.total * 8000) / (stats.loading.end - stats.loading.first);\n if (!this.callbacks) {\n return;\n }\n const onProgress = this.callbacks.onProgress;\n if (onProgress) {\n onProgress(stats, context, data, xhr);\n }\n if (!this.callbacks) {\n return;\n }\n const response: LoaderResponse = {\n url: xhr.responseURL,\n data: data,\n code: status,\n };\n\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n const retryConfig = config.loadPolicy.errorRetry;\n const retryCount = stats.retry;\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n const response: LoaderResponse = {\n url: context.url,\n data: undefined,\n code: status,\n };\n if (shouldRetry(retryConfig, retryCount, false, response)) {\n this.retry(retryConfig);\n } else {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks!.onError(\n { code: status, text: xhr.statusText },\n context,\n xhr,\n stats,\n );\n }\n }\n }\n }\n }\n\n loadtimeout() {\n if (!this.config) return;\n const retryConfig = this.config.loadPolicy.timeoutRetry;\n const retryCount = this.stats.retry;\n if (shouldRetry(retryConfig, retryCount, true)) {\n this.retry(retryConfig);\n } else {\n logger.warn(`timeout while loading ${this.context?.url}`);\n const callbacks = this.callbacks;\n if (callbacks) {\n this.abortInternal();\n callbacks.onTimeout(\n this.stats,\n this.context as LoaderContext,\n this.loader,\n );\n }\n }\n }\n\n retry(retryConfig: RetryConfig) {\n const { context, stats } = this;\n this.retryDelay = getRetryDelay(retryConfig, stats.retry);\n stats.retry++;\n logger.warn(\n `${\n status ? 'HTTP Status ' + status : 'Timeout'\n } while loading ${context?.url}, retrying ${stats.retry}/${\n retryConfig.maxNumRetry\n } in ${this.retryDelay}ms`,\n );\n // abort and reset internal state\n this.abortInternal();\n this.loader = null;\n // schedule retry\n self.clearTimeout(this.retryTimeout);\n this.retryTimeout = self.setTimeout(\n this.loadInternal.bind(this),\n this.retryDelay,\n );\n }\n\n loadprogress(event: ProgressEvent) {\n const stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n }\n\n getCacheAge(): number | null {\n let result: number | null = null;\n if (\n this.loader &&\n AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())\n ) {\n const ageHeader = this.loader.getResponseHeader('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n\n getResponseHeader(name: string): string | null {\n if (\n this.loader &&\n new RegExp(`^${name}:\\\\s*[\\\\d.]+\\\\s*$`, 'im').test(\n this.loader.getAllResponseHeaders(),\n )\n ) {\n return this.loader.getResponseHeader(name);\n }\n return null;\n }\n}\n\nexport default XhrLoader;\n","import {\n LoaderCallbacks,\n LoaderContext,\n Loader,\n LoaderStats,\n LoaderConfiguration,\n LoaderOnProgress,\n LoaderResponse,\n} from '../types/loader';\nimport { LoadStats } from '../loader/load-stats';\nimport ChunkCache from '../demux/chunk-cache';\n\nexport function fetchSupported() {\n if (\n // @ts-ignore\n self.fetch &&\n self.AbortController &&\n self.ReadableStream &&\n self.Request\n ) {\n try {\n new self.ReadableStream({}); // eslint-disable-line no-new\n return true;\n } catch (e) {\n /* noop */\n }\n }\n return false;\n}\n\nconst BYTERANGE = /(\\d+)-(\\d+)\\/(\\d+)/;\n\nclass FetchLoader implements Loader<LoaderContext> {\n private fetchSetup: Function;\n private requestTimeout?: number;\n private request: Request | null = null;\n private response: Response | null = null;\n private controller: AbortController;\n public context: LoaderContext | null = null;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public stats: LoaderStats;\n private loader: Response | null = null;\n\n constructor(config /* HlsConfig */) {\n this.fetchSetup = config.fetchSetup || getRequest;\n this.controller = new self.AbortController();\n this.stats = new LoadStats();\n }\n\n destroy(): void {\n this.loader =\n this.callbacks =\n this.context =\n this.config =\n this.request =\n null;\n this.abortInternal();\n this.response = null;\n // @ts-ignore\n this.fetchSetup = this.controller = this.stats = null;\n }\n\n abortInternal(): void {\n if (this.controller && !this.stats.loading.end) {\n this.stats.aborted = true;\n this.controller.abort();\n }\n }\n\n abort(): void {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(\n this.stats,\n this.context as LoaderContext,\n this.response,\n );\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>,\n ): void {\n const stats = this.stats;\n if (stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n stats.loading.start = self.performance.now();\n\n const initParams = getRequestParameters(context, this.controller.signal);\n const onProgress: LoaderOnProgress<LoaderContext> | undefined =\n callbacks.onProgress;\n const isArrayBuffer = context.responseType === 'arraybuffer';\n const LENGTH = isArrayBuffer ? 'byteLength' : 'length';\n const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy;\n\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.request = this.fetchSetup(context, initParams);\n self.clearTimeout(this.requestTimeout);\n config.timeout =\n maxTimeToFirstByteMs && Number.isFinite(maxTimeToFirstByteMs)\n ? maxTimeToFirstByteMs\n : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(() => {\n this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n }, config.timeout);\n\n self\n .fetch(this.request as Request)\n .then((response: Response): Promise<string | ArrayBuffer> => {\n this.response = this.loader = response;\n\n const first = Math.max(self.performance.now(), stats.loading.start);\n\n self.clearTimeout(this.requestTimeout);\n config.timeout = maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n () => {\n this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n },\n maxLoadTimeMs - (first - stats.loading.start),\n );\n\n if (!response.ok) {\n const { status, statusText } = response;\n throw new FetchError(\n statusText || 'fetch, bad network response',\n status,\n response,\n );\n }\n stats.loading.first = first;\n\n stats.total = getContentLength(response.headers) || stats.total;\n\n if (onProgress && Number.isFinite(config.highWaterMark)) {\n return this.loadProgressively(\n response,\n stats,\n context,\n config.highWaterMark,\n onProgress,\n );\n }\n\n if (isArrayBuffer) {\n return response.arrayBuffer();\n }\n if (context.responseType === 'json') {\n return response.json();\n }\n return response.text();\n })\n .then((responseData: string | ArrayBuffer) => {\n const response = this.response;\n if (!response) {\n throw new Error('loader destroyed');\n }\n self.clearTimeout(this.requestTimeout);\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first,\n );\n const total = responseData[LENGTH];\n if (total) {\n stats.loaded = stats.total = total;\n }\n\n const loaderResponse: LoaderResponse = {\n url: response.url,\n data: responseData,\n code: response.status,\n };\n\n if (onProgress && !Number.isFinite(config.highWaterMark)) {\n onProgress(stats, context, responseData, response);\n }\n\n callbacks.onSuccess(loaderResponse, stats, context, response);\n })\n .catch((error) => {\n self.clearTimeout(this.requestTimeout);\n if (stats.aborted) {\n return;\n }\n // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior\n // when destroying, 'error' itself can be undefined\n const code: number = !error ? 0 : error.code || 0;\n const text: string = !error ? null : error.message;\n callbacks.onError(\n { code, text },\n context,\n error ? error.details : null,\n stats,\n );\n });\n }\n\n getCacheAge(): number | null {\n let result: number | null = null;\n if (this.response) {\n const ageHeader = this.response.headers.get('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n\n getResponseHeader(name: string): string | null {\n return this.response ? this.response.headers.get(name) : null;\n }\n\n private loadProgressively(\n response: Response,\n stats: LoaderStats,\n context: LoaderContext,\n highWaterMark: number = 0,\n onProgress: LoaderOnProgress<LoaderContext>,\n ): Promise<ArrayBuffer> {\n const chunkCache = new ChunkCache();\n const reader = (response.body as ReadableStream).getReader();\n\n const pump = (): Promise<ArrayBuffer> => {\n return reader\n .read()\n .then((data) => {\n if (data.done) {\n if (chunkCache.dataLength) {\n onProgress(stats, context, chunkCache.flush(), response);\n }\n\n return Promise.resolve(new ArrayBuffer(0));\n }\n const chunk: Uint8Array = data.value;\n const len = chunk.length;\n stats.loaded += len;\n if (len < highWaterMark || chunkCache.dataLength) {\n // The current chunk is too small to to be emitted or the cache already has data\n // Push it to the cache\n chunkCache.push(chunk);\n if (chunkCache.dataLength >= highWaterMark) {\n // flush in order to join the typed arrays\n onProgress(stats, context, chunkCache.flush(), response);\n }\n } else {\n // If there's nothing cached already, and the chache is large enough\n // just emit the progress event\n onProgress(stats, context, chunk, response);\n }\n return pump();\n })\n .catch(() => {\n /* aborted */\n return Promise.reject();\n });\n };\n\n return pump();\n }\n}\n\nfunction getRequestParameters(context: LoaderContext, signal): any {\n const initParams: any = {\n method: 'GET',\n mode: 'cors',\n credentials: 'same-origin',\n signal,\n headers: new self.Headers(Object.assign({}, context.headers)),\n };\n\n if (context.rangeEnd) {\n initParams.headers.set(\n 'Range',\n 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1),\n );\n }\n\n return initParams;\n}\n\nfunction getByteRangeLength(byteRangeHeader: string): number | undefined {\n const result = BYTERANGE.exec(byteRangeHeader);\n if (result) {\n return parseInt(result[2]) - parseInt(result[1]) + 1;\n }\n}\n\nfunction getContentLength(headers: Headers): number | undefined {\n const contentRange = headers.get('Content-Range');\n if (contentRange) {\n const byteRangeLength = getByteRangeLength(contentRange);\n if (Number.isFinite(byteRangeLength)) {\n return byteRangeLength;\n }\n }\n const contentLength = headers.get('Content-Length');\n if (contentLength) {\n return parseInt(contentLength);\n }\n}\n\nfunction getRequest(context: LoaderContext, initParams: any): Request {\n return new self.Request(context.url, initParams);\n}\n\nclass FetchError extends Error {\n public code: number;\n public details: any;\n constructor(message: string, code: number, details: any) {\n super(message);\n this.code = code;\n this.details = details;\n }\n}\n\nexport default FetchLoader;\n","import {\n ManifestLoadedData,\n ManifestParsedData,\n LevelLoadedData,\n ErrorData,\n LevelSwitchingData,\n LevelsUpdatedData,\n ManifestLoadingData,\n FragBufferedData,\n} from '../types/events';\nimport { Level, VideoRangeValues, isVideoRange } from '../types/level';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport {\n areCodecsMediaSourceSupported,\n codecsSetSelectionPreferenceValue,\n convertAVC1ToAVCOTI,\n getCodecCompatibleName,\n videoCodecPreferenceValue,\n} from '../utils/codecs';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport ContentSteeringController from './content-steering-controller';\nimport { reassignFragmentLevelIndexes } from '../utils/level-helper';\nimport { hlsDefaultConfig } from '../config';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters, LevelParsed } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nlet chromeOrFirefox: boolean;\n\nexport default class LevelController extends BasePlaylistController {\n private _levels: Level[] = [];\n private _firstLevel: number = -1;\n private _maxAutoLevel: number = -1;\n private _startLevel?: number;\n private currentLevel: Level | null = null;\n private currentLevelIndex: number = -1;\n private manualLevelIndex: number = -1;\n private steering: ContentSteeringController | null;\n\n public onParsedComplete!: Function;\n\n constructor(\n hls: Hls,\n contentSteeringController: ContentSteeringController | null,\n ) {\n super(hls, '[level-controller]');\n this.steering = contentSteeringController;\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this._unregisterListeners();\n this.steering = null;\n this.resetLevels();\n super.destroy();\n }\n\n public stopLoad(): void {\n const levels = this._levels;\n\n // clean up live level details to force reload them, and reset load errors\n levels.forEach((level) => {\n level.loadError = 0;\n level.fragmentError = 0;\n });\n\n super.stopLoad();\n }\n\n private resetLevels() {\n this._startLevel = undefined;\n this.manualLevelIndex = -1;\n this.currentLevelIndex = -1;\n this.currentLevel = null;\n this._levels = [];\n this._maxAutoLevel = -1;\n }\n\n private onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData,\n ) {\n this.resetLevels();\n }\n\n protected onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData,\n ) {\n const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;\n const levels: Level[] = [];\n const redundantSet: { [key: string]: Level } = {};\n const generatePathwaySet: { [key: string]: number } = {};\n let resolutionFound = false;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n data.levels.forEach((levelParsed: LevelParsed) => {\n const attributes = levelParsed.attrs;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n let { audioCodec, videoCodec } = levelParsed;\n if (audioCodec?.indexOf('mp4a.40.34') !== -1) {\n chromeOrFirefox ||= /chrome|firefox/i.test(navigator.userAgent);\n if (chromeOrFirefox) {\n levelParsed.audioCodec = audioCodec = undefined;\n }\n }\n\n if (audioCodec) {\n levelParsed.audioCodec = audioCodec = getCodecCompatibleName(\n audioCodec,\n preferManagedMediaSource,\n );\n }\n\n if (videoCodec?.indexOf('avc1') === 0) {\n videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n const { width, height, unknownCodecs } = levelParsed;\n resolutionFound ||= !!(width && height);\n videoCodecFound ||= !!videoCodec;\n audioCodecFound ||= !!audioCodec;\n if (\n unknownCodecs?.length ||\n (audioCodec &&\n !areCodecsMediaSourceSupported(\n audioCodec,\n 'audio',\n preferManagedMediaSource,\n )) ||\n (videoCodec &&\n !areCodecsMediaSourceSupported(\n videoCodec,\n 'video',\n preferManagedMediaSource,\n ))\n ) {\n return;\n }\n\n const {\n CODECS,\n 'FRAME-RATE': FRAMERATE,\n 'HDCP-LEVEL': HDCP,\n 'PATHWAY-ID': PATHWAY,\n RESOLUTION,\n 'VIDEO-RANGE': VIDEO_RANGE,\n } = attributes;\n const contentSteeringPrefix = `${PATHWAY || '.'}-`;\n const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;\n\n if (!redundantSet[levelKey]) {\n const level = new Level(levelParsed);\n redundantSet[levelKey] = level;\n generatePathwaySet[levelKey] = 1;\n levels.push(level);\n } else if (\n redundantSet[levelKey].uri !== levelParsed.url &&\n !levelParsed.attrs['PATHWAY-ID']\n ) {\n // Assign Pathway IDs to Redundant Streams (default Pathways is \".\". Redundant Streams \"..\", \"...\", and so on.)\n // Content Steering controller to handles Pathway fallback on error\n const pathwayCount = (generatePathwaySet[levelKey] += 1);\n levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');\n const level = new Level(levelParsed);\n redundantSet[levelKey] = level;\n levels.push(level);\n } else {\n redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);\n redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);\n }\n });\n\n this.filterAndSortMediaOptions(\n levels,\n data,\n resolutionFound,\n videoCodecFound,\n audioCodecFound,\n );\n }\n\n private filterAndSortMediaOptions(\n filteredLevels: Level[],\n data: ManifestLoadedData,\n resolutionFound: boolean,\n videoCodecFound: boolean,\n audioCodecFound: boolean,\n ) {\n let audioTracks: MediaPlaylist[] = [];\n let subtitleTracks: MediaPlaylist[] = [];\n let levels = filteredLevels;\n\n // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled\n if ((resolutionFound || videoCodecFound) && audioCodecFound) {\n levels = levels.filter(\n ({ videoCodec, videoRange, width, height }) =>\n (!!videoCodec || !!(width && height)) && isVideoRange(videoRange),\n );\n }\n\n if (levels.length === 0) {\n // Dispatch error after MANIFEST_LOADED is done propagating\n Promise.resolve().then(() => {\n if (this.hls) {\n if (data.levels.length) {\n this.warn(\n `One or more CODECS in variant not supported: ${JSON.stringify(\n data.levels[0].attrs,\n )}`,\n );\n }\n const error = new Error(\n 'no level with compatible codecs found in manifest',\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: data.url,\n error,\n reason: error.message,\n });\n }\n });\n return;\n }\n\n if (data.audioTracks) {\n const { preferManagedMediaSource } = this.hls.config;\n audioTracks = data.audioTracks.filter(\n (track) =>\n !track.audioCodec ||\n areCodecsMediaSourceSupported(\n track.audioCodec,\n 'audio',\n preferManagedMediaSource,\n ),\n );\n // Assign ids after filtering as array indices by group-id\n assignTrackIdsByGroup(audioTracks);\n }\n\n if (data.subtitles) {\n subtitleTracks = data.subtitles;\n assignTrackIdsByGroup(subtitleTracks);\n }\n // start bitrate is the first bitrate of the manifest\n const unsortedLevels = levels.slice(0);\n // sort levels from lowest to highest\n levels.sort((a, b) => {\n if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {\n return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '')\n ? 1\n : -1;\n }\n // sort on height before bitrate for cap-level-controller\n if (resolutionFound && a.height !== b.height) {\n return a.height - b.height;\n }\n if (a.frameRate !== b.frameRate) {\n return a.frameRate - b.frameRate;\n }\n if (a.videoRange !== b.videoRange) {\n return (\n VideoRangeValues.indexOf(a.videoRange) -\n VideoRangeValues.indexOf(b.videoRange)\n );\n }\n if (a.videoCodec !== b.videoCodec) {\n const valueA = videoCodecPreferenceValue(a.videoCodec);\n const valueB = videoCodecPreferenceValue(b.videoCodec);\n if (valueA !== valueB) {\n return valueB - valueA;\n }\n }\n if (a.uri === b.uri && a.codecSet !== b.codecSet) {\n const valueA = codecsSetSelectionPreferenceValue(a.codecSet);\n const valueB = codecsSetSelectionPreferenceValue(b.codecSet);\n if (valueA !== valueB) {\n return valueB - valueA;\n }\n }\n if (a.averageBitrate !== b.averageBitrate) {\n return a.averageBitrate - b.averageBitrate;\n }\n return 0;\n });\n\n let firstLevelInPlaylist = unsortedLevels[0];\n if (this.steering) {\n levels = this.steering.filterParsedLevels(levels);\n if (levels.length !== unsortedLevels.length) {\n for (let i = 0; i < unsortedLevels.length; i++) {\n if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {\n firstLevelInPlaylist = unsortedLevels[i];\n break;\n }\n }\n }\n }\n\n this._levels = levels;\n\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i] === firstLevelInPlaylist) {\n this._firstLevel = i;\n const firstLevelBitrate = firstLevelInPlaylist.bitrate;\n const bandwidthEstimate = this.hls.bandwidthEstimate;\n this.log(\n `manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`,\n );\n // Update default bwe to first variant bitrate as long it has not been configured or set\n if (this.hls.userConfig?.abrEwmaDefaultEstimate === undefined) {\n const startingBwEstimate = Math.min(\n firstLevelBitrate,\n this.hls.config.abrEwmaDefaultEstimateMax,\n );\n if (\n startingBwEstimate > bandwidthEstimate &&\n bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate\n ) {\n this.hls.bandwidthEstimate = startingBwEstimate;\n }\n }\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag,\n // and this is not an audio-only stream where levels contain audio-only\n const audioOnly = audioCodecFound && !videoCodecFound;\n const edata: ManifestParsedData = {\n levels,\n audioTracks,\n subtitleTracks,\n sessionData: data.sessionData,\n sessionKeys: data.sessionKeys,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: !audioOnly && audioTracks.some((t) => !!t.url),\n };\n this.hls.trigger(Events.MANIFEST_PARSED, edata);\n\n // Initiate loading after all controllers have received MANIFEST_PARSED\n if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {\n this.hls.startLoad(this.hls.config.startPosition);\n }\n }\n\n get levels(): Level[] | null {\n if (this._levels.length === 0) {\n return null;\n }\n return this._levels;\n }\n\n get level(): number {\n return this.currentLevelIndex;\n }\n\n set level(newLevel: number) {\n const levels = this._levels;\n if (levels.length === 0) {\n return;\n }\n // check if level idx is valid\n if (newLevel < 0 || newLevel >= levels.length) {\n // invalid level id given, trigger error\n const error = new Error('invalid level idx');\n const fatal = newLevel < 0;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal,\n error,\n reason: error.message,\n });\n if (fatal) {\n return;\n }\n newLevel = Math.min(newLevel, levels.length - 1);\n }\n\n const lastLevelIndex = this.currentLevelIndex;\n const lastLevel = this.currentLevel;\n const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;\n const level = levels[newLevel];\n const pathwayId = level.attrs['PATHWAY-ID'];\n this.currentLevelIndex = newLevel;\n this.currentLevel = level;\n\n if (\n lastLevelIndex === newLevel &&\n level.details &&\n lastLevel &&\n lastPathwayId === pathwayId\n ) {\n return;\n }\n\n this.log(\n `Switching to level ${newLevel} (${\n level.height ? level.height + 'p ' : ''\n }${level.videoRange ? level.videoRange + ' ' : ''}${\n level.codecSet ? level.codecSet + ' ' : ''\n }@${level.bitrate})${\n pathwayId ? ' with Pathway ' + pathwayId : ''\n } from level ${lastLevelIndex}${\n lastPathwayId ? ' with Pathway ' + lastPathwayId : ''\n }`,\n );\n\n const levelSwitchingData: LevelSwitchingData = {\n level: newLevel,\n attrs: level.attrs,\n details: level.details,\n bitrate: level.bitrate,\n averageBitrate: level.averageBitrate,\n maxBitrate: level.maxBitrate,\n realBitrate: level.realBitrate,\n width: level.width,\n height: level.height,\n codecSet: level.codecSet,\n audioCodec: level.audioCodec,\n videoCodec: level.videoCodec,\n audioGroups: level.audioGroups,\n subtitleGroups: level.subtitleGroups,\n loaded: level.loaded,\n loadError: level.loadError,\n fragmentError: level.fragmentError,\n name: level.name,\n id: level.id,\n uri: level.uri,\n url: level.url,\n urlId: 0,\n audioGroupIds: level.audioGroupIds,\n textGroupIds: level.textGroupIds,\n };\n\n this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);\n // check if we need to load playlist for this level\n const levelDetails = level.details;\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n const hlsUrlParameters = this.switchParams(\n level.uri,\n lastLevel?.details,\n levelDetails,\n );\n this.loadPlaylist(hlsUrlParameters);\n }\n }\n\n get manualLevel(): number {\n return this.manualLevelIndex;\n }\n\n set manualLevel(newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel(): number {\n return this._firstLevel;\n }\n\n set firstLevel(newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel(): number {\n // Setting hls.startLevel (this._startLevel) overrides config.startLevel\n if (this._startLevel === undefined) {\n const configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n }\n return this.hls.firstAutoLevel;\n }\n return this._startLevel;\n }\n\n set startLevel(newLevel: number) {\n this._startLevel = newLevel;\n }\n\n protected onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.LEVEL &&\n data.context.level === this.level\n ) {\n this.checkRetry(data);\n }\n }\n\n // reset errors on the successful load of a fragment\n protected onFragBuffered(\n event: Events.FRAG_BUFFERED,\n { frag }: FragBufferedData,\n ) {\n if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {\n const el = frag.elementaryStreams;\n if (!Object.keys(el).some((type) => !!el[type])) {\n return;\n }\n const level = this._levels[frag.level];\n if (level?.loadError) {\n this.log(\n `Resetting level error count of ${level.loadError} on frag buffered`,\n );\n level.loadError = 0;\n }\n }\n }\n\n protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const { level, details } = data;\n const curLevel = this._levels[level];\n\n if (!curLevel) {\n this.warn(`Invalid level index ${level}`);\n if (data.deliveryDirectives?.skip) {\n details.deltaUpdateFailed = true;\n }\n return;\n }\n\n // only process level loaded events matching with expected level\n if (level === this.currentLevelIndex) {\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (curLevel.fragmentError === 0) {\n curLevel.loadError = 0;\n }\n this.playlistLoaded(level, data, curLevel.details);\n } else if (data.deliveryDirectives?.skip) {\n // received a delta playlist update that cannot be merged\n details.deltaUpdateFailed = true;\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters) {\n super.loadPlaylist();\n const currentLevelIndex = this.currentLevelIndex;\n const currentLevel = this.currentLevel;\n\n if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {\n let url = currentLevel.uri;\n if (hlsUrlParameters) {\n try {\n url = hlsUrlParameters.addDirectives(url);\n } catch (error) {\n this.warn(\n `Could not construct new URL with HLS Delivery Directives: ${error}`,\n );\n }\n }\n\n const pathwayId = currentLevel.attrs['PATHWAY-ID'];\n this.log(\n `Loading level index ${currentLevelIndex}${\n hlsUrlParameters?.msn !== undefined\n ? ' at sn ' +\n hlsUrlParameters.msn +\n ' part ' +\n hlsUrlParameters.part\n : ''\n } with${pathwayId ? ' Pathway ' + pathwayId : ''} ${url}`,\n );\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n this.clearTimer();\n this.hls.trigger(Events.LEVEL_LOADING, {\n url,\n level: currentLevelIndex,\n pathwayId: currentLevel.attrs['PATHWAY-ID'],\n id: 0, // Deprecated Level urlId\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n\n get nextLoadLevel() {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n\n removeLevel(levelIndex: number) {\n const levels = this._levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n if (this.steering) {\n this.steering.removeLevel(level);\n }\n if (level === this.currentLevel) {\n this.currentLevel = null;\n this.currentLevelIndex = -1;\n if (level.details) {\n level.details.fragments.forEach((f) => (f.level = -1));\n }\n }\n return false;\n });\n reassignFragmentLevelIndexes(levels);\n this._levels = levels;\n if (this.currentLevelIndex > -1 && this.currentLevel?.details) {\n this.currentLevelIndex = this.currentLevel.details.fragments[0].level;\n }\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n { levels }: LevelsUpdatedData,\n ) {\n this._levels = levels;\n }\n\n public checkMaxAutoUpdated() {\n const { autoLevelCapping, maxAutoLevel, maxHdcpLevel } = this.hls;\n if (this._maxAutoLevel !== maxAutoLevel) {\n this._maxAutoLevel = maxAutoLevel;\n this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {\n autoLevelCapping,\n levels: this.levels,\n maxAutoLevel,\n minAutoLevel: this.hls.minAutoLevel,\n maxHdcpLevel,\n });\n }\n }\n}\n\nfunction assignTrackIdsByGroup(tracks: MediaPlaylist[]): void {\n const groups = {};\n tracks.forEach((track) => {\n const groupId = track.groupId || '';\n track.id = groups[groupId] = groups[groupId] || 0;\n groups[groupId]++;\n });\n}\n","import { 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 LoaderResponse,\n PlaylistLoaderContext,\n} from './types/loader';\nimport type {\n AudioSelectionOption,\n SubtitleSelectionOption,\n VideoSelectionOption,\n} from './types/media-playlist';\n\nexport type ABRControllerConfig = {\n abrEwmaFastLive: number;\n abrEwmaSlowLive: number;\n abrEwmaFastVoD: number;\n abrEwmaSlowVoD: number;\n /**\n * Default bandwidth estimate in bits/s prior to collecting fragment bandwidth samples\n */\n abrEwmaDefaultEstimate: number;\n abrEwmaDefaultEstimateMax: number;\n abrBandWidthFactor: number;\n abrBandWidthUpFactor: number;\n abrMaxWithRealBitrate: boolean;\n maxStarvationDelay: number;\n maxLoadingDelay: number;\n};\n\nexport type BufferControllerConfig = {\n appendErrorMaxRetry: number;\n backBufferLength: number;\n frontBufferFlushThreshold: number;\n liveDurationInfinity: boolean;\n /**\n * @deprecated use backBufferLength\n */\n liveBackBufferLength: number | null;\n};\n\nexport type CapLevelControllerConfig = {\n capLevelToPlayerSize: boolean;\n};\n\nexport type CMCDControllerConfig = {\n sessionId?: string;\n contentId?: string;\n useHeaders?: boolean;\n includeKeys?: string[];\n};\n\nexport type DRMSystemOptions = {\n audioRobustness?: string;\n videoRobustness?: string;\n audioEncryptionScheme?: string | null;\n videoEncryptionScheme?: string | null;\n persistentState?: MediaKeysRequirement;\n distinctiveIdentifier?: MediaKeysRequirement;\n sessionTypes?: string[];\n sessionType?: string;\n};\n\nexport type DRMSystemConfiguration = {\n licenseUrl: string;\n serverCertificateUrl?: string;\n generateRequest?: (\n this: Hls,\n initDataType: string,\n initData: ArrayBuffer | null,\n keyContext: MediaKeySessionContext,\n ) =>\n | { initDataType: string; initData: ArrayBuffer | null }\n | undefined\n | never;\n};\n\nexport type DRMSystemsConfiguration = Partial<\n Record<KeySystems, DRMSystemConfiguration>\n>;\n\nexport type EMEControllerConfig = {\n licenseXhrSetup?: (\n this: Hls,\n xhr: XMLHttpRequest,\n url: string,\n keyContext: MediaKeySessionContext,\n licenseChallenge: Uint8Array,\n ) => void | Uint8Array | Promise<Uint8Array | void>;\n licenseResponseCallback?: (\n this: Hls,\n xhr: XMLHttpRequest,\n url: string,\n keyContext: MediaKeySessionContext,\n ) => ArrayBuffer;\n emeEnabled: boolean;\n widevineLicenseUrl?: string;\n drmSystems: DRMSystemsConfiguration;\n drmSystemOptions: DRMSystemOptions;\n requestMediaKeySystemAccessFunc: MediaKeyFunc | null;\n};\n\nexport interface FragmentLoaderConstructor {\n new (confg: HlsConfig): Loader<FragmentLoaderContext>;\n}\n\n/**\n * @deprecated use fragLoadPolicy.default\n */\nexport type FragmentLoaderConfig = {\n fragLoadingTimeOut: number;\n fragLoadingMaxRetry: number;\n fragLoadingRetryDelay: number;\n fragLoadingMaxRetryTimeout: number;\n};\n\nexport type FPSControllerConfig = {\n capLevelOnFPSDrop: boolean;\n fpsDroppedMonitoringPeriod: number;\n fpsDroppedMonitoringThreshold: number;\n};\n\nexport type LevelControllerConfig = {\n startLevel?: number;\n};\n\nexport type MP4RemuxerConfig = {\n stretchShortVideoTrack: boolean;\n maxAudioFramesDrift: number;\n};\n\nexport interface PlaylistLoaderConstructor {\n new (confg: HlsConfig): Loader<PlaylistLoaderContext>;\n}\n\n/**\n * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default\n */\nexport type PlaylistLoaderConfig = {\n manifestLoadingTimeOut: number;\n manifestLoadingMaxRetry: number;\n manifestLoadingRetryDelay: number;\n manifestLoadingMaxRetryTimeout: number;\n\n levelLoadingTimeOut: number;\n levelLoadingMaxRetry: number;\n levelLoadingRetryDelay: number;\n levelLoadingMaxRetryTimeout: number;\n};\n\nexport type HlsLoadPolicies = {\n fragLoadPolicy: LoadPolicy;\n keyLoadPolicy: LoadPolicy;\n certLoadPolicy: LoadPolicy;\n playlistLoadPolicy: LoadPolicy;\n manifestLoadPolicy: LoadPolicy;\n steeringManifestLoadPolicy: LoadPolicy;\n};\n\nexport type LoadPolicy = {\n default: LoaderConfig;\n};\n\nexport type LoaderConfig = {\n maxTimeToFirstByteMs: number; // Max time to first byte\n maxLoadTimeMs: number; // Max time for load completion\n timeoutRetry: RetryConfig | null;\n errorRetry: RetryConfig | null;\n};\n\nexport type RetryConfig = {\n maxNumRetry: number; // Maximum number of retries\n retryDelayMs: number; // Retry delay = 2^retryCount * retryDelayMs (exponential) or retryCount * retryDelayMs (linear)\n maxRetryDelayMs: number; // Maximum delay between retries\n backoff?: 'exponential' | 'linear'; // used to determine retry backoff duration (see retryDelayMs)\n shouldRetry?: (\n retryConfig: RetryConfig | null | undefined,\n retryCount: number,\n isTimeout: boolean,\n loaderResponse: LoaderResponse | undefined,\n retry: boolean,\n ) => boolean;\n};\n\nexport type StreamControllerConfig = {\n autoStartLoad: boolean;\n startPosition: number;\n defaultAudioCodec?: string;\n initialLiveManifestSize: number;\n maxBufferLength: number;\n maxBufferSize: number;\n maxBufferHole: number;\n highBufferWatchdogPeriod: number;\n nudgeOffset: number;\n nudgeMaxRetry: number;\n maxFragLookUpTolerance: number;\n maxMaxBufferLength: number;\n startFragPrefetch: boolean;\n testBandwidth: boolean;\n};\n\nexport type SelectionPreferences = {\n videoPreference?: VideoSelectionOption;\n audioPreference?: AudioSelectionOption;\n subtitlePreference?: SubtitleSelectionOption;\n};\n\nexport type LatencyControllerConfig = {\n liveSyncDurationCount: number;\n liveMaxLatencyDurationCount: number;\n liveSyncDuration?: number;\n liveMaxLatencyDuration?: number;\n maxLiveSyncPlaybackRate: number;\n};\n\nexport type MetadataControllerConfig = {\n enableDateRangeMetadataCues: boolean;\n enableEmsgMetadataCues: boolean;\n enableID3MetadataCues: boolean;\n};\n\nexport type TimelineControllerConfig = {\n cueHandler: CuesInterface;\n enableWebVTT: boolean;\n enableIMSC1: boolean;\n enableCEA708Captions: boolean;\n captionsTextTrack1Label: string;\n captionsTextTrack1LanguageCode: string;\n captionsTextTrack2Label: string;\n captionsTextTrack2LanguageCode: string;\n captionsTextTrack3Label: string;\n captionsTextTrack3LanguageCode: string;\n captionsTextTrack4Label: string;\n captionsTextTrack4LanguageCode: string;\n renderTextTracksNatively: boolean;\n};\n\nexport type TSDemuxerConfig = {\n forceKeyFrameOnDiscontinuity: boolean;\n};\n\nexport type HlsConfig = {\n debug: boolean | ILogger;\n enableWorker: boolean;\n workerPath: null | string;\n enableSoftwareAES: boolean;\n minAutoBitrate: number;\n ignoreDevicePixelRatio: boolean;\n preferManagedMediaSource: boolean;\n loader: { new (confg: HlsConfig): Loader<LoaderContext> };\n fLoader?: FragmentLoaderConstructor;\n pLoader?: PlaylistLoaderConstructor;\n fetchSetup?: (context: LoaderContext, initParams: any) => Request;\n xhrSetup?: (xhr: XMLHttpRequest, url: string) => Promise<void> | void;\n\n // Alt Audio\n audioStreamController?: typeof AudioStreamController;\n audioTrackController?: typeof AudioTrackController;\n // Subtitle\n subtitleStreamController?: typeof SubtitleStreamController;\n subtitleTrackController?: typeof SubtitleTrackController;\n timelineController?: typeof TimelineController;\n // EME\n emeController?: typeof EMEController;\n // CMCD\n cmcd?: CMCDControllerConfig;\n cmcdController?: typeof CMCDController;\n // Content Steering\n contentSteeringController?: typeof ContentSteeringController;\n\n // MediaCapabilies API for level, track, and switch filtering\n useMediaCapabilities: boolean;\n\n abrController: typeof AbrController;\n bufferController: typeof BufferController;\n capLevelController: typeof CapLevelController;\n errorController: typeof ErrorController;\n fpsController: typeof FPSController;\n progressive: boolean;\n lowLatencyMode: boolean;\n} & ABRControllerConfig &\n BufferControllerConfig &\n CapLevelControllerConfig &\n EMEControllerConfig &\n FPSControllerConfig &\n LevelControllerConfig &\n MP4RemuxerConfig &\n StreamControllerConfig &\n SelectionPreferences &\n LatencyControllerConfig &\n MetadataControllerConfig &\n TimelineControllerConfig &\n TSDemuxerConfig &\n HlsLoadPolicies &\n FragmentLoaderConfig &\n PlaylistLoaderConfig;\n\nconst defaultLoadPolicy: LoaderConfig = {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: null,\n errorRetry: null,\n};\n\n/**\n * @ignore\n * If possible, keep hlsDefaultConfig shallow\n * It is cloned whenever a new Hls instance is created, by keeping the config\n * shallow the properties are cloned, and we don't end up manipulating the default\n */\nexport const hlsDefaultConfig: HlsConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: undefined, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n ignoreDevicePixelRatio: false, // used by cap-level-controller\n preferManagedMediaSource: true,\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n backBufferLength: Infinity, // used by buffer-controller\n frontBufferFlushThreshold: Infinity,\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.1, // used by stream-controller\n highBufferWatchdogPeriod: 2, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry: 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount: 3, // used by latency-controller\n liveMaxLatencyDurationCount: Infinity, // used by latency-controller\n liveSyncDuration: undefined, // used by latency-controller\n liveMaxLatencyDuration: undefined, // used by latency-controller\n maxLiveSyncPlaybackRate: 1, // used by latency-controller\n liveDurationInfinity: false, // used by buffer-controller\n /**\n * @deprecated use backBufferLength\n */\n liveBackBufferLength: null, // used by buffer-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by transmuxer\n workerPath: null, // used by transmuxer\n enableSoftwareAES: true, // used by decrypter\n startLevel: undefined, // used by level-controller\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\n loader: XhrLoader,\n // loader: FetchLoader,\n fLoader: undefined, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\n licenseResponseCallback: undefined, // used by eme-controller\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n errorController: ErrorController,\n fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift: 1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrEwmaDefaultEstimateMax: 5e6, // 5 mbps\n abrBandWidthFactor: 0.95, // used by abr-controller\n abrBandWidthUpFactor: 0.7, // used by abr-controller\n abrMaxWithRealBitrate: false, // used by abr-controller\n maxStarvationDelay: 4, // used by abr-controller\n maxLoadingDelay: 4, // used by abr-controller\n minAutoBitrate: 0, // used by hls\n emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n drmSystems: {}, // used by eme-controller\n drmSystemOptions: {}, // used by eme-controller\n requestMediaKeySystemAccessFunc: __USE_EME_DRM__\n ? requestMediaKeySystemAccess\n : null, // used by eme-controller\n testBandwidth: true,\n progressive: false,\n lowLatencyMode: true,\n cmcd: undefined,\n enableDateRangeMetadataCues: true,\n enableEmsgMetadataCues: true,\n enableID3MetadataCues: true,\n useMediaCapabilities: __USE_MEDIA_CAPABILITIES__,\n\n certLoadPolicy: {\n default: defaultLoadPolicy,\n },\n keyLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear',\n },\n errorRetry: {\n maxNumRetry: 8,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear',\n },\n },\n },\n manifestLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: Infinity,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n playlistLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 2,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n fragLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 120000,\n timeoutRetry: {\n maxNumRetry: 4,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 6,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n steeringManifestLoadPolicy: {\n default: __USE_CONTENT_STEERING__\n ? {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n }\n : defaultLoadPolicy,\n },\n\n // These default settings are deprecated in favor of the above policies\n // and are maintained for backwards compatibility\n manifestLoadingTimeOut: 10000,\n manifestLoadingMaxRetry: 1,\n manifestLoadingRetryDelay: 1000,\n manifestLoadingMaxRetryTimeout: 64000,\n levelLoadingTimeOut: 10000,\n levelLoadingMaxRetry: 4,\n levelLoadingRetryDelay: 1000,\n levelLoadingMaxRetryTimeout: 64000,\n fragLoadingTimeOut: 20000,\n fragLoadingMaxRetry: 6,\n fragLoadingRetryDelay: 1000,\n fragLoadingMaxRetryTimeout: 64000,\n\n // Dynamic Modules\n ...timelineConfig(),\n subtitleStreamController: __USE_SUBTITLES__\n ? SubtitleStreamController\n : undefined,\n subtitleTrackController: __USE_SUBTITLES__\n ? SubtitleTrackController\n : undefined,\n timelineController: __USE_SUBTITLES__ ? TimelineController : undefined,\n audioStreamController: __USE_ALT_AUDIO__ ? AudioStreamController : undefined,\n audioTrackController: __USE_ALT_AUDIO__ ? AudioTrackController : undefined,\n emeController: __USE_EME_DRM__ ? EMEController : undefined,\n cmcdController: __USE_CMCD__ ? CMCDController : undefined,\n contentSteeringController: __USE_CONTENT_STEERING__\n ? ContentSteeringController\n : undefined,\n};\n\nfunction timelineConfig(): TimelineControllerConfig {\n return {\n cueHandler: Cues, // used by timeline-controller\n enableWebVTT: __USE_SUBTITLES__, // used by timeline-controller\n enableIMSC1: __USE_SUBTITLES__, // used by timeline-controller\n enableCEA708Captions: __USE_SUBTITLES__, // used by timeline-controller\n captionsTextTrack1Label: 'English', // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en', // used by timeline-controller\n captionsTextTrack2Label: 'Spanish', // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es', // used by timeline-controller\n captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack3LanguageCode: '', // used by timeline-controller\n captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack4LanguageCode: '', // used by timeline-controller\n renderTextTracksNatively: true,\n };\n}\n\n/**\n * @ignore\n */\nexport function mergeConfig(\n defaultConfig: HlsConfig,\n userConfig: Partial<HlsConfig>,\n): HlsConfig {\n if (\n (userConfig.liveSyncDurationCount ||\n userConfig.liveMaxLatencyDurationCount) &&\n (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)\n ) {\n throw new Error(\n \"Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration\",\n );\n }\n\n if (\n userConfig.liveMaxLatencyDurationCount !== undefined &&\n (userConfig.liveSyncDurationCount === undefined ||\n userConfig.liveMaxLatencyDurationCount <=\n userConfig.liveSyncDurationCount)\n ) {\n throw new Error(\n 'Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be greater than \"liveSyncDurationCount\"',\n );\n }\n\n if (\n userConfig.liveMaxLatencyDuration !== undefined &&\n (userConfig.liveSyncDuration === undefined ||\n userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)\n ) {\n throw new Error(\n 'Illegal hls.js config: \"liveMaxLatencyDuration\" must be greater than \"liveSyncDuration\"',\n );\n }\n\n const defaultsCopy = deepCpy(defaultConfig);\n\n // Backwards compatibility with deprecated config values\n const deprecatedSettingTypes = ['manifest', 'level', 'frag'];\n const deprecatedSettings = [\n 'TimeOut',\n 'MaxRetry',\n 'RetryDelay',\n 'MaxRetryTimeout',\n ];\n deprecatedSettingTypes.forEach((type) => {\n const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;\n const policyNotSet = userConfig[policyName] === undefined;\n const report: string[] = [];\n deprecatedSettings.forEach((setting) => {\n const deprecatedSetting = `${type}Loading${setting}`;\n const value = userConfig[deprecatedSetting];\n if (value !== undefined && policyNotSet) {\n report.push(deprecatedSetting);\n const settings: LoaderConfig = defaultsCopy[policyName].default;\n userConfig[policyName] = { default: settings };\n switch (setting) {\n case 'TimeOut':\n settings.maxLoadTimeMs = value;\n settings.maxTimeToFirstByteMs = value;\n break;\n case 'MaxRetry':\n settings.errorRetry!.maxNumRetry = value;\n settings.timeoutRetry!.maxNumRetry = value;\n break;\n case 'RetryDelay':\n settings.errorRetry!.retryDelayMs = value;\n settings.timeoutRetry!.retryDelayMs = value;\n break;\n case 'MaxRetryTimeout':\n settings.errorRetry!.maxRetryDelayMs = value;\n settings.timeoutRetry!.maxRetryDelayMs = value;\n break;\n }\n }\n });\n if (report.length) {\n logger.warn(\n `hls.js config: \"${report.join(\n '\", \"',\n )}\" setting(s) are deprecated, use \"${policyName}\": ${JSON.stringify(\n userConfig[policyName],\n )}`,\n );\n }\n });\n\n return {\n ...defaultsCopy,\n ...userConfig,\n };\n}\n\nfunction deepCpy(obj: any): any {\n if (obj && typeof obj === 'object') {\n if (Array.isArray(obj)) {\n return obj.map(deepCpy);\n }\n return Object.keys(obj).reduce((result, key) => {\n result[key] = deepCpy(obj[key]);\n return result;\n }, {});\n }\n return obj;\n}\n\n/**\n * @ignore\n */\nexport function enableStreamingMode(config) {\n const currentLoader = config.loader;\n if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {\n // If a developer has configured their own loader, respect that choice\n logger.log(\n '[config]: Custom loader detected, cannot enable progressive streaming',\n );\n config.progressive = false;\n } else {\n const canStreamProgressively = fetchSupported();\n if (canStreamProgressively) {\n config.loader = FetchLoader;\n config.progressive = true;\n config.enableSoftwareAES = true;\n logger.log('[config]: Progressive streaming enabled, using FetchLoader');\n }\n }\n}\n","import { 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","import { getMediaSource } from './utils/mediasource-helper';\nimport { mimeTypeForCodec } from './utils/codecs';\nimport type { ExtendedSourceBuffer } from './types/buffer';\n\nfunction getSourceBuffer(): typeof self.SourceBuffer {\n return self.SourceBuffer || (self as any).WebKitSourceBuffer;\n}\n\nexport function isMSESupported(): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n\n // if SourceBuffer is exposed ensure its API is valid\n // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBuffer = getSourceBuffer();\n return (\n !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function')\n );\n}\n\nexport function isSupported(): boolean {\n if (!isMSESupported()) {\n return false;\n }\n\n const mediaSource = getMediaSource();\n return (\n typeof mediaSource?.isTypeSupported === 'function' &&\n (['avc1.42E01E,mp4a.40.2', 'av01.0.01M.08', 'vp09.00.50.08'].some(\n (codecsForVideoContainer) =>\n mediaSource.isTypeSupported(\n mimeTypeForCodec(codecsForVideoContainer, 'video'),\n ),\n ) ||\n ['mp4a.40.2', 'fLaC'].some((codecForAudioContainer) =>\n mediaSource.isTypeSupported(\n mimeTypeForCodec(codecForAudioContainer, 'audio'),\n ),\n ))\n );\n}\n\nexport function changeTypeSupported(): boolean {\n const sourceBuffer = getSourceBuffer();\n return (\n typeof (sourceBuffer?.prototype as ExtendedSourceBuffer)?.changeType ===\n 'function'\n );\n}\n","import type { BufferInfo } from '../utils/buffer-helper';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { FragmentTracker } from './fragment-tracker';\n\nexport const STALL_MINIMUM_DURATION_MS = 250;\nexport const MAX_START_GAP_JUMP = 2.0;\nexport const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\nexport const SKIP_BUFFER_RANGE_START = 0.05;\n\nexport default class GapController {\n private config: HlsConfig;\n private media: HTMLMediaElement | null = null;\n private fragmentTracker: FragmentTracker;\n private hls: Hls;\n private nudgeRetry: number = 0;\n private stallReported: boolean = false;\n private stalled: number | null = null;\n private moved: boolean = false;\n private seeking: boolean = false;\n\n constructor(config, media, fragmentTracker, hls) {\n this.config = config;\n this.media = media;\n this.fragmentTracker = fragmentTracker;\n this.hls = hls;\n }\n\n public destroy() {\n this.media = null;\n // @ts-ignore\n this.hls = this.fragmentTracker = null;\n }\n\n /**\n * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n *\n * @param lastCurrentTime - Previously read playhead position\n */\n public poll(lastCurrentTime: number, activeFrag: Fragment | null) {\n const { config, media, stalled } = this;\n if (media === null) {\n return;\n }\n const { currentTime, seeking } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n this.moved = true;\n if (!seeking) {\n this.nudgeRetry = 0;\n }\n if (stalled !== null) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n logger.warn(\n `playback not stuck anymore @${currentTime}, after ${Math.round(\n stalledDuration,\n )}ms`,\n );\n this.stallReported = false;\n }\n this.stalled = null;\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n this.stalled = null;\n return;\n }\n\n // The playhead should not be moving\n if (\n (media.paused && !seeking) ||\n media.ended ||\n media.playbackRate === 0 ||\n !BufferHelper.getBuffered(media).length\n ) {\n this.nudgeRetry = 0;\n return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const nextStart = bufferInfo.nextStart || 0;\n\n if (seeking) {\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferGap =\n !nextStart ||\n (activeFrag && activeFrag.start <= currentTime) ||\n (nextStart - currentTime > MAX_START_GAP_JUMP &&\n !this.fragmentTracker.getPartialFragment(currentTime));\n if (hasEnoughBuffer || noBufferGap) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n if (!this.moved && this.stalled !== null) {\n // There is no playable buffer (seeked, waiting for buffer)\n const isBuffered = bufferInfo.len > 0;\n if (!isBuffered && !nextStart) {\n return;\n }\n // Jump start gaps within jump threshold\n const startJump =\n Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n\n // When joining a live stream with audio tracks, account for live playlist window sliding by allowing\n // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment\n // that begins over 1 target duration after the video start position.\n const level = this.hls.levels\n ? this.hls.levels[this.hls.currentLevel]\n : null;\n const isLive = level?.details?.live;\n const maxStartGapJump = isLive\n ? level!.details!.targetduration * 2\n : MAX_START_GAP_JUMP;\n const partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);\n if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {\n if (!media.paused) {\n this._trySkipBufferHole(partialOrGap);\n }\n return;\n }\n }\n\n // Start tracking stall time\n const tnow = self.performance.now();\n if (stalled === null) {\n this.stalled = tnow;\n return;\n }\n\n const stalledDuration = tnow - stalled;\n if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo);\n if (!this.media) {\n return;\n }\n }\n\n const bufferedWithHoles = BufferHelper.bufferInfo(\n media,\n currentTime,\n config.maxBufferHole,\n );\n this._tryFixBufferStall(bufferedWithHoles, stalledDuration);\n }\n\n /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDurationMs - The amount of time Hls.js has been stalling for.\n * @private\n */\n private _tryFixBufferStall(\n bufferInfo: BufferInfo,\n stalledDurationMs: number,\n ) {\n const { config, fragmentTracker, media } = this;\n if (media === null) {\n return;\n }\n const currentTime = media.currentTime;\n\n const partial = fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n const targetTime = this._trySkipBufferHole(partial);\n // we return here in this case, meaning\n // the branch below only executes when we haven't seeked to a new position\n if (targetTime || !this.media) {\n return;\n }\n }\n\n // if we haven't had to skip over a buffer hole of a partial fragment\n // we may just have to \"nudge\" the playlist as the browser decoding/rendering engine\n // needs to cross some sort of threshold covering all source-buffers content\n // to start playing properly.\n if (\n (bufferInfo.len > config.maxBufferHole ||\n (bufferInfo.nextStart &&\n bufferInfo.nextStart - currentTime < config.maxBufferHole)) &&\n stalledDurationMs > config.highBufferWatchdogPeriod * 1000\n ) {\n logger.warn('Trying to nudge playhead over buffer-hole');\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n private _reportStall(bufferInfo: BufferInfo) {\n const { hls, media, stallReported } = this;\n if (!stallReported && media) {\n // Report stalled error once\n this.stallReported = true;\n const error = new Error(\n `Playback stalling at @${\n media.currentTime\n } due to low buffer (${JSON.stringify(bufferInfo)})`,\n );\n logger.warn(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n error,\n buffer: bufferInfo.len,\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n private _trySkipBufferHole(partial: Fragment | null): number {\n const { config, hls, media } = this;\n if (media === null) {\n return 0;\n }\n\n // Check if currentTime is between unbuffered regions of partial fragments\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const startTime =\n currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;\n if (startTime) {\n const bufferStarved = bufferInfo.len <= config.maxBufferHole;\n const waiting =\n bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;\n const gapLength = startTime - currentTime;\n if (gapLength > 0 && (bufferStarved || waiting)) {\n // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial\n if (gapLength > config.maxBufferHole) {\n const { fragmentTracker } = this;\n let startGap = false;\n if (currentTime === 0) {\n const startFrag = fragmentTracker.getAppendedFrag(\n 0,\n PlaylistLevelType.MAIN,\n );\n if (startFrag && startTime < startFrag.end) {\n startGap = true;\n }\n }\n if (!startGap) {\n const startProvisioned =\n partial ||\n fragmentTracker.getAppendedFrag(\n currentTime,\n PlaylistLevelType.MAIN,\n );\n if (startProvisioned) {\n let moreToLoad = false;\n let pos = startProvisioned.end;\n while (pos < startTime) {\n const provisioned = fragmentTracker.getPartialFragment(pos);\n if (provisioned) {\n pos += provisioned.duration;\n } else {\n moreToLoad = true;\n break;\n }\n }\n if (moreToLoad) {\n return 0;\n }\n }\n }\n }\n const targetTime = Math.max(\n startTime + SKIP_BUFFER_RANGE_START,\n currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS,\n );\n logger.warn(\n `skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`,\n );\n this.moved = true;\n this.stalled = null;\n media.currentTime = targetTime;\n if (partial && !partial.gap) {\n const error = new Error(\n `fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`,\n );\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n error,\n reason: error.message,\n frag: partial,\n });\n }\n return targetTime;\n }\n }\n return 0;\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n private _tryNudgeBuffer() {\n const { config, hls, media, nudgeRetry } = this;\n if (media === null) {\n return;\n }\n const currentTime = media.currentTime;\n this.nudgeRetry++;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n const error = new Error(\n `Nudging 'currentTime' from ${currentTime} to ${targetTime}`,\n );\n logger.warn(error.message);\n media.currentTime = targetTime;\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n error,\n fatal: false,\n });\n } else {\n const error = new Error(\n `Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`,\n );\n logger.error(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n error,\n fatal: true,\n });\n }\n }\n}\n","import BaseStreamController, { State } from './base-stream-controller';\nimport { changeTypeSupported } from '../is-supported';\nimport { Events } from '../events';\nimport { BufferHelper, BufferInfo } from '../utils/buffer-helper';\nimport { FragmentState } from './fragment-tracker';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { ElementaryStreamTypes, Fragment } from '../loader/fragment';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport GapController, { MAX_START_GAP_JUMP } from './gap-controller';\nimport { ErrorDetails } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { Level } from '../types/level';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type KeyLoader from '../loader/key-loader';\nimport type { TransmuxerResult } from '../types/transmuxer';\nimport type { TrackSet } from '../types/track';\nimport type { SourceBufferName } from '../types/buffer';\nimport type {\n AudioTrackSwitchedData,\n AudioTrackSwitchingData,\n BufferCreatedData,\n BufferEOSData,\n BufferFlushedData,\n ErrorData,\n FragBufferedData,\n FragLoadedData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n LevelLoadedData,\n LevelLoadingData,\n LevelsUpdatedData,\n ManifestParsedData,\n MediaAttachedData,\n} from '../types/events';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nexport default class StreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n private audioCodecSwap: boolean = false;\n private gapController: GapController | null = null;\n private level: number = -1;\n private _forceStartLoad: boolean = false;\n private altAudio: boolean = false;\n private audioOnly: boolean = false;\n private fragPlaying: Fragment | null = null;\n private onvplaying: EventListener | null = null;\n private onvseeked: EventListener | null = null;\n private fragLastKbps: number = 0;\n private couldBacktrack: boolean = false;\n private backtrackFragment: Fragment | null = null;\n private audioCodecSwitch: boolean = false;\n private videoBuffer: any | null = null;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader,\n ) {\n super(\n hls,\n fragmentTracker,\n keyLoader,\n '[stream-controller]',\n PlaylistLevelType.MAIN,\n );\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this,\n );\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this,\n );\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n super.onHandlerDestroying();\n }\n\n public startLoad(startPosition: number): void {\n if (this.levels) {\n const { lastCurrentTime, hls } = this;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n if (hls.config.testBandwidth && this.levels.length > 1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n } else {\n startLevel = hls.firstAutoLevel;\n }\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n hls.nextLoadLevel = startLevel;\n this.level = hls.loadLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(\n `Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(\n 3,\n )}`,\n );\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n this.tick();\n } else {\n this._forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n public stopLoad() {\n this._forceStartLoad = false;\n super.stopLoad();\n }\n\n protected doTick() {\n switch (this.state) {\n case State.WAITING_LEVEL: {\n const { levels, level } = this;\n const currentLevel = levels?.[level];\n const details = currentLevel?.details;\n if (\n details &&\n (!details.live || this.levelLastLoaded === currentLevel)\n ) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.IDLE;\n break;\n } else if (this.hls.nextLoadLevel !== this.level) {\n this.state = State.IDLE;\n break;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY:\n {\n const now = self.performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || this.media?.seeking) {\n const { levels, level } = this;\n const currentLevel = levels?.[level];\n this.resetStartWhenNotLoaded(currentLevel || null);\n this.state = State.IDLE;\n }\n }\n break;\n default:\n break;\n }\n if (this.state === State.IDLE) {\n this.doTickIdle();\n }\n this.onTickEnd();\n }\n\n protected onTickEnd() {\n super.onTickEnd();\n this.checkBuffer();\n this.checkFragmentChanged();\n }\n\n private doTickIdle() {\n const { hls, levelLastLoaded, levels, media } = this;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch not enabled\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (\n levelLastLoaded === null ||\n (!media && (this.startFragRequested || !hls.config.startFragPrefetch))\n ) {\n return;\n }\n\n // If the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n return;\n }\n\n const level = hls.nextLoadLevel;\n if (!levels?.[level]) {\n return;\n }\n\n const levelInfo = levels[level];\n\n // if buffer length is less than maxBufLen try to load a new fragment\n\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null) {\n return;\n }\n\n const lastDetails = this.getLevelDetails();\n if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {\n const data: BufferEOSData = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(Events.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n\n // set next load level : this will trigger a playlist load if needed\n if (hls.loadLevel !== level && hls.manualLevel === -1) {\n this.log(`Adapting to level ${level} from level ${this.level}`);\n }\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (\n !levelDetails ||\n this.state === State.WAITING_LEVEL ||\n (levelDetails.live && this.levelLastLoaded !== levelInfo)\n ) {\n this.level = level;\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n const bufferLen = bufferInfo.len;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s\n const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);\n\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n if (\n this.backtrackFragment &&\n this.backtrackFragment.start > bufferInfo.end\n ) {\n this.backtrackFragment = null;\n }\n const targetBufferTime = this.backtrackFragment\n ? this.backtrackFragment.start\n : bufferInfo.end;\n let frag = this.getNextFragment(targetBufferTime, levelDetails);\n // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)\n if (\n this.couldBacktrack &&\n !this.fragPrevious &&\n frag &&\n frag.sn !== 'initSegment' &&\n this.fragmentTracker.getState(frag) !== FragmentState.OK\n ) {\n const backtrackSn = (this.backtrackFragment ?? frag).sn as number;\n const fragIdx = backtrackSn - levelDetails.startSN;\n const backtrackFrag = levelDetails.fragments[fragIdx - 1];\n if (backtrackFrag && frag.cc === backtrackFrag.cc) {\n frag = backtrackFrag;\n this.fragmentTracker.removeFragment(backtrackFrag);\n }\n } else if (this.backtrackFragment && bufferInfo.len) {\n this.backtrackFragment = null;\n }\n // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags\n if (frag && this.isLoopLoading(frag, targetBufferTime)) {\n const gapStart = frag.gap;\n if (!gapStart) {\n // Cleanup the fragment tracker before trying to find the next unbuffered fragment\n const type =\n this.audioOnly && !this.altAudio\n ? ElementaryStreamTypes.AUDIO\n : ElementaryStreamTypes.VIDEO;\n const mediaBuffer =\n (type === ElementaryStreamTypes.VIDEO\n ? this.videoBuffer\n : this.mediaBuffer) || this.media;\n if (mediaBuffer) {\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n }\n }\n frag = this.getNextFragmentLoopLoading(\n frag,\n levelDetails,\n bufferInfo,\n PlaylistLevelType.MAIN,\n maxBufLen,\n );\n }\n if (!frag) {\n return;\n }\n if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {\n frag = frag.initSegment;\n }\n\n this.loadFragment(frag, levelInfo, targetBufferTime);\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number,\n ) {\n // Check if fragment is not loaded\n const fragState = this.fragmentTracker.getState(frag);\n this.fragCurrent = frag;\n if (\n fragState === FragmentState.NOT_LOADED ||\n fragState === FragmentState.PARTIAL\n ) {\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, level);\n } else if (this.bitrateTest) {\n this.log(\n `Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`,\n );\n this._loadBitrateTestFrag(frag, level);\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, level, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n\n private getBufferedFrag(position) {\n return this.fragmentTracker.getBufferedFrag(\n position,\n PlaylistLevelType.MAIN,\n );\n }\n\n private followingBufferedFrag(frag: Fragment | null) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.end + 0.5);\n }\n return null;\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n public immediateLevelSwitch() {\n this.abortCurrentFrag();\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n public nextLevelSwitch() {\n const { levels, media } = this;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media?.readyState) {\n let fetchdelay;\n const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.start - 1);\n }\n const levelDetails = this.getLevelDetails();\n if (levelDetails?.live) {\n const bufferInfo = this.getMainFwdBufferInfo();\n // Do not flush in live stream with low buffer\n if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {\n return;\n }\n }\n if (!media.paused && levels) {\n // add a safety delay of 1s\n const nextLevelId = this.hls.nextLoadLevel;\n const nextLevel = levels[nextLevelId];\n const fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay =\n (this.fragCurrent.duration * nextLevel.maxBitrate) /\n (1000 * fragLastKbps) +\n 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // this.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n this.abortCurrentFrag();\n // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.\n const maxStart = nextBufferedFrag.maxStartPTS\n ? nextBufferedFrag.maxStartPTS\n : nextBufferedFrag.start;\n const fragDuration = nextBufferedFrag.duration;\n const startPts = Math.max(\n bufferedFrag.end,\n maxStart +\n Math.min(\n Math.max(\n fragDuration - this.config.maxFragLookUpTolerance,\n fragDuration * (this.couldBacktrack ? 0.5 : 0.125),\n ),\n fragDuration * (this.couldBacktrack ? 0.75 : 0.25),\n ),\n );\n this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n private abortCurrentFrag() {\n const fragCurrent = this.fragCurrent;\n this.fragCurrent = null;\n this.backtrackFragment = null;\n if (fragCurrent) {\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n switch (this.state) {\n case State.KEY_LOADING:\n case State.FRAG_LOADING:\n case State.FRAG_LOADING_WAITING_RETRY:\n case State.PARSING:\n case State.PARSED:\n this.state = State.IDLE;\n break;\n }\n this.nextLoadPosition = this.getLoadPosition();\n }\n\n protected flushMainBuffer(startOffset: number, endOffset: number) {\n super.flushMainBuffer(\n startOffset,\n endOffset,\n this.altAudio ? 'video' : null,\n );\n }\n\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData,\n ) {\n super.onMediaAttached(event, data);\n const media = data.media;\n this.onvplaying = this.onMediaPlaying.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n media.addEventListener('playing', this.onvplaying as EventListener);\n media.addEventListener('seeked', this.onvseeked as EventListener);\n this.gapController = new GapController(\n this.config,\n media,\n this.fragmentTracker,\n this.hls,\n );\n }\n\n protected onMediaDetaching() {\n const { media } = this;\n if (media && this.onvplaying && this.onvseeked) {\n media.removeEventListener('playing', this.onvplaying);\n media.removeEventListener('seeked', this.onvseeked);\n this.onvplaying = this.onvseeked = null;\n this.videoBuffer = null;\n }\n this.fragPlaying = null;\n if (this.gapController) {\n this.gapController.destroy();\n this.gapController = null;\n }\n super.onMediaDetaching();\n }\n\n private onMediaPlaying() {\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n }\n\n private onMediaSeeked() {\n const media = this.media;\n const currentTime = media ? media.currentTime : null;\n if (Number.isFinite(currentTime)) {\n this.log(`Media seeked to ${(currentTime as number).toFixed(3)}`);\n }\n\n // If seeked was issued before buffer was appended do not tick immediately\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null || bufferInfo.len === 0) {\n this.warn(\n `Main forward buffer length on \"seeked\" event ${\n bufferInfo ? bufferInfo.len : 'empty'\n })`,\n );\n return;\n }\n\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n }\n\n private onManifestLoading() {\n // reset buffer on manifest loading\n this.log('Trigger BUFFER_RESET');\n this.hls.trigger(Events.BUFFER_RESET, undefined);\n this.fragmentTracker.removeAllFragments();\n this.couldBacktrack = false;\n this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;\n this.levels =\n this.fragPlaying =\n this.backtrackFragment =\n this.levelLastLoaded =\n null;\n this.altAudio = this.audioOnly = this.startFragRequested = false;\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData,\n ) {\n // detect if we have different kind of audio codecs used amongst playlists\n let aac = false;\n let heaac = false;\n data.levels.forEach((level) => {\n const codec = level.audioCodec;\n if (codec) {\n aac = aac || codec.indexOf('mp4a.40.2') !== -1;\n heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;\n }\n });\n this.audioCodecSwitch = aac && heaac && !changeTypeSupported();\n if (this.audioCodecSwitch) {\n this.log(\n 'Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC',\n );\n }\n\n this.levels = data.levels;\n this.startFragRequested = false;\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { levels } = this;\n if (!levels || this.state !== State.IDLE) {\n return;\n }\n const level = levels[data.level];\n if (\n !level.details ||\n (level.details.live && this.levelLastLoaded !== level) ||\n this.waitForCdnTuneIn(level.details)\n ) {\n this.state = State.WAITING_LEVEL;\n }\n }\n\n private onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const { levels } = this;\n const newLevelId = data.level;\n const newDetails = data.details;\n const duration = newDetails.totalduration;\n\n if (!levels) {\n this.warn(`Levels were reset while loading level ${newLevelId}`);\n return;\n }\n this.log(\n `Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${\n newDetails.lastPartSn\n ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]`\n : ''\n }, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`,\n );\n\n const curLevel = levels[newLevelId];\n const fragCurrent = this.fragCurrent;\n if (\n fragCurrent &&\n (this.state === State.FRAG_LOADING ||\n this.state === State.FRAG_LOADING_WAITING_RETRY)\n ) {\n if (fragCurrent.level !== data.level && fragCurrent.loader) {\n this.abortCurrentFrag();\n }\n }\n\n let sliding = 0;\n if (newDetails.live || curLevel.details?.live) {\n this.checkLiveUpdate(newDetails);\n if (newDetails.deltaUpdateFailed) {\n return;\n }\n sliding = this.alignPlaylists(\n newDetails,\n curLevel.details,\n this.levelLastLoaded?.details,\n );\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = curLevel;\n\n this.hls.trigger(Events.LEVEL_UPDATED, {\n details: newDetails,\n level: newLevelId,\n });\n\n // only switch back to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n if (this.waitForCdnTuneIn(newDetails)) {\n // Wait for Low-Latency CDN Tune-in\n return;\n }\n this.state = State.IDLE;\n }\n\n if (!this.startFragRequested) {\n this.setStartPosition(newDetails, sliding);\n } else if (newDetails.live) {\n this.synchronizeToLiveEdge(newDetails);\n }\n\n // trigger handler right now\n this.tick();\n }\n\n protected _handleFragmentLoadProgress(data: FragLoadedData) {\n const { frag, part, payload } = data;\n const { levels } = this;\n if (!levels) {\n this.warn(\n `Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`,\n );\n return;\n }\n const currentLevel = levels[frag.level];\n const details = currentLevel.details as LevelDetails;\n if (!details) {\n this.warn(\n `Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`,\n );\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n const videoCodec = currentLevel.videoCodec;\n\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n const accurateTimeOffset = details.PTSKnown || !details.live;\n const initSegmentData = frag.initSegment?.data;\n const audioCodec = this._getAudioCodec(currentLevel);\n\n // transmux the MPEG-TS data to ISO-BMFF segments\n // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);\n const transmuxer = (this.transmuxer =\n this.transmuxer ||\n new TransmuxerInterface(\n this.hls,\n PlaylistLevelType.MAIN,\n this._handleTransmuxComplete.bind(this),\n this._handleTransmuxerFlush.bind(this),\n ));\n const partIndex = part ? part.index : -1;\n const partial = partIndex !== -1;\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount,\n payload.byteLength,\n partIndex,\n partial,\n );\n const initPTS = this.initPTS[frag.cc];\n\n transmuxer.push(\n payload,\n initSegmentData,\n audioCodec,\n videoCodec,\n frag,\n part,\n details.totalduration,\n accurateTimeOffset,\n chunkMeta,\n initPTS,\n );\n }\n\n private onAudioTrackSwitching(\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData,\n ) {\n // if any URL found on new audio track, it is an alternate audio track\n const fromAltAudio = this.altAudio;\n const altAudio = !!data.url;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n this.log(\n 'Switching on main audio, use media.buffered to schedule main fragment loading',\n );\n this.mediaBuffer = this.media;\n const fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent) {\n this.log('Switching to main audio track, cancel main fragment load');\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n // destroy transmuxer to force init segment generation (following audio switch)\n this.resetTransmuxer();\n // switch to IDLE state to load new fragment\n this.resetLoadingState();\n } else if (this.audioOnly) {\n // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off\n this.resetTransmuxer();\n }\n const hls = this.hls;\n // If switching from alt to main audio, flush all audio and trigger track switched\n if (fromAltAudio) {\n hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: Number.POSITIVE_INFINITY,\n type: null,\n });\n this.fragmentTracker.removeAllFragments();\n }\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);\n }\n }\n\n private onAudioTrackSwitched(\n event: Events.AUDIO_TRACK_SWITCHED,\n data: AudioTrackSwitchedData,\n ) {\n const trackId = data.id;\n const altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n const videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n this.log(\n 'Switching on alternate audio, use video.buffered to schedule main fragment loading',\n );\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n private onBufferCreated(\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData,\n ) {\n const tracks = data.tracks;\n let mediaTrack;\n let name;\n let alternate = false;\n for (const type in tracks) {\n const track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n const videoTrack = tracks[type];\n if (videoTrack) {\n this.videoBuffer = videoTrack.buffer;\n }\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n this.log(\n `Alternate track found, use ${name}.buffered to schedule main fragment loading`,\n );\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n private onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n const { frag, part } = data;\n if (frag && frag.type !== PlaylistLevelType.MAIN) {\n return;\n }\n if (this.fragContextChanged(frag)) {\n // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n // Avoid setting state back to IDLE, since that will interfere with a level switch\n this.warn(\n `Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${\n frag.level\n } finished buffering, but was aborted. state: ${this.state}`,\n );\n if (this.state === State.PARSED) {\n this.state = State.IDLE;\n }\n return;\n }\n const stats = part ? part.stats : frag.stats;\n this.fragLastKbps = Math.round(\n (8 * stats.total) / (stats.buffering.end - stats.loading.first),\n );\n if (frag.sn !== 'initSegment') {\n this.fragPrevious = frag;\n }\n this.fragBufferedComplete(frag, part);\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n this.state = State.ERROR;\n return;\n }\n switch (data.details) {\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_PARSING_ERROR:\n case ErrorDetails.FRAG_DECRYPT_ERROR:\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE\n if (\n !data.levelRetry &&\n this.state === State.WAITING_LEVEL &&\n data.context?.type === PlaylistContextType.LEVEL\n ) {\n this.state = State.IDLE;\n }\n break;\n case ErrorDetails.BUFFER_APPEND_ERROR:\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (!data.parent || data.parent !== 'main') {\n return;\n }\n if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {\n this.resetLoadingState();\n return;\n }\n if (this.reduceLengthAndFlushBuffer(data)) {\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n break;\n case ErrorDetails.INTERNAL_EXCEPTION:\n this.recoverWorkerError(data);\n break;\n default:\n break;\n }\n }\n\n // Checks the health of the buffer and attempts to resolve playback stalls.\n private checkBuffer() {\n const { media, gapController } = this;\n if (!media || !gapController || !media.readyState) {\n // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n return;\n }\n\n if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {\n // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers\n const activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;\n gapController.poll(this.lastCurrentTime, activeFrag);\n }\n\n this.lastCurrentTime = media.currentTime;\n }\n\n private onFragLoadEmergencyAborted() {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tickImmediate();\n }\n\n private onBufferFlushed(\n event: Events.BUFFER_FLUSHED,\n { type }: BufferFlushedData,\n ) {\n if (\n type !== ElementaryStreamTypes.AUDIO ||\n (this.audioOnly && !this.altAudio)\n ) {\n const mediaBuffer =\n (type === ElementaryStreamTypes.VIDEO\n ? this.videoBuffer\n : this.mediaBuffer) || this.media;\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n this.tick();\n }\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData,\n ) {\n if (this.level > -1 && this.fragCurrent) {\n this.level = this.fragCurrent.level;\n }\n this.levels = data.levels;\n }\n\n public swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n */\n protected seekToStartPos() {\n const { media } = this;\n if (!media) {\n return;\n }\n const currentTime = media.currentTime;\n let startPosition = this.startPosition;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n if (startPosition >= 0 && currentTime < startPosition) {\n if (media.seeking) {\n this.log(\n `could not seek to ${startPosition}, already seeking at ${currentTime}`,\n );\n return;\n }\n const buffered = BufferHelper.getBuffered(media);\n const bufferStart = buffered.length ? buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n if (\n delta > 0 &&\n (delta < this.config.maxBufferHole ||\n delta < this.config.maxFragLookUpTolerance)\n ) {\n this.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n this.log(\n `seek to target start position ${startPosition} from current time ${currentTime}`,\n );\n media.currentTime = startPosition;\n }\n }\n\n private _getAudioCodec(currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap && audioCodec) {\n this.log('Swapping audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n\n return audioCodec;\n }\n\n private _loadBitrateTestFrag(frag: Fragment, level: Level) {\n frag.bitrateTest = true;\n this._doFragLoad(frag, level).then((data) => {\n const { hls } = this;\n if (!data || this.fragContextChanged(frag)) {\n return;\n }\n level.fragmentError = 0;\n this.state = State.IDLE;\n this.startFragRequested = false;\n this.bitrateTest = false;\n const stats = frag.stats;\n // Bitrate tests fragments are neither parsed nor buffered\n stats.parsing.start =\n stats.parsing.end =\n stats.buffering.start =\n stats.buffering.end =\n self.performance.now();\n hls.trigger(Events.FRAG_LOADED, data as FragLoadedData);\n frag.bitrateTest = false;\n });\n }\n\n private _handleTransmuxComplete(transmuxResult: TransmuxerResult) {\n const id = 'main';\n const { hls } = this;\n const { remuxResult, chunkMeta } = transmuxResult;\n\n const context = this.getCurrentContext(chunkMeta);\n if (!context) {\n this.resetWhenMissingContext(chunkMeta);\n return;\n }\n const { frag, part, level } = context;\n const { video, text, id3, initSegment } = remuxResult;\n const { details } = level;\n // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track\n const audio = this.altAudio ? undefined : remuxResult.audio;\n\n // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n if (this.fragContextChanged(frag)) {\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n\n this.state = State.PARSING;\n\n if (initSegment) {\n if (initSegment?.tracks) {\n const mapFragment = frag.initSegment || frag;\n this._bufferInitSegment(\n level,\n initSegment.tracks,\n mapFragment,\n chunkMeta,\n );\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag: mapFragment,\n id,\n tracks: initSegment.tracks,\n });\n }\n\n // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038\n const initPTS = initSegment.initPTS as number;\n const timescale = initSegment.timescale as number;\n if (Number.isFinite(initPTS)) {\n this.initPTS[frag.cc] = { baseTime: initPTS, timescale };\n hls.trigger(Events.INIT_PTS_FOUND, { frag, id, initPTS, timescale });\n }\n }\n\n // Avoid buffering if backtracking this fragment\n if (video && details && frag.sn !== 'initSegment') {\n const prevFrag = details.fragments[frag.sn - 1 - details.startSN];\n const isFirstFragment = frag.sn === details.startSN;\n const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;\n if (remuxResult.independent !== false) {\n const { startPTS, endPTS, startDTS, endDTS } = video;\n if (part) {\n part.elementaryStreams[video.type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n } else {\n if (\n video.firstKeyFrame &&\n video.independent &&\n chunkMeta.id === 1 &&\n !isFirstInDiscontinuity\n ) {\n this.couldBacktrack = true;\n }\n if (video.dropped && video.independent) {\n // Backtrack if dropped frames create a gap after currentTime\n\n const bufferInfo = this.getMainFwdBufferInfo();\n const targetBufferTime =\n (bufferInfo ? bufferInfo.end : this.getLoadPosition()) +\n this.config.maxBufferHole;\n const startTime = video.firstKeyFramePTS\n ? video.firstKeyFramePTS\n : startPTS;\n if (\n !isFirstFragment &&\n targetBufferTime < startTime - this.config.maxBufferHole &&\n !isFirstInDiscontinuity\n ) {\n this.backtrack(frag);\n return;\n } else if (isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n }\n // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n frag.start,\n endPTS,\n frag.start,\n endDTS,\n true,\n );\n } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) {\n // Mark segment with a gap to skip large start gap\n frag.gap = true;\n }\n }\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n );\n if (this.backtrackFragment) {\n this.backtrackFragment = frag;\n }\n this.bufferFragmentData(\n video,\n frag,\n part,\n chunkMeta,\n isFirstFragment || isFirstInDiscontinuity,\n );\n } else if (isFirstFragment || isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n } else {\n this.backtrack(frag);\n return;\n }\n }\n\n if (audio) {\n const { startPTS, endPTS, startDTS, endDTS } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n }\n frag.setElementaryStreamInfo(\n ElementaryStreamTypes.AUDIO,\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n );\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n\n if (details && id3?.samples?.length) {\n const emittedID3: FragParsingMetadataData = {\n id,\n frag,\n details,\n samples: id3.samples,\n };\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (details && text) {\n const emittedText: FragParsingUserdataData = {\n id,\n frag,\n details,\n samples: text.samples,\n };\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n\n private _bufferInitSegment(\n currentLevel: Level,\n tracks: TrackSet,\n frag: Fragment,\n chunkMeta: ChunkMetadata,\n ) {\n if (this.state !== State.PARSING) {\n return;\n }\n\n this.audioOnly = !!tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\n delete tracks.audio;\n }\n // include levelCodec in audio and video tracks\n const { audio, video, audiovideo } = tracks;\n if (audio) {\n let audioCodec = currentLevel.audioCodec;\n const ua = navigator.userAgent.toLowerCase();\n if (this.audioCodecSwitch) {\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // In the case that AAC and HE-AAC audio codecs are signalled in manifest,\n // force HE-AAC, as it seems that most browsers prefers it.\n // don't force HE-AAC if mono stream, or in Firefox\n const audioMetadata = audio.metadata;\n if (\n audioMetadata &&\n 'channelCount' in audioMetadata &&\n (audioMetadata.channelCount || 1) !== 1 &&\n ua.indexOf('firefox') === -1\n ) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (\n audioCodec &&\n audioCodec.indexOf('mp4a.40.5') !== -1 &&\n ua.indexOf('android') !== -1 &&\n audio.container !== 'audio/mpeg'\n ) {\n // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n this.log(`Android: force audio codec to ${audioCodec}`);\n }\n if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {\n this.log(\n `Swapping manifest audio codec \"${currentLevel.audioCodec}\" for \"${audioCodec}\"`,\n );\n }\n audio.levelCodec = audioCodec;\n audio.id = 'main';\n this.log(\n `Init audio buffer, container:${\n audio.container\n }, codecs[selected/level/parsed]=[${audioCodec || ''}/${\n currentLevel.audioCodec || ''\n }/${audio.codec}]`,\n );\n }\n if (video) {\n video.levelCodec = currentLevel.videoCodec;\n video.id = 'main';\n this.log(\n `Init video buffer, container:${\n video.container\n }, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${\n video.codec\n }]`,\n );\n }\n if (audiovideo) {\n this.log(\n `Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`,\n );\n }\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n Object.keys(tracks).forEach((trackName) => {\n const track = tracks[trackName];\n const initSegment = track.initSegment;\n if (initSegment?.byteLength) {\n this.hls.trigger(Events.BUFFER_APPENDING, {\n type: trackName as SourceBufferName,\n data: initSegment,\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n });\n }\n });\n // trigger handler right now\n this.tickImmediate();\n }\n\n public getMainFwdBufferInfo(): BufferInfo | null {\n return this.getFwdBufferInfo(\n this.mediaBuffer ? this.mediaBuffer : this.media,\n PlaylistLevelType.MAIN,\n );\n }\n\n private backtrack(frag: Fragment) {\n this.couldBacktrack = true;\n // Causes findFragments to backtrack through fragments to find the keyframe\n this.backtrackFragment = frag;\n this.resetTransmuxer();\n this.flushBufferGap(frag);\n this.fragmentTracker.removeFragment(frag);\n this.fragPrevious = null;\n this.nextLoadPosition = frag.start;\n this.state = State.IDLE;\n }\n\n private checkFragmentChanged() {\n const video = this.media;\n let fragPlayingCurrent: Fragment | null = null;\n if (video && video.readyState > 1 && video.seeking === false) {\n const currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getAppendedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n this.backtrackFragment = null;\n const fragPlaying = this.fragPlaying;\n const fragCurrentLevel = fragPlayingCurrent.level;\n if (\n !fragPlaying ||\n fragPlayingCurrent.sn !== fragPlaying.sn ||\n fragPlaying.level !== fragCurrentLevel\n ) {\n this.fragPlaying = fragPlayingCurrent;\n this.hls.trigger(Events.FRAG_CHANGED, { frag: fragPlayingCurrent });\n if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {\n this.hls.trigger(Events.LEVEL_SWITCHED, {\n level: fragCurrentLevel,\n });\n }\n }\n }\n }\n }\n\n get nextLevel(): number {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get currentFrag(): Fragment | null {\n const media = this.media;\n if (media) {\n return this.fragPlaying || this.getAppendedFrag(media.currentTime);\n }\n return null;\n }\n\n get currentProgramDateTime(): Date | null {\n const media = this.media;\n if (media) {\n const currentTime = media.currentTime;\n const frag = this.currentFrag;\n if (\n frag &&\n Number.isFinite(currentTime) &&\n Number.isFinite(frag.programDateTime)\n ) {\n const epocMs =\n (frag.programDateTime as number) + (currentTime - frag.start) * 1000;\n return new Date(epocMs);\n }\n }\n return null;\n }\n\n get currentLevel(): number {\n const frag = this.currentFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get nextBufferedFrag() {\n const frag = this.currentFrag;\n if (frag) {\n return this.followingBufferedFrag(frag);\n }\n return null;\n }\n\n get forceStartLoad() {\n return this._forceStartLoad;\n }\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport PlaylistLoader from './loader/playlist-loader';\nimport ID3TrackController from './controller/id3-track-controller';\nimport LatencyController from './controller/latency-controller';\nimport LevelController from './controller/level-controller';\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport KeyLoader from './loader/key-loader';\nimport StreamController from './controller/stream-controller';\nimport { isMSESupported, isSupported } from './is-supported';\nimport { getMediaSource } from './utils/mediasource-helper';\nimport { logger, enableLogs } from './utils/logger';\nimport { enableStreamingMode, hlsDefaultConfig, mergeConfig } from './config';\nimport { EventEmitter } from 'eventemitter3';\nimport { Events } from './events';\nimport { ErrorTypes, ErrorDetails } from './errors';\nimport { isHdcpLevel, type HdcpLevel, type Level } from './types/level';\nimport type { HlsEventEmitter, HlsListeners } from './events';\nimport type AudioTrackController from './controller/audio-track-controller';\nimport type AbrController from './controller/abr-controller';\nimport type BufferController from './controller/buffer-controller';\nimport type CapLevelController from './controller/cap-level-controller';\nimport type CMCDController from './controller/cmcd-controller';\nimport type EMEController from './controller/eme-controller';\nimport type SubtitleTrackController from './controller/subtitle-track-controller';\nimport type {\n AbrComponentAPI,\n ComponentAPI,\n NetworkComponentAPI,\n} from './types/component-api';\nimport type {\n AudioSelectionOption,\n MediaPlaylist,\n SubtitleSelectionOption,\n VideoSelectionOption,\n} from './types/media-playlist';\nimport type { HlsConfig } from './config';\nimport type { BufferInfo } from './utils/buffer-helper';\nimport type AudioStreamController from './controller/audio-stream-controller';\nimport type BasePlaylistController from './controller/base-playlist-controller';\nimport type BaseStreamController from './controller/base-stream-controller';\nimport type ContentSteeringController from './controller/content-steering-controller';\nimport type ErrorController from './controller/error-controller';\nimport type FPSController from './controller/fps-controller';\n\n/**\n * The `Hls` class is the core of the HLS.js library used to instantiate player instances.\n * @public\n */\nexport default class Hls implements HlsEventEmitter {\n private static defaultConfig: HlsConfig | undefined;\n\n /**\n * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.\n */\n public readonly config: HlsConfig;\n\n /**\n * The configuration object provided on player instantiation.\n */\n public readonly userConfig: Partial<HlsConfig>;\n\n private coreComponents: ComponentAPI[];\n private networkControllers: NetworkComponentAPI[];\n private started: boolean = false;\n private _emitter: HlsEventEmitter = new EventEmitter();\n private _autoLevelCapping: number = -1;\n private _maxHdcpLevel: HdcpLevel = null;\n private abrController: AbrComponentAPI;\n private bufferController: BufferController;\n private capLevelController: CapLevelController;\n private latencyController: LatencyController;\n private levelController: LevelController;\n private streamController: StreamController;\n private audioTrackController: AudioTrackController;\n private subtitleTrackController: SubtitleTrackController;\n private emeController: EMEController;\n private cmcdController: CMCDController;\n private _media: HTMLMediaElement | null = null;\n private url: string | null = null;\n private triggeringException?: boolean;\n\n /**\n * Get the video-dev/hls.js package version.\n */\n static get version(): string {\n return __VERSION__;\n }\n\n /**\n * Check if the required MediaSource Extensions are available.\n */\n static isMSESupported(): boolean {\n return isMSESupported();\n }\n\n /**\n * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.\n */\n static isSupported(): boolean {\n return isSupported();\n }\n\n /**\n * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).\n */\n static getMediaSource(): typeof MediaSource | undefined {\n return getMediaSource();\n }\n\n static get Events(): typeof Events {\n return Events;\n }\n\n static get ErrorTypes(): typeof ErrorTypes {\n return ErrorTypes;\n }\n\n static get ErrorDetails(): typeof ErrorDetails {\n return ErrorDetails;\n }\n\n /**\n * Get the default configuration applied to new instances.\n */\n static get DefaultConfig(): HlsConfig {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * Replace the default configuration applied to new instances.\n */\n static set DefaultConfig(defaultConfig: HlsConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n * @param userConfig - Configuration options applied over `Hls.DefaultConfig`\n */\n constructor(userConfig: Partial<HlsConfig> = {}) {\n enableLogs(userConfig.debug || false, 'Hls instance');\n const config = (this.config = mergeConfig(Hls.DefaultConfig, userConfig));\n this.userConfig = userConfig;\n\n if (config.progressive) {\n enableStreamingMode(config);\n }\n\n // core controllers and network loaders\n const {\n abrController: ConfigAbrController,\n bufferController: ConfigBufferController,\n capLevelController: ConfigCapLevelController,\n errorController: ConfigErrorController,\n fpsController: ConfigFpsController,\n } = config;\n const errorController = new ConfigErrorController(this);\n const abrController = (this.abrController = new ConfigAbrController(this));\n const bufferController = (this.bufferController =\n new ConfigBufferController(this));\n const capLevelController = (this.capLevelController =\n new ConfigCapLevelController(this));\n\n const fpsController = new ConfigFpsController(this);\n const playListLoader = new PlaylistLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n const ConfigContentSteeringController = config.contentSteeringController;\n // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first\n const contentSteering = ConfigContentSteeringController\n ? new ConfigContentSteeringController(this)\n : null;\n const levelController = (this.levelController = new LevelController(\n this,\n contentSteering,\n ));\n // FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n const keyLoader = new KeyLoader(this.config);\n const streamController = (this.streamController = new StreamController(\n this,\n fragmentTracker,\n keyLoader,\n ));\n\n // Cap level controller uses streamController to flush the buffer\n capLevelController.setStreamController(streamController);\n // fpsController uses streamController to switch when frames are being dropped\n fpsController.setStreamController(streamController);\n\n const networkControllers: NetworkComponentAPI[] = [\n playListLoader,\n levelController,\n streamController,\n ];\n if (contentSteering) {\n networkControllers.splice(1, 0, contentSteering);\n }\n\n this.networkControllers = networkControllers;\n const coreComponents: ComponentAPI[] = [\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker,\n ];\n\n this.audioTrackController = this.createController(\n config.audioTrackController,\n networkControllers,\n );\n const AudioStreamControllerClass = config.audioStreamController;\n if (AudioStreamControllerClass) {\n networkControllers.push(\n new AudioStreamControllerClass(this, fragmentTracker, keyLoader),\n );\n }\n // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important\n this.subtitleTrackController = this.createController(\n config.subtitleTrackController,\n networkControllers,\n );\n const SubtitleStreamControllerClass = config.subtitleStreamController;\n if (SubtitleStreamControllerClass) {\n networkControllers.push(\n new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader),\n );\n }\n this.createController(config.timelineController, coreComponents);\n keyLoader.emeController = this.emeController = this.createController(\n config.emeController,\n coreComponents,\n );\n this.cmcdController = this.createController(\n config.cmcdController,\n coreComponents,\n );\n this.latencyController = this.createController(\n LatencyController,\n coreComponents,\n );\n\n this.coreComponents = coreComponents;\n\n // Error controller handles errors before and after all other controllers\n // This listener will be invoked after all other controllers error listeners\n networkControllers.push(errorController);\n const onErrorOut = errorController.onErrorOut;\n if (typeof onErrorOut === 'function') {\n this.on(Events.ERROR, onErrorOut, errorController);\n }\n }\n\n createController(ControllerClass, components) {\n if (ControllerClass) {\n const controllerInstance = new ControllerClass(this);\n if (components) {\n components.push(controllerInstance);\n }\n return controllerInstance;\n }\n return null;\n }\n\n // Delegate the EventEmitter through the public API of Hls.js\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any,\n ) {\n this._emitter.on(event, listener, context);\n }\n\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any,\n ) {\n this._emitter.once(event, listener, context);\n }\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E | undefined) {\n this._emitter.removeAllListeners(event);\n }\n\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E] | undefined,\n context: Context = this as any,\n once?: boolean | undefined,\n ) {\n this._emitter.off(event, listener, context, once);\n }\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][] {\n return this._emitter.listeners(event);\n }\n\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1],\n ): boolean {\n return this._emitter.emit(event, name, eventObject);\n }\n\n trigger<E extends keyof HlsListeners>(\n event: E,\n eventObject: Parameters<HlsListeners[E]>[1],\n ): boolean {\n if (this.config.debug) {\n return this.emit(event, event, eventObject);\n } else {\n try {\n return this.emit(event, event, eventObject);\n } catch (error) {\n logger.error(\n 'An internal error happened while handling event ' +\n event +\n '. Error message: \"' +\n error.message +\n '\". Here is a stacktrace:',\n error,\n );\n // Prevent recursion in error event handlers that throw #5497\n if (!this.triggeringException) {\n this.triggeringException = true;\n const fatal = event === Events.ERROR;\n this.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal,\n event,\n error,\n });\n this.triggeringException = false;\n }\n }\n }\n return false;\n }\n\n listenerCount<E extends keyof HlsListeners>(event: E): number {\n return this._emitter.listenerCount(event);\n }\n\n /**\n * Dispose of the instance\n */\n destroy() {\n logger.log('destroy');\n this.trigger(Events.DESTROYING, undefined);\n this.detachMedia();\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n this.url = null;\n\n this.networkControllers.forEach((component) => component.destroy());\n this.networkControllers.length = 0;\n\n this.coreComponents.forEach((component) => component.destroy());\n this.coreComponents.length = 0;\n // Remove any references that could be held in config options or callbacks\n const config = this.config;\n config.xhrSetup = config.fetchSetup = undefined;\n // @ts-ignore\n this.userConfig = null;\n }\n\n /**\n * Attaches Hls.js to a media element\n */\n attachMedia(media: HTMLMediaElement) {\n logger.log('attachMedia');\n this._media = media;\n this.trigger(Events.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach Hls.js from the media\n */\n detachMedia() {\n logger.log('detachMedia');\n this.trigger(Events.MEDIA_DETACHING, undefined);\n this._media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n */\n loadSource(url: string) {\n this.stopLoad();\n const media = this.media;\n const loadedSource = this.url;\n const loadingSource = (this.url = buildAbsoluteURL(\n self.location.href,\n url,\n {\n alwaysNormalize: true,\n },\n ));\n this._autoLevelCapping = -1;\n this._maxHdcpLevel = null;\n logger.log(`loadSource:${loadingSource}`);\n if (\n media &&\n loadedSource &&\n (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())\n ) {\n this.detachMedia();\n this.attachMedia(media);\n }\n // when attaching to a source URL, trigger a playlist load\n this.trigger(Events.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param startPosition - Set the start position to stream from.\n * Defaults to -1 (None: starts from earliest point)\n */\n startLoad(startPosition: number = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.started = true;\n this.networkControllers.forEach((controller) => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad() {\n logger.log('stopLoad');\n this.started = false;\n this.networkControllers.forEach((controller) => {\n controller.stopLoad();\n });\n }\n\n /**\n * Resumes stream controller segment loading if previously started.\n */\n resumeBuffering() {\n if (this.started) {\n this.networkControllers.forEach((controller) => {\n if ('fragmentLoader' in controller) {\n controller.startLoad(-1);\n }\n });\n }\n }\n\n /**\n * Stops stream controller segment loading without changing 'started' state like stopLoad().\n * This allows for media buffering to be paused without interupting playlist loading.\n */\n pauseBuffering() {\n this.networkControllers.forEach((controller) => {\n if ('fragmentLoader' in controller) {\n controller.stopLoad();\n }\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec() {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError() {\n logger.log('recoverMediaError');\n const media = this._media;\n this.detachMedia();\n if (media) {\n this.attachMedia(media);\n }\n }\n\n removeLevel(levelIndex: number) {\n this.levelController.removeLevel(levelIndex);\n }\n\n /**\n * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH\n */\n get levels(): Level[] {\n const levels = this.levelController.levels;\n return levels ? levels : [];\n }\n\n /**\n * Index of quality level (variant) currently played\n */\n get currentLevel(): number {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.\n */\n set currentLevel(newLevel: number) {\n logger.log(`set currentLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n */\n get nextLevel(): number {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @param newLevel - Pass -1 for automatic level selection\n */\n set nextLevel(newLevel: number) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n */\n get loadLevel(): number {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @param newLevel - Pass -1 for automatic level selection\n */\n set loadLevel(newLevel: number) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n */\n get nextLoadLevel(): number {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n */\n set nextLoadLevel(level: number) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n */\n get firstLevel(): number {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n */\n set firstLevel(newLevel: number) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return the desired start level for the first fragment that will be loaded.\n * The default value of -1 indicates automatic start level selection.\n * Setting hls.nextAutoLevel without setting a startLevel will result in\n * the nextAutoLevel value being used for one fragment load.\n */\n get startLevel(): number {\n const startLevel = this.levelController.startLevel;\n if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {\n return this.abrController.forcedAutoLevel;\n }\n return startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n */\n set startLevel(newLevel: number) {\n logger.log(`set startLevel:${newLevel}`);\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.minAutoLevel);\n }\n\n this.levelController.startLevel = newLevel;\n }\n\n /**\n * Whether level capping is enabled.\n * Default value is set via `config.capLevelToPlayerSize`.\n */\n get capLevelToPlayerSize(): boolean {\n return this.config.capLevelToPlayerSize;\n }\n\n /**\n * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.\n */\n set capLevelToPlayerSize(shouldStartCapping: boolean) {\n const newCapLevelToPlayerSize = !!shouldStartCapping;\n\n if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n if (newCapLevelToPlayerSize) {\n this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n } else {\n this.capLevelController.stopCapping();\n this.autoLevelCapping = -1;\n this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n }\n\n this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n }\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n get autoLevelCapping(): number {\n return this._autoLevelCapping;\n }\n\n /**\n * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.\n */\n get bandwidthEstimate(): number {\n const { bwEstimator } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimate();\n }\n\n set bandwidthEstimate(abrEwmaDefaultEstimate: number) {\n this.abrController.resetEstimator(abrEwmaDefaultEstimate);\n }\n\n /**\n * get time to first byte estimate\n * @type {number}\n */\n get ttfbEstimate(): number {\n const { bwEstimator } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimateTTFB();\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n set autoLevelCapping(newLevel: number) {\n if (this._autoLevelCapping !== newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n this.levelController.checkMaxAutoUpdated();\n }\n }\n\n get maxHdcpLevel(): HdcpLevel {\n return this._maxHdcpLevel;\n }\n\n set maxHdcpLevel(value: HdcpLevel) {\n if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {\n this._maxHdcpLevel = value;\n this.levelController.checkMaxAutoUpdated();\n }\n }\n\n /**\n * True when automatic level selection enabled\n */\n get autoLevelEnabled(): boolean {\n return this.levelController.manualLevel === -1;\n }\n\n /**\n * Level set manually (if any)\n */\n get manualLevel(): number {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n */\n get minAutoLevel(): number {\n const {\n levels,\n config: { minAutoBitrate },\n } = this;\n if (!levels) return 0;\n\n const len = levels.length;\n for (let i = 0; i < len; i++) {\n if (levels[i].maxBitrate >= minAutoBitrate) {\n return i;\n }\n }\n\n return 0;\n }\n\n /**\n * max level selectable in auto mode according to autoLevelCapping\n */\n get maxAutoLevel(): number {\n const { levels, autoLevelCapping, maxHdcpLevel } = this;\n\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels?.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n if (maxHdcpLevel) {\n for (let i = maxAutoLevel; i--; ) {\n const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];\n if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {\n return i;\n }\n }\n }\n\n return maxAutoLevel;\n }\n\n get firstAutoLevel(): number {\n return this.abrController.firstAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n */\n get nextAutoLevel(): number {\n return this.abrController.nextAutoLevel;\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon successful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n */\n set nextAutoLevel(nextLevel: number) {\n this.abrController.nextAutoLevel = nextLevel;\n }\n\n /**\n * get the datetime value relative to media.currentTime for the active level Program Date Time if present\n */\n public get playingDate(): Date | null {\n return this.streamController.currentProgramDateTime;\n }\n\n public get mainForwardBufferInfo(): BufferInfo | null {\n return this.streamController.getMainFwdBufferInfo();\n }\n\n /**\n * Find and select the best matching audio track, making a level switch when a Group change is necessary.\n * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.\n */\n public setAudioOption(\n audioOption: MediaPlaylist | AudioSelectionOption | undefined,\n ): MediaPlaylist | null {\n return this.audioTrackController?.setAudioOption(audioOption);\n }\n /**\n * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.\n * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.\n */\n public setSubtitleOption(\n subtitleOption: MediaPlaylist | SubtitleSelectionOption | undefined,\n ): MediaPlaylist | null {\n this.subtitleTrackController?.setSubtitleOption(subtitleOption);\n return null;\n }\n\n /**\n * Get the complete list of audio tracks across all media groups\n */\n get allAudioTracks(): Array<MediaPlaylist> {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.allAudioTracks : [];\n }\n\n /**\n * Get the list of selectable audio tracks\n */\n get audioTracks(): Array<MediaPlaylist> {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n */\n get audioTrack(): number {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n */\n set audioTrack(audioTrackId: number) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * get the complete list of subtitle tracks across all media groups\n */\n get allSubtitleTracks(): Array<MediaPlaylist> {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.allSubtitleTracks\n : [];\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n */\n get subtitleTracks(): Array<MediaPlaylist> {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.subtitleTracks\n : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n */\n get subtitleTrack(): number {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n get media() {\n return this._media;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n */\n set subtitleTrack(subtitleTrackId: number) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * Whether subtitle display is enabled or not\n */\n get subtitleDisplay(): boolean {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.subtitleDisplay\n : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n */\n set subtitleDisplay(value: boolean) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n\n /**\n * get mode for Low-Latency HLS loading\n */\n get lowLatencyMode(): boolean {\n return this.config.lowLatencyMode;\n }\n\n /**\n * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.\n */\n set lowLatencyMode(mode: boolean) {\n this.config.lowLatencyMode = mode;\n }\n\n /**\n * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)\n * @returns null prior to loading live Playlist\n */\n get liveSyncPosition(): number | null {\n return this.latencyController.liveSyncPosition;\n }\n\n /**\n * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)\n * @returns 0 before first playlist is loaded\n */\n get latency(): number {\n return this.latencyController.latency;\n }\n\n /**\n * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```\n * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```\n * @returns 0 before first playlist is loaded\n */\n get maxLatency(): number {\n return this.latencyController.maxLatency;\n }\n\n /**\n * target distance from the edge as calculated by the latency controller\n */\n get targetLatency(): number | null {\n return this.latencyController.targetLatency;\n }\n\n /**\n * the rate at which the edge of the current live playlist is advancing or 1 if there is none\n */\n get drift(): number | null {\n return this.latencyController.drift;\n }\n\n /**\n * set to true when startLoad is called before MANIFEST_PARSED event\n */\n get forceStartLoad(): boolean {\n return this.streamController.forceStartLoad;\n }\n}\n\nexport type {\n AudioSelectionOption,\n SubtitleSelectionOption,\n VideoSelectionOption,\n MediaPlaylist,\n ErrorDetails,\n ErrorTypes,\n Events,\n Level,\n HlsListeners,\n HlsEventEmitter,\n HlsConfig,\n BufferInfo,\n HdcpLevel,\n AbrController,\n AudioStreamController,\n AudioTrackController,\n BasePlaylistController,\n BaseStreamController,\n BufferController,\n CapLevelController,\n CMCDController,\n ContentSteeringController,\n EMEController,\n ErrorController,\n FPSController,\n SubtitleTrackController,\n};\nexport type {\n ComponentAPI,\n AbrComponentAPI,\n NetworkComponentAPI,\n} from './types/component-api';\nexport type {\n ABRControllerConfig,\n BufferControllerConfig,\n CapLevelControllerConfig,\n CMCDControllerConfig,\n EMEControllerConfig,\n DRMSystemsConfiguration,\n DRMSystemOptions,\n FPSControllerConfig,\n FragmentLoaderConfig,\n FragmentLoaderConstructor,\n HlsLoadPolicies,\n LevelControllerConfig,\n LoaderConfig,\n LoadPolicy,\n MP4RemuxerConfig,\n PlaylistLoaderConfig,\n PlaylistLoaderConstructor,\n RetryConfig,\n SelectionPreferences,\n StreamControllerConfig,\n LatencyControllerConfig,\n MetadataControllerConfig,\n TimelineControllerConfig,\n TSDemuxerConfig,\n} from './config';\nexport type { MediaKeySessionContext } from './controller/eme-controller';\nexport type { ILogger } from './utils/logger';\nexport type {\n PathwayClone,\n SteeringManifest,\n UriReplacement,\n} from './controller/content-steering-controller';\nexport type { SubtitleStreamController } from './controller/subtitle-stream-controller';\nexport type { TimelineController } from './controller/timeline-controller';\nexport type { CuesInterface } from './utils/cues';\nexport type {\n MediaKeyFunc,\n KeySystems,\n KeySystemFormats,\n} from './utils/mediakeys-helper';\nexport type { DateRange } from './loader/date-range';\nexport type { LoadStats } from './loader/load-stats';\nexport type { LevelKey } from './loader/level-key';\nexport type { LevelDetails } from './loader/level-details';\nexport type { SourceBufferName } from './types/buffer';\nexport type {\n MetadataSample,\n MetadataSchema,\n UserdataSample,\n} from './types/demuxer';\nexport type {\n HlsSkip,\n HlsUrlParameters,\n LevelAttributes,\n LevelParsed,\n VariableMap,\n} from './types/level';\nexport type { MediaDecodingInfo } from './utils/mediacapabilities-helper';\nexport type {\n PlaylistLevelType,\n HlsChunkPerformanceTiming,\n HlsPerformanceTiming,\n HlsProgressivePerformanceTiming,\n PlaylistContextType,\n PlaylistLoaderContext,\n FragmentLoaderContext,\n Loader,\n LoaderStats,\n LoaderContext,\n LoaderResponse,\n LoaderConfiguration,\n LoaderCallbacks,\n LoaderOnProgress,\n LoaderOnAbort,\n LoaderOnError,\n LoaderOnSuccess,\n LoaderOnTimeout,\n} from './types/loader';\nexport type {\n MediaAttributes,\n MediaPlaylistType,\n MainPlaylistType,\n AudioPlaylistType,\n SubtitlePlaylistType,\n} from './types/media-playlist';\nexport type { Track, TrackSet } from './types/track';\nexport type { ChunkMetadata } from './types/transmuxer';\nexport type {\n BaseSegment,\n Fragment,\n Part,\n ElementaryStreams,\n ElementaryStreamTypes,\n ElementaryStreamInfo,\n} from './loader/fragment';\nexport type {\n TrackLoadingData,\n TrackLoadedData,\n AudioTrackLoadedData,\n AudioTracksUpdatedData,\n AudioTrackSwitchedData,\n AudioTrackSwitchingData,\n BackBufferData,\n BufferAppendedData,\n BufferAppendingData,\n BufferCodecsData,\n BufferCreatedData,\n BufferEOSData,\n BufferFlushedData,\n BufferFlushingData,\n CuesParsedData,\n ErrorData,\n FPSDropData,\n FPSDropLevelCappingData,\n FragBufferedData,\n FragChangedData,\n FragDecryptedData,\n FragLoadedData,\n FragLoadEmergencyAbortedData,\n FragLoadingData,\n FragParsedData,\n FragParsingInitSegmentData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n InitPTSFoundData,\n KeyLoadedData,\n KeyLoadingData,\n LevelLoadedData,\n LevelLoadingData,\n LevelPTSUpdatedData,\n LevelsUpdatedData,\n LevelSwitchedData,\n LevelSwitchingData,\n LevelUpdatedData,\n LiveBackBufferData,\n ContentSteeringOptions,\n ManifestLoadedData,\n ManifestLoadingData,\n ManifestParsedData,\n MediaAttachedData,\n MediaAttachingData,\n NonNativeTextTrack,\n NonNativeTextTracksData,\n SteeringManifestLoadedData,\n SubtitleFragProcessedData,\n SubtitleTrackLoadedData,\n SubtitleTracksUpdatedData,\n SubtitleTrackSwitchData,\n} from './types/events';\nexport type {\n NetworkErrorAction,\n ErrorActionFlags,\n IErrorAction,\n} from './controller/error-controller';\nexport type { AttrList } from './utils/attr-list';\n"],"names":["URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","Error","path","normalizePath","buildURLFromParts","relativeParts","scheme","baseParts","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","substring","lastIndexOf","url","parts","split","reverse","join","replace","length","module","exports","isFiniteNumber","Number","isFinite","value","isSafeInteger","Math","abs","MAX_SAFE_INTEGER","Events","ErrorTypes","ErrorDetails","noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","exportLoggerFunctions","debugConfig","_len","arguments","functions","Array","_key","forEach","type","bind","func","self","console","consolePrintFn","enableLogs","id","e","logger","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","parseAttrList","_extends","this","_proto","prototype","decimalInteger","attrName","intValue","parseInt","Infinity","hexadecimalInteger","stringValue","slice","Uint8Array","i","hexadecimalIntegerAsNumber","decimalFloatingPoint","parseFloat","optionalFloat","defaultValue","enumeratedString","bool","decimalResolution","res","width","height","input","match","lastIndex","indexOf","_createClass","key","get","Object","keys","filter","attr","isSCTE35Attribute","DateRange","dateRangeAttr","dateRangeWithSameId","_startDate","_endDate","_badValueForSameId","previousAttr","hasOwnProperty","call","ID","Date","endDate","_isFiniteNumber","getTime","CLASS","duration","_isFiniteNumber2","_isFiniteNumber3","startDate","endOnNext","class","LoadStats","aborted","loaded","retry","total","chunkCount","bwEstimate","loading","start","first","end","parsing","buffering","ElementaryStreamTypes","BaseSegment","baseurl","_this$elementaryStrea","_byteRange","_url","relurl","elementaryStreams","setByteRange","previous","byteRangeEndOffset","byteRange","set","Fragment","_BaseSegment","_this","_decryptdata","rawProgramDateTime","programDateTime","tagList","sn","levelkeys","loader","keyLoader","level","cc","startPTS","endPTS","startDTS","endDTS","deltaPTS","maxStartPTS","minEndPTS","stats","data","bitrateTest","title","initSegment","endList","gap","urlId","_inheritsLoose","_proto2","setKeyFormat","keyFormat","getDecryptData","abortRequests","_this$loader","_this$keyLoader","abort","setElementaryStreamInfo","partial","min","max","clearElementaryStreamInfo","NONE","identity","keyFormats","_this$_decryptdata","encrypted","len","Part","_BaseSegment2","partAttrs","frag","index","_this2","fragOffset","independent","audio","video","audiovideo","LevelDetails","baseUrl","PTSKnown","alignedSliding","averagetargetduration","endCC","endSN","fragments","fragmentHint","partList","dateRanges","live","ageHeader","advancedDateTime","updated","advanced","availabilityDelay","misses","startCC","startSN","startTimeOffset","targetduration","totalduration","m3u8","version","canBlockReload","canSkipUntil","canSkipDateRanges","skippedSegments","recentlyRemovedDateranges","partHoldBack","holdBack","partTarget","preloadHint","renditionReports","tuneInGoal","deltaUpdateFailed","driftStartTime","driftEndTime","driftStart","driftEnd","encryptedFragments","playlistParsingError","variableList","hasVariableRefs","reloaded","partSnDiff","lastPartSn","partIndexDiff","lastPartIndex","floor","runTime","partEnd","fragmentEnd","_this$partList","_this$fragments","now","_this$partList2","_this$partList3","base64Decode","base64encodedStr","from","atob","c","charCodeAt","convertDataUriToArrayBytes","uri","keyIdbytes","paddedkeyIdbytes","colonsplit","keydata","semicolonsplit","commasplit","isbase64","splice","strToUtf8array","subarray","str","unescape","encodeURIComponent","optionalSelf","undefined","KeySystems","CLEARKEY","FAIRPLAY","PLAYREADY","WIDEVINE","KeySystemFormats","keySystemFormatToKeySystemDomain","format","KeySystemIds","keySystemIdToKeySystemDomain","systemId","keySystemDomainToKeySystemFormat","keySystem","getKeySystemsForConfig","config","drmSystems","widevineLicenseUrl","keySystemsToAttempt","push","_optionalSelf$navigat","requestMediaKeySystemAccess","navigator","sliceUint8","array","decoder","isHeader","offset","isFooter","getID3Data","front","readSize","size","canParse","getTimeStamp","frames","getID3Frames","frame","isTimeStampFrame","readTimeStamp","getFrameData","String","fromCharCode","id3Data","frameData","decodeFrame","decodePrivFrame","decodeURLFrame","decodeTextFrame","owner","utf8ArrayToStr","privateData","buffer","description","text","timeStampFrame","byteLength","pts33Bit","timestamp","round","exitOnNull","getTextDecoder","decoded","decode","idx","char2","char3","out","userAgent","includes","TextDecoder","Hex","hexDump","h","toString","UINT32_MAX","pow","RemuxerTrackIdConfig","id3","bin2str","apply","readUint16","val","readUint32","readSint32","readUint64","result","writeUint32","findBox","results","endbox","subresults","parseSegmentIndex","sidx","references","timescale","earliestPresentationTime","firstOffset","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","parseInitSegment","traks","trak","tkhd","trackId","mdhd","hdlr","hdlrType","soun","vide","stsdData","parseStsd","_objectSpread","trex","track","default","flags","stsd","sampleEntries","sampleEntriesEnd","fourCC","codec","encBox","sinf","schm","frma","avcCBox","toHex","codecBox","esdsBox","skipBERInteger","objectType","firstByte","audioObjectType","hvcCBox","profileByte","profileSpace","generalProfileIdc","profileCompat","tierFlag","levelIDC","constraintIndicator","toUpperCase","constraintString","byte","dvcCBox","profile","addLeadingZero","vpcCBox","bitDepth","av1CBox","highBitDepth","twelveBit","monochrome","chromaSubsamplingX","chromaSubsamplingY","chromaSamplePosition","bytes","limit","x","num","parseSinf","computeRawDurationFromSamples","trun","sampleCount","appendUint8Array","data1","data2","temp","parseSamples","timeOffset","seiSamples","videoData","samples","isHEVCFlavor","map","moof","moofOffset","byteOffset","traf","baseTime","tfdt","tfhd","tfhdFlags","defaultSampleDuration","defaultSampleSizePresent","defaultSampleSize","defaultSampleFlagsPresent","tfhdOffset","delimit","baseCodec","isHEVC","dataOffsetPresent","dataOffset","firstSampleFlagsPresent","sampleDurationPresent","sampleDuration","sampleSizePresent","sampleSize","sampleFlagsPresent","sampleCompositionOffsetsPresent","compositionOffset","trunOffset","sampleOffset","ix","naluTotalSize","naluSize","isSEIMessage","parseSEIMessageFromNALu","naluHeader","naluType","unescapedData","headerSize","pts","discardEPB","seiPtr","payloadType","payloadSize","b","leftOver","payPtr","providerCode","userStructure","userDataType","enabled","totalBytes","byteArray","uuidStrArray","userDataBytes","uuid","userData","EPBPositions","newLength","newData","sourceIndex","shift","mp4pssh","keyids","RangeError","kids","kidCount","k","DataView","setUint32","dataSize","payload","mp4Box","parsePssh","view","getUint32","dataSizeOrKidCount","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","preferManagedMediaSource","MediaSource","ManagedMediaSource","WebKitMediaSource","sampleEntryCodesISO","a3ds","alac","alaw","dra1","dtsc","dtse","dtsh","enca","fLaC","flac","FLAC","g719","g726","m4ae","mha1","mha2","mhm1","mhm2","mlpa","mp4a","Opus","opus","samr","sawb","sawp","sevc","sqcp","ssmv","twos","ulaw","avc1","avc2","avc3","avc4","avcp","av01","drac","dva1","dvav","dvh1","dvhe","encv","hev1","hvc1","mjp2","mp4v","mvc1","mvc2","mvc3","mvc4","resv","rv60","s263","svc1","svc2","vp08","vp09","stpp","wvtt","areCodecsMediaSourceSupported","codecs","some","isCodecMediaSourceSupported","_MediaSource$isTypeSu","isTypeSupported","mimeTypeForCodec","videoCodecPreferenceValue","videoCodec","codecsSetSelectionPreferenceValue","codecSet","reduce","preferenceValue","CODEC_COMPATIBLE_NAMES","AUDIO_CODEC_REGEXP","getCodecCompatibleName","m","lowerCaseCodec","codecsToCheck","getCodecCompatibleNameLower","toLowerCase","pickMostCompleteCodecName","parsedCodec","levelCodec","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","IS_MEDIA_PLAYLIST","LEVEL_PLAYLIST_REGEX_FAST","RegExp","source","LEVEL_PLAYLIST_REGEX_SLOW","M3U8Parser","findGroup","groups","mediaGroupId","group","resolve","isMediaPlaylist","parseMasterPlaylist","string","contentSteering","levels","sessionData","sessionKeys","levelsWithKnownCodecs","_level$unknownCodecs","bitrate","resolution","setCodecs","CODECS","unknownCodecs","tag","attributes","sessionAttrs","dataId","sessionKey","parseKey","variableAttributes","contentSteeringAttributes","pathwayId","parseStartTimeOffset","stripUnknownCodecLevels","parseMasterPlaylistMedia","groupsByType","AUDIO","audioCodec","SUBTITLES","textCodec","TYPE","medias","lang","LANGUAGE","assocLang","channels","CHANNELS","characteristics","CHARACTERISTICS","instreamId","media","groupId","autoselect","forced","URI","groupCodec","assignCodec","parseLevelPlaylist","levelUrlId","multivariantVariableList","currentInitSegment","currentSN","currentPart","discontinuityCounter","prevFrag","firstPdtIndex","createNextFrag","nextByteRange","setFragLevelKeys","assignProgramDateTime","value1","value2","skipAttrs","unshift","clientAttrs","dateRange","isValid","levelKey","mapAttrs","init","setInitSegment","byteRangeStartOffset","serverControlAttrs","partInfAttrs","previousFragmentPart","part","preloadHintAttrs","renditionReportAttrs","pop","fragmentLength","firstFragment","lastFragment","lastSn","fragPrev","backfillProgramDateTimes","keyTagAttributes","_keyAttrs$METHOD","_keyAttrs$KEYFORMAT","keyAttrs","decryptmethod","METHOD","decrypturi","decryptiv","decryptkeyformatversions","KEYFORMATVERSIONS","decryptkeyformat","KEYFORMAT","IV","resolvedUri","startAttributes","codecsAttributeValue","filtered","typeCodes","isCodecType","groupItem","codecProperty","codecValue","parse","endProgramDateTime","_isFiniteNumber4","BYTERANGE","PlaylistContextType","PlaylistLevelType","mapContextToLevelType","context","getResponseUrl","response","PlaylistLoader","hls","loaders","create","registerListeners","startLoad","startPosition","stopLoad","destroyInternalLoaders","on","MANIFEST_LOADING","onManifestLoading","LEVEL_LOADING","onLevelLoading","AUDIO_TRACK_LOADING","onAudioTrackLoading","SUBTITLE_TRACK_LOADING","onSubtitleTrackLoading","unregisterListeners","off","createInternalLoader","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","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","filterSubtitleTracks","textTrackList","tracks","kind","label","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","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","candidateDateRange","otherDateRange","LatencyController","currentTime","stallCount","_latency","timeupdateHandler","timeupdate","addEventListener","removeEventListener","_this$levelDetails","BUFFER_STALLED_ERROR","latency","computeLatency","_this$config","lowLatencyMode","maxLiveSyncPlaybackRate","targetLatency","distanceFromTarget","maxLatency","forwardBufferLength","rate","exp","edgeStalled","playbackRate","estimateLiveEdge","edge","age","liveEdge","liveMaxLatencyDuration","liveMaxLatencyDurationCount","_this$config2","liveSyncDuration","liveSyncDurationCount","userConfig","maxLiveSyncOnStallIncrease","syncPosition","drift","maxLevelUpdateAge","bufferedRanges","buffered","HdcpLevels","VideoRangeValues","HlsSkip","getSkipValue","HlsUrlParameters","msn","skip","addDirectives","href","Level","_attrs","frameRate","fragmentError","loadError","realBitrate","supportedPromise","supportedResult","_avgBitrate","_audioGroups","_subtitleGroups","_urlId","s","addGroupId","hasAudioGroup","hasGroup","hasSubtitleGroup","audioGroups","subtitleGroups","addFallback","audioGroupId","textGroupId","_this$audioGroups","_this$subtitleGroups","updateFromToPTS","fragFrom","fragTo","fragToPTS","updateFragPTSDTS","fragStartPts","fragEndPts","fragIdx","mergeDetails","oldDetails","newDetails","oldFragments","oldInit","PTSFrag","oldDateRanges","deltaDateRanges","ccOffset","intersectionFn","delta","newFrags","concat","oldFrags","oldFrag","newFrag","mapFragmentIntersection","_isFiniteNumber5","_currentInitSegment","newFragments","oldParts","newParts","oldPart","newPart","mapPartIntersection","adjustSliding","addSliding","getPartWith","partIndex","_level$details","findPart","reassignFragmentLevelIndexes","isTimeoutError","FRAG_LOAD_TIMEOUT","KEY_LOAD_TIMEOUT","getRetryConfig","isTimeout","getRetryDelay","retryConfig","retryCount","backoffFactor","backoff","getLoaderConfigWithoutReties","loderConfig","shouldRetry","loaderResponse","httpStatus","onLine","retryForHttpStatus","BinarySearch","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","findFragmentByPTS","fragPrevious","bufferEnd","maxFragLookUpTolerance","nextFragLookupTolerance","fragNext","bufferEdgeError","fragmentWithinToleranceTest","firstDuration","fragmentWithinFastStartSwitch","foundFragment","candidate","candidateLookupTolerance","pdtWithinToleranceTest","pdtBufferEnd","NetworkErrorAction","ErrorActionFlags","ErrorController","playlistError","penalizedRenditions","onErrorOut","getVariantLevelIndex","loadLevel","_data$frag","_data$level","FRAG_LOAD_ERROR","KEY_LOAD_ERROR","errorAction","getFragRetryOrSwitchAction","FRAG_PARSING_ERROR","action","FRAG_GAP","FRAG_DECRYPT_ERROR","_data$context","_data$context$levelDe","getPlaylistRetryOrSwitchAction","levelRetry","getLevelSwitchAction","KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED","restrictedHdcpLevel","hdcpLevel","keySystemError","BUFFER_ADD_CODEC_ERROR","REMUX_ALLOC_ERROR","BUFFER_APPEND_ERROR","INTERNAL_EXCEPTION","BUFFER_APPENDING_ERROR","BUFFER_FULL_ERROR","LEVEL_SWITCH_ERROR","BUFFER_SEEK_OVER_HOLE","BUFFER_NUDGE_ON_STALL","KEY_SYSTEM_ERROR","variantLevelIndex","fragLoadPolicy","keyLoadPolicy","startsWith","fragmentErrors","acc","_data$frag2","_data$context2","errorDetails","nextLevel","minAutoLevel","maxAutoLevel","autoLevelEnabled","_ret","fragErrorType","findAudioCodecAlternate","sourceBufferName","findVideoCodecAlternate","_ref3","playlistErrorType","playlistErrorGroupId","_level$audioGroups","_level$subtitleGroups","levelCandidate","fragCandidate","nextAutoLevel","_data$errorAction","sendAlternateToPenaltyBox","resolved","recoverMediaError","switchLevel","maxHdcpLevel","nextLoadLevel","BasePlaylistController","logPrefix","timer","requestScheduled","canLoad","clearTimer","clearTimeout","loadPlaylist","switchParams","playlistUri","current","foundIndex","currentGoal","hlsUrlParameters","shouldLoadPlaylist","playlist","shouldReloadPlaylist","playlistLoaded","previousDetails","elapsed","endSn","lastPart","lastAdvanced","cdnAge","segments","toFixed","getDeliveryDirectives","bufferInfo","mainForwardBufferInfo","position","reloadInterval","distanceToLiveEdgeMs","lastSegmentDuration","computeReloadInterval","estimatedTimeUntilUpdate","setTimeout","previousDeliveryDirectives","checkRetry","errorEvent","_ref$retryCount","_errorEvent$context","delay","EWMA","halfLife","estimate","weight","alpha_","estimate_","totalWeight_","sample","adjAlpha","getTotalWeight","getEstimate","zeroFactor","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultTTFB","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","defaultTTFB_","ttfb_","update","durationMs","numBytes","durationS","bandwidthInBps","sampleTTFB","ttfb","seconds","sqrt","canEstimate","getEstimateTTFB","SUPPORTED_INFO_DEFAULT","supported","configurations","decodingInfoResults","powerEfficient","smooth","SUPPORTED_INFO_CACHE","getMediaDecodingInfoPromise","audioTracksByGroup","mediaCapabilities","videoCodecs","audioCodecs","Promise","baseVideoConfiguration","ceil","averageBitrate","framerate","videoRange","transferFunction","contentType","_audioTracksByGroup$g","channelsNumber","all","configuration","decodingInfoKey","mediaConfig","spatialRendering","getMediaDecodingInfoKey","decodingInfo","then","catch","getVideoSelectionOptions","currentVideoRange","videoPreference","preferHDR","allowedVideoRanges","matchMedia","mediaQueryList","badQuery","matches","isHdrSupported","range","logStartCodecCandidateIgnored","codeSet","findMatchingOption","option","matchPredicate","matchesOption","isDefault","characteristicsA","characteristicsB","arrA","arrB","el","characteristicsMatch","audioMatchPredicate","searchDownAndUpList","arr","searchIndex","AbrController","lastLevelLoadSec","lastLoadedFragLevel","firstSelection","_nextAutoLevel","nextAutoLevelKey","codecTiers","fragCurrent","partCurrent","bitrateTestDelay","bwEstimator","_abandonRulesCheck","timeLoading","paused","readyState","ttfbEstimate","bufferStarvationDelay","loadedFirstByte","getBwEstimate","expectedLen","timeStreaming","loadRate","fragLoadedDelay","bwe","fragLevelNextLoadedDelay","levelNextBitrate","maxBitrate","getTimeToLoadFrag","nextLoadLevelBitrate","abrBandWidthUpFactor","resetEstimator","FRAG_LOAD_EMERGENCY_ABORTED","initEstimator","abrEwmaDefaultEstimate","abrEwmaSlowVoD","abrEwmaFastVoD","FRAG_LOADING","onFragLoading","FRAG_LOADED","onFragLoaded","FRAG_BUFFERED","onFragBuffered","LEVEL_SWITCHING","onLevelSwitching","onLevelLoaded","LEVELS_UPDATED","onLevelsUpdated","MAX_AUTO_LEVEL_UPDATED","onMaxAutoLevelUpdated","_data$part","ignoreFragment","setInterval","timeToFirstByteSec","bandwidth","fragSizeBits","isSwitch","timeLoadingMs","abrEwmaSlowLive","abrEwmaFastLive","abrMaxWithRealBitrate","loadedBytes","loadedDuration","fragBufferedData","processingMs","clearInterval","getAutoLevelKey","getStarvationDelay","getNextABRAutoLevel","currentFragDuration","avgbw","bwFactor","abrBandWidthFactor","bwUpFactor","bestLevel","findBestLevel","maxStarvationDelay","maxLoadingDelay","minLevel","autoLevel","currentBw","maxFetchDuration","selectionBaseLevel","firstLevel","_this$hls","allAudioTracks","currentCodecSet","currentFrameRate","audioPreference","trackGroup","hasDefault","hasAutoSelect","channelsKey","hasDefaultAudio","hasAutoSelectAudio","getAudioTracksByGroup","tiers","tier","minBitrate","minHeight","minFramerate","maxScore","videoRanges","SDR","lesserWidthOrHeight","score","audioGroup","getCodecTiers","startTier","codecSets","channelsPreference","audioCodecPreference","preferStereo","hasStereo","hasCurrentVideoRange","selectedScore","_getVideoSelectionOpt","matchingVideoRanges","maxHeight","maxFramerate","selected","candidateTier","getStartCodecTier","ttfbEstimateSec","levelsSkipped","_levelInfo$supportedR","levelInfo","upSwitch","useMediaCapabilities","maxChannels","audioChannels","audioTrackGroup","requiresMediaCapabilitiesDecodingInfo","removeLevel","adjustedbw","avgDuration","fetchDuration","forcedAutoLevel","v","_this$hls2","maxStartDelay","abrAutoLevel","clamped","useEstimate","loadedFirstFrag","nextABRAutoLevel","firstAutoLevel","_this$hls3","TaskLoop","_boundTick","_tickTimer","_tickInterval","_tickCallCount","tick","onHandlerDestroying","onHandlerDestroyed","clearNextTick","hasInterval","hasNextTick","millis","doTick","tickImmediate","FragmentState","FragmentTracker","activePartLists","endListFragments","timeRanges","bufferPadding","hasGaps","BUFFER_APPENDED","onBufferAppended","getAppendedFrag","activeParts","activePart","appendedPTS","getBufferedFrag","fragmentEntity","body","detectEvictedFragments","elementaryStream","timeRange","playlistType","appendedPart","appendedPartSn","esData","isNotBuffered","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","isFragHint","streamInfo","getBufferedTimes","isPartial","removeParts","snToKeep","fragBuffered","force","getPartialFragment","timePadding","bestFragment","bestOverlap","isEndListAppended","lastFragmentEntity","getState","_this3","hasFragment","hasParts","_this$activePartLists","removeFragmentsInRange","withGapOnly","unbufferedOnly","_this4","snToRemove","removeAllFragments","_fragmentEntity$range","_fragmentEntity$range2","_fragmentEntity$range3","noopBuffered","BufferHelper","isBuffered","getBuffered","pos","maxHoleDuration","vbuffered","bufferedInfo","nextStart","sort","a","diff","buffered2","buf2len","buf2end","bufferStartNext","bufferLen","bufferStart","ChunkMetadata","transmuxing","executeStart","executeEnd","findFirstFragWithCC","_fragments$i","adjustFragmentStart","sliding","adjustSlidingStart","alignStream","lastFrag","switchDetails","shouldAlignOnDiscontinuities","referenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","findDiscontinuousReferenceFrag","alignDiscontinuities","alignMediaPlaylistByPDT","refDetails","refFragments","refFrag","targetCC","refPDT","targetPDT","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","_frag$decryptdata","byteRangeStart","byteRangeEnd","fragmentLen","MEDIA_ERROR","_Error","_wrapNativeSuper","AESCrypto","subtle","aesIV","decrypt","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","ksRows","keySize","keySchedule","invKeySchedule","initTable","uint8ArrayToUint32Array_","arrayBuffer","newArray","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","d","xi","sx","x2","x4","x8","t","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","onWebCryptoError","aesKey","splitPoint","msg","TimeRanges","r","State","BaseStreamController","_TaskLoop","fragmentTracker","transmuxer","_state","mediaBuffer","lastCurrentTime","nextLoadPosition","loadedmetadata","retryDate","fragmentLoader","levelLastLoaded","startFragRequested","decrypter","initPTS","onvseeking","onvended","onManifestLoaded","_assertThisInitialized","onTickEnd","resetTransmuxer","state","_streamEnded","getLevelDetails","_this$levelLastLoaded","onMediaSeeking","onMediaEnded","autoStartLoad","ended","detach","maxBufferHole","resetLoadingState","tolerance","fragStartOffset","fragEndOffset","pastFragment","loadFragment","targetBufferTime","_loadFragForPlayback","_doFragLoad","fragContextChanged","_handleFragmentLoadProgress","_handleFragmentLoadComplete","resetFragmentLoading","clearTrackerIfNeeded","_this$mediaBuffer","getFwdBufferInfo","minForwardBufferLength","maxBufferLength","backtrackFragment","reduceMaxBufferLength","checkLiveUpdate","flushMainBuffer","flushScope","_loadInitSegment","decryptData","decryptedData","FRAG_DECRYPTED","tstart","tdecrypt","completeInitSegmentLoad","fragBufferedComplete","_frag$startPTS","_frag$endPTS","_this$fragCurrent","_this$fragPrevious","NaN","_this$levels","seekToStartPos","fragLoadedEndData","partsLoaded","complete","fragLoaded","chunkMeta","progressCallback","keyLoadingPromise","loadClear","keyLoadedData","KEY_LOADED","KEY_LOADING","getNextPart","doFragPartsLoad","handleFragLoadError","loadedEndOfParts","dataOnProgress","progressive","fragLoadedData","fromPart","_this5","initialPartList","loadedPart","nextPart","handleFragLoadAborted","OTHER_ERROR","_handleTransmuxerFlush","getCurrentContext","updateLevelTiming","getFragmentWithSN","bufferFragmentData","noBacktracking","_buffer","BUFFER_APPENDING","dropped","flushBufferGap","fragDuration","segmentFraction","bufferable","getLoadPosition","getFwdBufferInfoAtPos","bufferedFragAtPos","getMaxBufferLength","levelBitrate","maxBufLen","maxBufferSize","maxMaxBufferLength","threshold","minLength","reducedLength","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","alignPlaylists","slidingStart","firstLevelLoad","aligned","alignedSlidingStart","waitForCdnTuneIn","setStartPosition","offsetInMultivariantPlaylist","onFragmentOrKeyLoadError","filterType","_this$fragCurrent2","gapTagEncountered","_ref2$retryCount","resetStartWhenNotLoaded","resetFragmentErrors","reduceLengthAndFlushBuffer","flushBuffer","afterBufferFlushed","bufferType","bufferedTimeRanges","resetWhenMissingContext","removeUnbufferedFrags","_this$transmuxer","_this6","parsedDuration","LEVEL_PTS_UPDATED","FRAG_PARSED","recoverWorkerError","nextState","previousState","ChunkCache","chunks","dataLength","chunk","concatUint8Arrays","dummyTrack","inputTimeScale","pid","sequenceNumber","BaseAudioDemuxer","_audioTrack","_id3Track","frameIndex","cachedData","basePTS","lastPTS","resetInitSegment","trackDuration","resetTimeStamp","deaultTimestamp","resetContiguity","appendFrame","demux","lastDataIndex","initPTSFn","dts","partialData","videoTrack","demuxSampleAes","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","headerLength","frameLength","newOffset","initTrackConfig","observer","samplerate","adtsObjectType","adtsExtensionSamplingIndex","adtsChannelConfig","manifestCodec","adtsSamplingRates","adtsSamplingIndex","channelCount","emit","getAudioConfig","getFrameDuration","unit","stamp","header","parseFrameHeader","missing","chromeVersion","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","mpegVersion","mpegLayer","bitRateIndex","sampleRateIndex","paddingBit","channelMode","bitRate","sampleCoefficient","bytesInSlot","AACDemuxer","_BaseAudioDemuxer","container","segmentCodec","MpegAudio","ADTS","canGetFrameLength","emsgSchemePattern","MP4Demuxer","txtTrack","captionTrack","initData","_initData$video","_initData$audio","hasMoofData","videoSamples","segmentedData","segmentedRange","valid","remainder","moofs","last","segmentValidRange","extractID3Track","emsgs","emsgInfo","schemeIdUri","timeScale","presentationTimeDelta","presentationTime","eventDuration","leftPresentationTime","rightPresentationTime","_isSafeInteger","parseEmsg","getAudioBSID","bsid","numBits","mask","bits","AC3Demuxer","samplingRateCode","frameSizeCode","skipCount","lfeon","bsmod","BaseVideoParser","VideoSample","createVideoSample","units","getLastNalUnit","_VideoSample","lastUnit","pushAccessUnit","nbSamples","lastSample","ExpGolomb","bytesAvailable","bitsAvailable","loadWord","workingBytes","availableBytes","skipBits","count","skipBytes","readBits","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","readSliceType","AvcVideoParser","_BaseVideoParser","parseAVCPES","pes","parseAVCNALu","spsfound","audFound","_VideoSample2","iskey","sliceType","_track$pixelRatio","_track$pixelRatio2","sps","codecarray","codecstring","pps","overflow","naluState","lastState","lastUnitStart","lastUnitType","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","callback","curUnit","encryptedBuffer","decryptedBuffer","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","uint8DecryptedData","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","PACKET_LENGTH","TSDemuxer","typeSupported","sampleAes","pmtParsed","_duration","_pmtId","_videoTrack","_txtTrack","aacOverFlow","videoParser","syncOffset","scanwindow","foundPat","packetStart","tsPackets","parsePID","pesData","isSampleAes","videoPid","audioPid","id3Pid","audioData","unknownPID","pmtId","tsPacketErrors","stt","parsePES","parseAACPES","parseMPEGPES","parseAC3PES","parseID3PES","parsePAT","parsedPIDs","parsePMT","segmentVideoCodec","segmentAudioCodec","emitParsingError","demuxResult","extractRemainingSamples","frameMissingBytes","sampleLength","frameOverflowBytes","recoverable","frameDuration","AC3","id3Sample","tableEnd","esInfoLength","logEncryptedSamplesFoundInUnencryptedStream","mpeg","mp3","ac3","parsePos","remaining","descriptorLen","stream","pesLen","pesHdrLen","pesPts","pesDts","pesFlags","payloadStartOffset","dataLen","MP3Demuxer","AAC","getSilentFrame","MP4","types","avcC","btrt","dinf","dref","esds","ftyp","mdat","mdia","mfhd","minf","moov","dac3","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsz","stts","vmhd","smhd","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","upperWordDuration","lowerWordDuration","baseMediaDecodeTime","boxes","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","audioStsd","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","cts","arraylen","isLeading","paddingValue","isNonSync","degradPrio","movie","MPEG_TS_CLOCK_FREQ_HZ","toTimescaleFromBase","destScale","srcBase","toMsFromMpegTsClock","safariWebkitVersion","MP4Remuxer","vendor","ISGenerated","_initPTS","_initDTS","nextAvcDts","nextAudioPts","videoSampleDuration","isAudioContiguous","isVideoContiguous","videoTrackConfig","defaultTimeStamp","resetNextTimestamp","getVideoStartPts","rolloverDetected","minPTS","normalizePts","remux","accurateTimeOffset","audioTimeOffset","videoTimeOffset","hasAudio","hasVideo","enoughAudioSamples","enoughVideoSamples","_videoTrack$pixelRati","_config$pixelRatio","_videoTrack$pixelRati2","_config$pixelRatio2","generateIS","firstKeyFramePTS","firstKeyFrameIndex","findKeyframeIndex","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","dtsStep","nbUnits","sampleLen","mdatSize","MUX_ERROR","stretchedLastFrame","minDtsDelta","minPtsDelta","maxDtsDelta","maxPtsDelta","VideoSampleUnits","mp4SampleLength","unitData","unitDataLen","ptsDelta","lastFrameDuration","stretchShortVideoTrack","gapTolerance","deltaToFrameEnd","compositionTimeOffset","Mp4Sample","nextDts","nextPts","nb","getSamplesPerFrame","scaleFactor","inputSampleDuration","rawMPEG","alignedWithVideo","timeOffsetMpegTS","maxAudioFramesDrift","newStamp","fillFrame","audioSample","unitLen","remuxEmptyAudio","init90kHz","silentFrame","reference","isKeyframe","PassThroughRemuxer","emitInitSegment","initTracks","lastEndTime","defaultInitPTS","generateInitSegment","encBoxes","isAudio","enc","tenc","tencKeyId","patchEncyptionData","getParsedTrackCodec","_initData","_initData2","rawDuration","videoDuration","audioDuration","trafs","trackDefault","truns","sidxMinStart","sidxMaxEnd","sidxDuration","sidxs","subSegmentDuration","dur","ref","getDuration","fmp4","getStartDTS","decodeTime","minDuration","isInvalidInitPts","upper","lower","offsetStartDTS","muxConfig","Transmuxer","async","demuxer","remuxer","decryptionPromise","transmuxConfig","currentTransmuxState","configure","uintData","discontinuity","trackSwitch","initSegmentChange","defaultInitPts","initSegmentData","encryptionType","getEncryptionType","getDecrypter","emptyResult","resetMuxers","needsProbing","configureTransmuxer","resetInitialTimestamp","transmux","currentState","transmuxResults","demuxResultOrPromise","isPromise","flushRemux","_this$currentTransmux","remuxResult","transmuxSampleAes","transmuxUnencrypted","_demux","mux","_muxConfig$i$demux","Remuxer","Demuxer","p","Function","TransmuxConfig","TransmuxState","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","m2tsTypeSupported","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","subtitleOptionsIdentical","trackList1","trackList2","mediaAttributesIdentical","attrs1","attrs2","customAttributes","stableRenditionId","subtitleAttribute","subtitleTrackMatchesTextTrack","subtitleTrack","language","AudioStreamController","_BaseStreamController","videoBuffer","videoTrackCC","waitingVideoCC","bufferedTrack","switchingTrack","waitingData","mainDetails","flushing","bufferFlushed","cachedTrackLoadedData","AUDIO_TRACKS_UPDATED","onAudioTracksUpdated","AUDIO_TRACK_SWITCHING","onAudioTrackSwitching","onAudioTrackLoaded","BUFFER_RESET","onBufferReset","BUFFER_CREATED","onBufferCreated","BUFFER_FLUSHED","onBufferFlushed","INIT_PTS_FOUND","onInitPtsFound","doTickIdle","_levels$trackId","_this$media","seeking","cache","clearWaitingFragment","startFragPrefetch","trackDetails","BUFFER_EOS","mainBufferInfo","atGap","atBufferSyncLimit","mainFrag","mainBufferLength","maxConfigBuffer","mediaPlaylist","altAudio","flushAudioIfNeeded","_track$details","defaultAudioCodec","_handleTransmuxComplete","AUDIO_TRACK_SWITCHED","_ref4","_id3$samples","completeAudioSwitch","mapFragment","_bufferInitSegment","FRAG_PARSING_INIT_SEGMENT","emittedID3","emittedText","FRAG_PARSING_USERDATA","currentLevel","variantAudioCodecs","BUFFER_CODECS","_track$details2","bufferedAttributes","switchAttributes","AudioTrackController","_BasePlaylistControll","groupIds","tracksInGroup","currentTrack","selectDefaultTrack","MANIFEST_PARSED","onManifestParsed","trackInActiveGroup","currentGroups","groupIndex","allIndex","findTrackId","audioTracksUpdated","selectedTrackId","setAudioTrack","_this$groupIds","setAudioOption","audioOption","switchIndex","renditions","variantMap","currentVideoCodec","matchingVideo","findClosestLevelWithAudioGroup","withoutCodecAndChannelsMatch","newId","lastTrack","trackLoaded","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","asyncPollTrackChange","pollTrackChange","useTextTrackPolling","subtitlePollingInterval","_subtitleDisplay","onTextTracksChanged","renderTextTracksNatively","findTrackForTextTrack","setSubtitleTrack","subtitlePreference","subtitleTracksUpdated","selectDefault","setSubtitleOption","subtitleOption","allSubtitleTracks","toggleTrackModes","nextTrack","subtitleDisplay","_track$groupId","BufferOperationQueue","sourceBufferReference","buffers","queues","append","operation","pending","queue","executeNext","insertAbort","appendBlocker","execute","promise","onStart","onComplete","sb","updating","shiftAndExecuteNext","VIDEO_CODEC_PROFILE_REPLACE","BufferController","_objectUrl","operationQueue","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","lastMpegAudioChunk","appendSource","appendErrors","pendingTracks","sourceBuffer","_onEndStreaming","pauseBuffering","_onStartStreaming","resumeBuffering","_onMediaSourceOpen","_onMediaEmptied","updateMediaElementDuration","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","mediaSrc","_initSourceBuffer","hasSourceTypes","getSourceBufferTypes","MEDIA_ATTACHING","onMediaAttaching","onBufferAppending","onBufferCodecs","onBufferEos","onFragParsed","FRAG_CHANGED","onFragChanged","codecEvents","_ms$constructor","ms","constructor","objectUrl","removeAttribute","MMS","disableRemotePlayback","removeSourceChildren","createElement","src","appendChild","addSource","endOfStream","MEDIA_DETACHED","resetBuffer","_this$mediaSource","removeBufferListeners","sourceBuffers","removeSourceBuffer","sourceBufferCount","trackNames","trackName","changeType","_trackCodec","_data$trackName","currentCodecFull","currentCodec","trackCodec","nextCodec","mimeType","appendChangeType","eventData","chunkStats","bufferAppendingStart","fragBuffering","partBuffering","checkTimestampOffset","timestampOffset","appendExecutor","QUOTA_EXCEEDED_ERR","appendErrorCount","appendErrorMaxRetry","flushOperation","removeExecutor","_this7","buffersAppendedTo","blockBuffers","trimBuffers","_this8","ending","backBufferLength","liveBackBufferLength","maxBackBufferLength","targetBackBufferPosition","flushBackBuffer","frontBufferFlushThreshold","frontBufferLength","maxFrontBufferLength","targetFrontBufferPosition","flushFrontBuffer","_this9","BACK_BUFFER_REACHED","LIVE_BACK_BUFFER_REACHED","_this10","numBufferedRanges","levelDuration","mediaDuration","msDuration","liveDurationInfinity","updateSeekableRange","setLiveSeekableRange","pendingTracksCount","createSourceBuffers","BUFFER_INCOMPATIBLE_CODECS_ERROR","_this11","_track$levelCodec","addSourceBuffer","sbName","addBufferListener","_onSBUpdateStart","_onSBUpdateEnd","_onSBUpdateError","removedRanges","_this$mediaSource2","_this$mediaSource3","_isFiniteNumber6","removeStart","removeEnd","remove","appendBuffer","onUnblocked","_this12","blockingOperations","_this$media$querySele","querySelector","node","sourceChildren","querySelectorAll","removeChild","specialCea608CharsCodes","getCharForByte","NR_ROWS","NR_COLS","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","CaptionsLogger","verboseLevel","severity","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","setStyles","styles","attribs","style","equals","other","copy","newPenState","StyledUnicodeChar","uchar","penState","_proto3","setChar","setPenState","newChar","isEmpty","Row","chars","currPenState","cueStartTime","_proto4","empty","setCursor","absPos","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","rows","currRow","nrRollUpRows","lastOutputScreen","_proto5","equal","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","tmp","ccTO","nrCols","ccMIDROW","secondByte","colorIndex","dispatch","newCue","dispatchCue","cueSplitAtTime","Cea608Parser","field","out1","out2","currentChannel","cmdHistory","_proto7","channel","addData","byteList","cmdFound","charsFound","hasCmdRepeated","setLastCmd","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","currChNr","interpretPAC","pacIndex","channelNr","oneCode","charCodes","charCode1","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","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","xmlDoc","tt","defaultRateInfo","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","elementsWithId","dict","element","_node$childNodes","nodeName","textContent","ns","hasAttributeNS","timeAttributeValue","parseHoursMinutesSecondsFrames","parseTimeUnits","TimelineController","Cues","unparsedVttFrags","captionsTracks","nonNativeCaptionsTracks","cea608Parser1","cea608Parser2","lastCc","captionsProperties","cueHandler","textTrack1","captionsTextTrack1Label","languageCode","captionsTextTrack1LanguageCode","textTrack2","captionsTextTrack2Label","captionsTextTrack2LanguageCode","textTrack3","captionsTextTrack3Label","captionsTextTrack3LanguageCode","textTrack4","captionsTextTrack4Label","captionsTextTrack4LanguageCode","onFragParsingUserdata","onFragDecrypted","SUBTITLE_TRACKS_CLEARED","onSubtitleTracksCleared","initCea608Parsers","enableCEA708Captions","channel1","channel2","channel3","channel4","x1","y1","y2","merged","cueRange","overlap","CUES_PARSED","getExistingTrack","canReuseVttTextTrack","createNativeTrack","createNonNativeTrack","_captionsProperties$t","existingTrack","createTextTrack","trackProperties","closedCaptions","NON_NATIVE_TEXT_TRACKS_FOUND","_cleanTracks","hasIMSC1","enableWebVTT","enableIMSC1","inUseTracks","inUseTrack","textTrackKind","captionsOrSubtitlesFromCharacteristics","unusedTextTracks","tracksList","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","stopCapping","FPS_DROP_LEVEL_CAPPING","onFpsDropLevelCapping","droppedLevel","isLevelAllowed","HTMLVideoElement","detectPlayerSize","capLevelToPlayerSize","startCapping","mediaHeight","mediaWidth","maxLevel","getMaxLevel","nextLevelSwitch","capLevelIndex","validLevels","getMaxLevelByMediaSize","getDimensions","boundsRect","getBoundingClientRect","bottom","top","restrictedLevel","curLevel","maxLevelIndex","squareSize","contentScaleFactor","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","attempt","keySystems","getMediaKeysPromise","mediaKeys","EMEKeyError","KEY_SYSTEM_NO_ACCESS","supportedConfigurations","errMessage","protocol","mediaKeySystemConfigs","initDataTypes","persistentState","distinctiveIdentifier","sessionTypes","sessionType","audioCapabilities","robustness","audioRobustness","encryptionScheme","audioEncryptionScheme","videoCapabilities","videoRobustness","videoEncryptionScheme","createMediaKeySystemConfigurations","getSupportedMediaKeySystemConfigurations","keySystemAccess","mediaKeySystemAccess","certificateRequest","fetchServerCertificate","createMediaKeys","certificate","setMediaKeysServerCertificate","createMediaKeySessionContext","mediaKeysSession","createSession","mediaKeySessionContext","keyStatus","renewKeySession","keySessionContext","getKeyIdString","generateRequestWithPreferredKeySession","removeSession","updateKeySession","_mediaKeySessionConte","keySession","sessionId","selectKeySystemFormat","getKeyFormatPromise","keySystemsInConfig","getKeySystemSelectionPromise","keySystemFormat","keySystemToKeySystemFormat","loadKey","keyInfo","keyDetails","keySessionContextPromise","getKeySystemForKeyPromise","throwIfDestroyed","attemptSetMediaKeys","handleError","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_CONFIGURED_LICENSE","initDataType","logMessage","keySystemDomain","json","psshResults","parseMultiPssh","psshInfo","keyIdHex","keyContext","oldKeyIdHex","_keySystemToKeySystem","setMediaKeysPromise","setMediaKeys","_this$config$drmSyste","_this$config$drmSyste2","generateRequestFilter","generateRequest","mappedInitData","licenseStatus","onmessage","_onmessage","messageType","renewLicense","onkeystatuseschange","_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","requestLicense","KEY_SYSTEM_SESSION_UPDATE_FAILED","unpackPlayReadyKeyMessage","xhr","licenseChallenge","xmlString","setRequestHeader","keyMessageXml","_header$querySelector","_header$querySelector2","challengeElement","challengeText","setupLicenseXHR","keysListItem","open","licenseXhrSetupResult","XMLHttpRequest","onreadystatechange","KEY_SYSTEM_LICENSE_REQUEST_FAILED","statusText","attemptsLeft","licenseXhr","DONE","_ref5","send","emeEnabled","_this13","mediaKeysList","keySessionCount","_ref6","formats","_this14","close","CmObjectType","CmStreamingFormat","CmcdHeaderField","_this15","CmcdHeaderMap","_CmcdHeaderMap","OBJECT","REQUEST","SESSION","STATUS","SfItem","SfToken","DICT","throwError","cause","Map","Set","BARE_ITEM","BOOLEAN","BYTES","DECIMAL","INTEGER","STRING_REGEX","TOKEN","KEY","serializeError","serializeByteSequence","isView","base64encode","binary","btoa","serializeInteger","isInvalidInt","roundToEven","precision","decimalShift","EPSILON","flooredValue","serializeDecimal","roundedValue","STRING","serializeToken","token","symbol","serializeBareItem","isInteger","serializeString","serializeBoolean","serializeDate","serializeKey","serializeParams","entries","serializeItem","serializeDict","_options","whitespace","optionalWhiteSpace","item","output","isTokenField","toRounded","toHundred","CmcdFormatters","br","bl","dl","mtp","nor","base","origin","toPath","pathname","fromPath","urlToRelativePath","rtp","tb","encodeCmcd","cmcd","encodeSfDict","formatters","formatter","processCmcd","appendCmcdHeaders","headerMap","customHeaderMap","shards","entry","_headerMap$find","find","toCmcdHeaders","CMCD_PARAM","REGEX","appendCmcdQuery","toCmcdQuery","separator","CMCDController","sid","cid","useHeaders","includeKeys","initialized","starved","audioBuffer","onWaiting","onPlaying","applyPlaylistData","ot","CmcdObjectType","MANIFEST","su","applyFragmentData","getObjectType","VIDEO","MUXED","getTopBandwidth","getBufferLength","createPlaylistLoader","createFragmentLoader","randomUUID","dt","random","contentId","_data$tracks$audio","_data$tracks$video","createData","sf","CmcdStreamingFormat","HLS","pr","bandwidthEstimate","isVideo","INIT","bs","TIMED_TEXT","_step","_iterator","_createForOfIteratorHelperLoose","done","Ctor","CmcdPlaylistLoader","callbacks","CmcdFragmentLoader","ContentSteeringController","pathwayPriority","timeToLoad","reloadTimer","started","penalizedPathways","ttl","scheduleRefresh","loadSteeringManifest","levelToRemove","errorPathway","getPathwayForGroupId","pathways","updatePathwayPriority","filterParsedLevels","pathwayLevels","getLevelsForPathway","selectedIndex","selectedLevel","levelAfterChange","defaultPathway","clonePathways","pathwayClones","audioGroupCloneMap","subtitleGroupCloneMap","pathwayClone","cloneId","baseId","uriReplacement","clonedVariants","baseLevel","clonedAudioGroupId","clonedSubtitleGroupId","performUriReplacement","clonedLevel","cloneRenditionGroups","throughput","steeringManifestLoadPolicy","steeringData","VERSION","TTL","reloadUri","loadedSteeringData","steeringManifest","STEERING_MANIFEST_LOADED","getResponseHeader","retryAfter","ttlMs","_this3$hls","groupCloneMap","clonedTracks","clonedTrack","stableId","perOptionKey","perVariantUri","host","HOST","PARAMS","perOptionUris","AGE_HEADER_LINE_REGEX","XhrLoader","xhrSetup","requestTimeout","retryTimeout","abortInternal","onprogress","_this$callbacks","loadInternal","openAndSendXhr","_config$loadPolicy","readystatechange","loadprogress","loadtimeout","useResponse","responseText","responseURL","_this$context","lengthComputable","getAllResponseHeaders","FetchLoader","fetchSetup","request","controller","getRequest","AbortController","initParams","signal","credentials","Headers","getRequestParameters","isArrayBuffer","LENGTH","fetch","ok","FetchError","contentRange","byteRangeLength","byteRangeHeader","getByteRangeLength","contentLength","getContentLength","loadProgressively","responseData","chunkCache","reader","getReader","pump","read","Request","chromeOrFirefox","WHITESPACE_CHAR","hlsDefaultConfig","highBufferWatchdogPeriod","nudgeOffset","nudgeMaxRetry","startLevel","abrController","bufferController","capLevelController","errorController","fpsController","abrEwmaDefaultEstimateMax","minAutoBitrate","testBandwidth","manifestLoadingTimeOut","manifestLoadingMaxRetry","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","fragLoadingTimeOut","fragLoadingMaxRetry","fragLoadingRetryDelay","fragLoadingMaxRetryTimeout","captionScreen","indenting","_track$cues","cueA","cueB","subtitleStreamController","subtitleTrackController","audioStreamController","audioTrackController","emeController","cmcdController","contentSteeringController","deepCpy","enableStreamingMode","currentLoader","ReadableStream","fetchSupported","LevelController","_levels","_firstLevel","_maxAutoLevel","_startLevel","currentLevelIndex","manualLevelIndex","steering","onParsedComplete","resetLevels","redundantSet","generatePathwaySet","resolutionFound","videoCodecFound","audioCodecFound","levelParsed","_audioCodec","_videoCodec","avcdata","convertAVC1ToAVCOTI","FRAMERATE","HDCP","PATHWAY","RESOLUTION","VIDEO_RANGE","pathwayCount","filterAndSortMediaOptions","filteredLevels","assignTrackIdsByGroup","unsortedLevels","valueA","valueB","firstLevelInPlaylist","_this$hls$userConfig","firstLevelBitrate","startingBwEstimate","audioOnly","edata","forceStartLoad","MANIFEST_INCOMPATIBLE_CODECS_ERROR","_data$deliveryDirecti2","_data$deliveryDirecti","_this$currentLevel","checkMaxAutoUpdated","newLevel","lastLevelIndex","lastLevel","lastPathwayId","levelSwitchingData","audioGroupIds","textGroupIds","configStartLevel","KeyLoader","keyUriToKeyInfo","_loader$context","createKeyLoadError","loadingFrag","_keyInfo","_keyInfo2","_keyInfo$mediaKeySess","keyLoadPromise","loadKeyHTTP","loadKeyEME","getSourceBuffer","SourceBuffer","WebKitSourceBuffer","isMSESupported","GapController","nudgeRetry","stallReported","stalled","moved","poll","activeFrag","seeked","beginSeek","hasEnoughBuffer","noBufferGap","startJump","maxStartGapJump","partialOrGap","_trySkipBufferHole","tnow","stalledDuration","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","_tryNudgeBuffer","bufferStarved","waiting","gapLength","startGap","startFrag","startProvisioned","moreToLoad","provisioned","targetTime","StreamController","audioCodecSwap","gapController","_forceStartLoad","fragPlaying","onvplaying","onvseeked","fragLastKbps","couldBacktrack","audioCodecSwitch","onFragLoadEmergencyAborted","onAudioTrackSwitched","checkBuffer","checkFragmentChanged","getMainFwdBufferInfo","lastDetails","manualLevel","_this$backtrackFragme","backtrackFrag","_loadBitrateTestFrag","followingBufferedFrag","immediateLevelSwitch","abortCurrentFrag","fetchdelay","fragPlayingCurrent","bufferedFrag","nextBufferedFrag","maxStart","startPts","onMediaPlaying","onMediaSeeked","_sourceBuffer$prototy","aac","heaac","_curLevel$details","newLevelId","_getAudioCodec","fromAltAudio","mediaTrack","alternate","swapAudioCodec","isFirstFragment","isFirstInDiscontinuity","backtrack","ua","audioMetadata","fragCurrentLevel","LEVEL_SWITCHED","currentFrag","epocMs","Hls","coreComponents","networkControllers","_emitter","_autoLevelCapping","_maxHdcpLevel","latencyController","levelController","_media","triggeringException","defaultConfig","defaultsCopy","deprecatedSettings","policyName","policyNotSet","report","deprecatedSetting","mergeConfig","DefaultConfig","ConfigAbrController","ConfigBufferController","ConfigCapLevelController","ConfigErrorController","ConfigFpsController","playListLoader","id3TrackController","ConfigContentSteeringController","createController","AudioStreamControllerClass","SubtitleStreamControllerClass","codecsForVideoContainer","codecForAudioContainer","ControllerClass","components","controllerInstance","eventObject","DESTROYING","detachMedia","component","attachMedia","loadSource","loadedSource","loadingSource","_this$audioTrackContr","_this$subtitleTrackCo","shouldStartCapping","newCapLevelToPlayerSize","isHdcpLevel","currentProgramDateTime","audioTrackId","subtitleTrackId"],"mappings":"oyHAEA,IACMA,EAEAC,EACAC,EACAC,EAEAC,EANAJ,EACF,iIACEC,EAAsB,2BACtBC,EAAkB,oBAClBC,EAAsB,wCAEtBC,EAAa,CAOfC,iBAAkB,SAAUC,EAASC,EAAaC,GAKhD,GAJAA,EAAOA,GAAQ,GAEfF,EAAUA,EAAQG,SAClBF,EAAcA,EAAYE,QACR,CAIhB,IAAKD,EAAKE,gBACR,OAAOJ,EAET,IAAIK,EAAwBP,EAAWQ,SAASN,GAChD,IAAKK,EACH,MAAM,IAAIE,MAAM,mCAKlB,OAHAF,EAAsBG,KAAOV,EAAWW,cACtCJ,EAAsBG,MAEjBV,EAAWY,kBAAkBL,EACrC,CACD,IAAIM,EAAgBb,EAAWQ,SAASL,GACxC,IAAKU,EACH,MAAM,IAAIJ,MAAM,uCAElB,GAAII,EAAcC,OAGhB,OAAKV,EAAKE,iBAGVO,EAAcH,KAAOV,EAAWW,cAAcE,EAAcH,MACrDV,EAAWY,kBAAkBC,IAH3BV,EAKX,IAAIY,EAAYf,EAAWQ,SAASN,GACpC,IAAKa,EACH,MAAM,IAAIN,MAAM,mCAElB,IAAKM,EAAUC,QAAUD,EAAUL,MAA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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,IAGF6mE,EAAI2B,WAAa,CACfvgE,MAAOqgE,EACPtgE,MAAOugE,GAGT,IAAMrB,EAAO,IAAIlnE,WAAW,CAC1B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,IACA,IACA,GACA,EACA,EACA,EACA,IAGIgoE,EAAO,IAAIhoE,WAAW,CAC1B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAGF6mE,EAAI4B,KAAO5B,EAAI6B,KAAO7B,EAAI8B,KAAOX,EAEjCnB,EAAI+B,KAAO,IAAI5oE,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAEF6mE,EAAIgC,KAAO,IAAI7oE,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAEF6mE,EAAIiC,KAAO,IAAI9oE,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAGF6mE,EAAIkC,KAAO,IAAI/oE,WAAW,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IAGF,IAAMgpE,EAAa,IAAIhpE,WAAW,CAAC,IAAK,IAAK,IAAK,MAC5CipE,EAAY,IAAIjpE,WAAW,CAAC,GAAI,IAAK,GAAI,KACzCkpE,EAAe,IAAIlpE,WAAW,CAAC,EAAG,EAAG,EAAG,IAE9C6mE,EAAIsC,KAAOtC,EAAIuC,IACbvC,EAAIC,MAAMM,KACV4B,EACAE,EACAF,EACAC,GAEFpC,EAAIwC,KAAOxC,EAAIuC,IAAIvC,EAAIC,MAAMG,KAAMJ,EAAIuC,IAAIvC,EAAIC,MAAMI,KAAMA,KAC5DL,EAEMuC,IAAP,SAAW/qE,GACI,IAAb,IAAI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,EAAO,GAAG5jB,UAAW4jB,EAAO,GAAGv0B,WACtD89B,OAAOmpC,GACPnpC,OAAOumC,EAAIc,KAAK5wC,MAEtB8vC,EAEMc,KAAP,SAAY5wC,GAIV,IAHA,IAAI92B,EAAI82B,EAAOz6B,OACTmtE,EAAsB,GAErBxpE,KACLwpE,EAAMxpE,GAAK4mE,EAAIpyD,KAAKsiB,EAAO92B,IAG7B,OAAO4mE,EAAIuC,IAAIh3D,MAAM,KAAOy0D,CAAAA,EAAIC,MAAMa,MAAIrnC,OAAKmpC,KAChD5C,EAEMe,KAAP,SAAYz0D,EAAW3Q,GACrBA,GAAY2Q,EACZ,IAAMm2D,EAAoBxsE,KAAKuO,MAAM7I,GAAYuP,GAAa,IACxDw3D,EAAoBzsE,KAAKuO,MAAM7I,GAAYuP,GAAa,IACxDsF,EAAQ,IAAIrX,WAAW,CAC3B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACCmT,GAAa,GAAM,IACnBA,GAAa,GAAM,IACnBA,GAAa,EAAK,IACP,IAAZA,EACAm2D,GAAqB,GACpBA,GAAqB,GAAM,IAC3BA,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,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,IACA,IACA,IACA,MAEF,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wD,EAAIvyD,KAAMhH,IAAQ,EAAK,KACvBu5D,EAAIvyD,KAAW,IAANhH,GAETu5D,EAAMA,EAAIxgC,OAAOpiC,MAAMqB,UAAUQ,MAAMkC,KAAK4D,IAG9C,IAAMgkE,EAAOhD,EAAIuC,IACfvC,EAAIC,MAAMC,KACV,IAAI/mE,WACF,CACE,EACA2gE,EAAI,GACJA,EAAI,GACJA,EAAI,GACJ,IACA,IAAOjsD,EAAMisD,IAAIrkE,QAEhBgkC,OAAOqgC,GACPrgC,OAAO,CACN5rB,EAAMosD,IAAIxkE,SAEXgkC,OAAOwgC,KAGRngE,EAAQ+T,EAAM/T,MACdC,EAAS8T,EAAM9T,OACfkpE,EAAWp1D,EAAMmrD,WAAW,GAC5BkK,EAAWr1D,EAAMmrD,WAAW,GAElC,OAAOgH,EAAIuC,IACTvC,EAAIC,MAAM/jD,KACV,IAAI/iB,WAAW,CACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACCW,GAAS,EAAK,IACP,IAARA,EACCC,GAAU,EAAK,IACP,IAATA,EACA,EACA,GACA,EACA,EACA,EACA,GACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,GACA,IACA,IACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,GACA,KAEFipE,EACAhD,EAAIuC,IACFvC,EAAIC,MAAME,KACV,IAAIhnE,WAAW,CACb,EACA,GACA,IACA,IACA,EACA,GACA,IACA,IACA,EACA,GACA,IACA,OAGJ6mE,EAAIuC,IACFvC,EAAIC,MAAMe,KACV,IAAI7nE,WAAW,CACb8pE,GAAY,GACXA,GAAY,GAAM,IAClBA,GAAY,EAAK,IACP,IAAXA,EACAC,GAAY,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C,KAAMlC,EAAIhB,IAAInxD,IAExB,QAAvBA,EAAMwlD,aACD2M,EAAIuC,IAAIvC,EAAIC,MAAMjyD,KAAMgyD,EAAIkC,KAAMlC,EAAIf,IAAIpxD,IAE5CmyD,EAAIuC,IAAIvC,EAAIC,MAAMjyD,KAAMgyD,EAAIkC,KAAMlC,EAAIzkD,KAAK1N,IAE3CmyD,EAAIuC,IAAIvC,EAAIC,MAAMjyD,KAAMgyD,EAAIkC,KAAMlC,EAAI9jD,KAAKrO,KAErDmyD,EAEM9yD,KAAP,SAAYW,GACV,IAAM9V,EAAK8V,EAAM9V,GACX4D,EAAWkS,EAAMlS,SAAWkS,EAAMvB,UAClCxS,EAAQ+T,EAAM/T,MACdC,EAAS8T,EAAM9T,OACf0oE,EAAoBxsE,KAAKuO,MAAM7I,GAAYuP,GAAa,IACxDw3D,EAAoBzsE,KAAKuO,MAAM7I,GAAYuP,GAAa,IAC9D,OAAO80D,EAAIuC,IACTvC,EAAIC,MAAM/yD,KACV,IAAI/T,WAAW,CACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACCpB,GAAM,GAAM,IACZA,GAAM,GAAM,IACZA,GAAM,EAAK,IACP,IAALA,EACA,EACA,EACA,EACA,EACA0qE,GAAqB,GACpBA,GAAqB,GAAM,IAC3BA,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,EACC5oE,GAAS,EAAK,IACP,I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IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,KAIN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,KACN,IAAM,IACN,IAAM,IACN,IAAM,KACN,IAAM,IACN,IAAM,GACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IAGN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,KACN,IAAM,IACN,IAAM,GACN,IAAM,KACN,IAAM,KACN,IAAM,IACN,IAAM,KACN,IAAM,KACN,IAAM,KACN,IAAM,KACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IAGN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,GACN,IAAM,GACN,IAAM,GACN,IAAM,IACN,IAAM,KACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,KACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,IACN,IAAM,KACN,IAAM,KACN,IAAM,KACN,IAAM,MAMFC,GAAiB,SAAC73E,GAAY,OAClC3G,OAAOC,aAAas+E,GAAwB53E,IAASA,EAAK,EAEtD83E,GAAU,GACVC,GAAU,IAEVC,GAAa,CACjB,GAAM,EACN,GAAM,EACN,GAAM,EACN,GAAM,EACN,GAAM,EACN,GAAM,GACN,GAAM,GACN,GAAM,IAEFC,GAAc,CAClB,GAAM,EACN,GAAM,EACN,GAAM,EACN,GAAM,EACN,GAAM,GACN,GAAM,GACN,GAAM,IAEFC,GAAa,CACjB,GAAM,EACN,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AAz6B,IAAA,gBAAAC,IAGA,WACE,OAAO9B,KAAK0xH,kBAAkBt1F,aAChC,GAEA,CAAAv6B,IAAA,QAAAC,IAGA,WACE,OAAO9B,KAAK0xH,kBAAkBl0F,KAChC,GAEA,CAAA37B,IAAA,iBAAAC,IAGA,WACE,OAAO9B,KAAKioG,iBAAiBqiB,cAC/B,IAAC,CAAA,CAAAzoH,IAAA,UAAAC,IAv3BD,WACE,MAAO,QACT,GAAC,CAAAD,IAAA,SAAAC,IAuBD,WACE,OAAOlE,CACT,GAAC,CAAAiE,IAAA,aAAAC,IAED,WACE,OAAOjE,CACT,GAAC,CAAAgE,IAAA,eAAAC,IAED,WACE,OAAOhE,CACT,GAEA,CAAA+D,IAAA,gBAAAC,IAGA,WACE,OAAKsvH,EAAIU,cAIFV,EAAIU,cAHFxM,EAIX,EAEApgH,IAGA,SAAyB4sH,GACvBV,EAAIU,cAAgBA,CACtB,KAACV,CAAA,CAzFqB,UAAHA,GACJU,mBAAa","x_google_ignoreList":[0,75,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,144]}