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AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,GAAG;AACd,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,iBAAiB;AAC5B,WAAW,UAAU;AACrB,WAAW,GAAG;AACd,WAAW,SAAS;AACpB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,iBAAiB;AAC5B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,0DAA0D,OAAO;AACjE;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,aAAa,SAAS;AACtB;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,0CAA0C,SAAS;AACnD;AACA;;AAEA;AACA,IAAI;AACJ;AACA;;AAEA,gBAAgB,YAAY;AAC5B;;AAEA;AACA,4DAA4D;AAC5D,gEAAgE;AAChE,oEAAoE;AACpE,wEAAwE;AACxE;AACA,2DAA2D,SAAS;AACpE;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,UAAU;AACrB,WAAW,GAAG;AACd,aAAa,cAAc;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,UAAU;AACrB,WAAW,GAAG;AACd,aAAa,cAAc;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,UAAU;AACrB,WAAW,GAAG;AACd,WAAW,SAAS;AACpB,aAAa,cAAc;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,4DAA4D,YAAY;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,aAAa,cAAc;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAI,IAA6B;AACjC;AACA;;;;;;;;;;;AC/UA;;AAEA;AACA;AACA,sFAAsF,iBAAiB;AACvG;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB;AACA;AACA;AACA;AACA,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA,MAAM,IAAyD;AAC/D;AACA,OAAO,EAKgC;AACvC,CAAC;;;;;;;UC7KD;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;UAEA;UACA;;;;;WCzBA;WACA;WACA;WACA;WACA;WACA,iCAAiC,WAAW;WAC5C;WACA;;;;;WCPA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;;;;;WCAA;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;UENA;UACA;UACA;UACA","sources":["webpack://Hls/webpack/universalModuleDefinition","webpack://Hls/./src/config.ts","webpack://Hls/./src/controller/abr-controller.ts","webpack://Hls/./src/controller/audio-stream-controller.ts","webpack://Hls/./src/controller/audio-track-controller.ts","webpack://Hls/./src/controller/base-playlist-controller.ts","webpack://Hls/./src/controller/base-stream-controller.ts","webpack://Hls/./src/controller/buffer-controller.ts","webpack://Hls/./src/controller/buffer-operation-queue.ts","webpack://Hls/./src/controller/cap-level-controller.ts","webpack://Hls/./src/controller/cmcd-controller.ts","webpack://Hls/./src/controller/eme-controller.ts","webpack://Hls/./src/controller/fps-controller.ts","webpack://Hls/./src/controller/fragment-finders.ts","webpack://Hls/./src/controller/fragment-tracker.ts","webpack://Hls/./src/controller/gap-controller.ts","webpack://Hls/./src/controller/id3-track-controller.ts","webpack://Hls/./src/controller/latency-controller.ts","webpack://Hls/./src/controller/level-controller.ts","webpack://Hls/./src/controller/level-helper.ts","webpack://Hls/./src/controller/stream-controller.ts","webpack://Hls/./src/controller/subtitle-stream-controller.ts","webpack://Hls/./src/controller/subtitle-track-controller.ts","webpack://Hls/./src/controller/timeline-controller.ts","webpack://Hls/./src/crypt/aes-crypto.ts","webpack://Hls/./src/crypt/aes-decryptor.ts","webpack://Hls/./src/crypt/decrypter.ts","webpack://Hls/./src/crypt/fast-aes-key.ts","webpack://Hls/./src/demux/aacdemuxer.ts","webpack://Hls/./src/demux/adts.ts","webpack://Hls/./src/demux/base-audio-demuxer.ts","webpack://Hls/./src/demux/chunk-cache.ts","webpack://Hls/./src/demux/dummy-demuxed-track.ts","webpack://Hls/./src/demux/exp-golomb.ts","webpack://Hls/./src/demux/id3.ts","webpack://Hls/./src/demux/mp3demuxer.ts","webpack://Hls/./src/demux/mp4demuxer.ts","webpack://Hls/./src/demux/mpegaudio.ts","webpack://Hls/./src/demux/sample-aes.ts","webpack://Hls/./src/demux/transmuxer-interface.ts","webpack://Hls/./src/demux/transmuxer-worker.ts","webpack://Hls/./src/demux/transmuxer.ts","webpack://Hls/./src/demux/tsdemuxer.ts","webpack://Hls/./src/demux/webworkify-webpack.js","webpack://Hls/./src/errors.ts","webpack://Hls/./src/events.ts","webpack://Hls/./src/hls.ts","webpack://Hls/./src/is-supported.ts","webpack://Hls/./src/loader/date-range.ts","webpack://Hls/./src/loader/fragment-loader.ts","webpack://Hls/./src/loader/fragment.ts","webpack://Hls/./src/loader/key-loader.ts","webpack://Hls/./src/loader/level-details.ts","webpack://Hls/./src/loader/level-key.ts","webpack://Hls/./src/loader/load-stats.ts","webpack://Hls/./src/loader/m3u8-parser.ts","webpack://Hls/./src/loader/playlist-loader.ts","webpack://Hls/./src/polyfills/number.ts","webpack://Hls/./src/remux/aac-helper.ts","webpack://Hls/./src/remux/mp4-generator.ts","webpack://Hls/./src/remux/mp4-remuxer.ts","webpack://Hls/./src/remux/passthrough-remuxer.ts","webpack://Hls/./src/task-loop.ts","webpack://Hls/./src/types/cmcd.ts","webpack://Hls/./src/types/demuxer.ts","webpack://Hls/./src/types/level.ts","webpack://Hls/./src/types/loader.ts","webpack://Hls/./src/types/transmuxer.ts","webpack://Hls/./src/utils/attr-list.ts","webpack://Hls/./src/utils/binary-search.ts","webpack://Hls/./src/utils/buffer-helper.ts","webpack://Hls/./src/utils/cea-608-parser.ts","webpack://Hls/./src/utils/codecs.ts","webpack://Hls/./src/utils/cues.ts","webpack://Hls/./src/utils/discontinuities.ts","webpack://Hls/./src/utils/ewma-bandwidth-estimator.ts","webpack://Hls/./src/utils/ewma.ts","webpack://Hls/./src/utils/fetch-loader.ts","webpack://Hls/./src/utils/imsc1-ttml-parser.ts","webpack://Hls/./src/utils/logger.ts","webpack://Hls/./src/utils/mediakeys-helper.ts","webpack://Hls/./src/utils/mediasource-helper.ts","webpack://Hls/./src/utils/mp4-tools.ts","webpack://Hls/./src/utils/output-filter.ts","webpack://Hls/./src/utils/texttrack-utils.ts","webpack://Hls/./src/utils/time-ranges.ts","webpack://Hls/./src/utils/timescale-conversion.ts","webpack://Hls/./src/utils/typed-array.ts","webpack://Hls/./src/utils/vttcue.ts","webpack://Hls/./src/utils/vttparser.ts","webpack://Hls/./src/utils/webvtt-parser.ts","webpack://Hls/./src/utils/xhr-loader.ts","webpack://Hls/./node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js","webpack://Hls/./node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js","webpack://Hls/webpack/bootstrap","webpack://Hls/webpack/runtime/compat get default export","webpack://Hls/webpack/runtime/define property getters","webpack://Hls/webpack/runtime/hasOwnProperty shorthand","webpack://Hls/webpack/runtime/make namespace object","webpack://Hls/webpack/before-startup","webpack://Hls/webpack/startup","webpack://Hls/webpack/after-startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Hls\"] = factory();\n\telse\n\t\troot[\"Hls\"] = factory();\n})(this, () => {\nreturn ","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 from './controller/eme-controller';\nimport CMCDController from './controller/cmcd-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 { CuesInterface } from './utils/cues';\nimport type { MediaKeyFunc } from './utils/mediakeys-helper';\nimport type {\n FragmentLoaderContext,\n Loader,\n LoaderContext,\n PlaylistLoaderContext,\n} from './types/loader';\n\nexport type ABRControllerConfig = {\n abrEwmaFastLive: number;\n abrEwmaSlowLive: number;\n abrEwmaFastVoD: number;\n abrEwmaSlowVoD: number;\n abrEwmaDefaultEstimate: number;\n abrBandWidthFactor: number;\n abrBandWidthUpFactor: number;\n abrMaxWithRealBitrate: boolean;\n maxStarvationDelay: number;\n maxLoadingDelay: number;\n};\n\nexport type BufferControllerConfig = {\n appendErrorMaxRetry: number;\n backBufferLength: number;\n liveDurationInfinity: boolean;\n liveBackBufferLength: number | null;\n};\n\nexport type CapLevelControllerConfig = {\n capLevelToPlayerSize: boolean;\n};\n\nexport type CMCDControllerConfig = {\n sessionId?: string;\n contentId?: string;\n useHeaders?: boolean;\n};\n\nexport type DRMSystemOptions = {\n audioRobustness?: string;\n videoRobustness?: string;\n};\n\nexport type EMEControllerConfig = {\n licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void;\n licenseResponseCallback?: (xhr: XMLHttpRequest, url: string) => ArrayBuffer;\n emeEnabled: boolean;\n widevineLicenseUrl?: string;\n drmSystemOptions: DRMSystemOptions;\n requestMediaKeySystemAccessFunc: MediaKeyFunc | null;\n};\n\nexport interface FragmentLoaderConstructor {\n new (confg: HlsConfig): Loader<FragmentLoaderContext>;\n}\n\nexport type FragmentLoaderConfig = {\n fLoader?: FragmentLoaderConstructor;\n\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\nexport type PlaylistLoaderConfig = {\n pLoader?: PlaylistLoaderConstructor;\n\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 StreamControllerConfig = {\n autoStartLoad: boolean;\n startPosition: number;\n defaultAudioCodec?: string;\n initialLiveManifestSize: number;\n maxBufferLength: number;\n maxBufferSize: number;\n maxBufferHole: number;\n highBufferWatchdogPeriod: number;\n nudgeOffset: number;\n nudgeMaxRetry: number;\n maxFragLookUpTolerance: number;\n maxMaxBufferLength: number;\n startFragPrefetch: boolean;\n testBandwidth: boolean;\n};\n\nexport type LatencyControllerConfig = {\n liveSyncDurationCount: number;\n liveMaxLatencyDurationCount: number;\n liveSyncDuration?: number;\n liveMaxLatencyDuration?: number;\n maxLiveSyncPlaybackRate: number;\n};\n\nexport type MetadataControllerConfig = {\n enableDateRangeMetadataCues: boolean;\n enableEmsgMetadataCues: boolean;\n enableID3MetadataCues: boolean;\n};\n\nexport type TimelineControllerConfig = {\n cueHandler: CuesInterface;\n enableWebVTT: boolean;\n enableIMSC1: boolean;\n enableCEA708Captions: boolean;\n captionsTextTrack1Label: string;\n captionsTextTrack1LanguageCode: string;\n captionsTextTrack2Label: string;\n captionsTextTrack2LanguageCode: string;\n captionsTextTrack3Label: string;\n captionsTextTrack3LanguageCode: string;\n captionsTextTrack4Label: string;\n captionsTextTrack4LanguageCode: string;\n renderTextTracksNatively: boolean;\n};\n\nexport type TSDemuxerConfig = {\n forceKeyFrameOnDiscontinuity: boolean;\n};\n\nexport type HlsConfig = {\n debug: boolean | ILogger;\n enableWorker: boolean;\n enableSoftwareAES: boolean;\n minAutoBitrate: number;\n ignoreDevicePixelRatio: boolean;\n loader: { new (confg: HlsConfig): Loader<LoaderContext> };\n fetchSetup?: (context: LoaderContext, initParams: any) => Request;\n xhrSetup?: (xhr: XMLHttpRequest, url: string) => 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\n abrController: typeof AbrController;\n bufferController: typeof BufferController;\n capLevelController: typeof CapLevelController;\n fpsController: typeof FPSController;\n progressive: boolean;\n lowLatencyMode: boolean;\n} & ABRControllerConfig &\n BufferControllerConfig &\n CapLevelControllerConfig &\n EMEControllerConfig &\n FPSControllerConfig &\n FragmentLoaderConfig &\n LevelControllerConfig &\n MP4RemuxerConfig &\n PlaylistLoaderConfig &\n StreamControllerConfig &\n LatencyControllerConfig &\n MetadataControllerConfig &\n TimelineControllerConfig &\n TSDemuxerConfig;\n\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\nexport const hlsDefaultConfig: HlsConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: undefined, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n ignoreDevicePixelRatio: false, // used by cap-level-controller\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n backBufferLength: Infinity, // used by buffer-controller\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.1, // used by stream-controller\n highBufferWatchdogPeriod: 2, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry: 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount: 3, // used by latency-controller\n liveMaxLatencyDurationCount: Infinity, // used by latency-controller\n liveSyncDuration: undefined, // used by latency-controller\n liveMaxLatencyDuration: undefined, // used by latency-controller\n maxLiveSyncPlaybackRate: 1, // used by latency-controller\n liveDurationInfinity: false, // used by buffer-controller\n liveBackBufferLength: null, // used by buffer-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by demuxer\n enableSoftwareAES: true, // used by decrypter\n manifestLoadingTimeOut: 10000, // used by playlist-loader\n manifestLoadingMaxRetry: 1, // used by playlist-loader\n manifestLoadingRetryDelay: 1000, // used by playlist-loader\n manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n startLevel: undefined, // used by level-controller\n levelLoadingTimeOut: 10000, // used by playlist-loader\n levelLoadingMaxRetry: 4, // used by playlist-loader\n levelLoadingRetryDelay: 1000, // used by playlist-loader\n levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n fragLoadingTimeOut: 20000, // used by fragment-loader\n fragLoadingMaxRetry: 6, // used by fragment-loader\n fragLoadingRetryDelay: 1000, // used by fragment-loader\n fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader\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 fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift: 1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrBandWidthFactor: 0.95, // used by abr-controller\n abrBandWidthUpFactor: 0.7, // used by abr-controller\n abrMaxWithRealBitrate: false, // used by abr-controller\n maxStarvationDelay: 4, // used by abr-controller\n maxLoadingDelay: 4, // used by abr-controller\n minAutoBitrate: 0, // used by hls\n emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n drmSystemOptions: {}, // used by eme-controller\n requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess, // used by eme-controller\n testBandwidth: true,\n progressive: false,\n lowLatencyMode: true,\n cmcd: undefined,\n enableDateRangeMetadataCues: true,\n enableEmsgMetadataCues: true,\n enableID3MetadataCues: true,\n\n // 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};\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\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 return Object.assign({}, defaultConfig, userConfig);\n}\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 EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\nimport { Events } from '../events';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { PlaylistLevelType } from '../types/loader';\nimport { logger } from '../utils/logger';\nimport type { Bufferable } from '../utils/buffer-helper';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { LoaderStats } from '../types/loader';\nimport type Hls from '../hls';\nimport type {\n FragLoadingData,\n FragLoadedData,\n FragBufferedData,\n ErrorData,\n LevelLoadedData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\n\nclass AbrController implements ComponentAPI {\n protected hls: Hls;\n private lastLoadedFragLevel: number = 0;\n private _nextAutoLevel: number = -1;\n private timer?: number;\n private onCheck: Function = this._abandonRulesCheck.bind(this);\n private fragCurrent: Fragment | null = null;\n private partCurrent: Part | null = null;\n private bitrateTestDelay: number = 0;\n\n public readonly bwEstimator: EwmaBandWidthEstimator;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n const config = hls.config;\n this.bwEstimator = new EwmaBandWidthEstimator(\n config.abrEwmaSlowVoD,\n config.abrEwmaFastVoD,\n config.abrEwmaDefaultEstimate\n );\n\n this.registerListeners();\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n protected unregisterListeners() {\n const { hls } = this;\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, 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.onCheck = null;\n this.fragCurrent = this.partCurrent = null;\n }\n\n protected onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {\n const frag = data.frag;\n if (frag.type === PlaylistLevelType.MAIN) {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.partCurrent = data.part ?? null;\n this.timer = self.setInterval(this.onCheck, 100);\n }\n }\n }\n\n protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const config = this.hls.config;\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, config, media } = hls;\n if (!frag || !media) {\n return;\n }\n\n const stats: LoaderStats = part ? part.stats : frag.stats;\n const duration = part ? part.duration : frag.duration;\n // If frag loading is aborted, complete, or from lowest level, stop timer and return\n if (\n stats.aborted ||\n (stats.loaded && stats.loaded === stats.total) ||\n frag.level === 0\n ) {\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n\n // This check only runs if we're in ABR mode and actually playing\n if (\n !autoLevelEnabled ||\n media.paused ||\n !media.playbackRate ||\n !media.readyState\n ) {\n return;\n }\n\n const bufferInfo = hls.mainForwardBufferInfo;\n if (bufferInfo === null) {\n return;\n }\n\n const requestDelay = performance.now() - stats.loading.start;\n const playbackRate = Math.abs(media.playbackRate);\n // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded\n if (requestDelay <= (500 * duration) / playbackRate) {\n return;\n }\n\n const loadedFirstByte = stats.loaded && stats.loading.first;\n const bwEstimate: number = this.bwEstimator.getEstimate();\n const { levels, minAutoLevel } = hls;\n const level = levels[frag.level];\n const expectedLen =\n stats.total ||\n Math.max(stats.loaded, Math.round((duration * level.maxBitrate) / 8));\n const loadRate = loadedFirstByte ? (stats.loaded * 1000) / requestDelay : 0;\n\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;\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\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 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 // 0.8 : consider only 80% of current bw to be conservative\n // 8 = bits per byte (bps/Bps)\n const levelNextBitrate = levels[nextLoadLevel].maxBitrate;\n fragLevelNextLoadedDelay = loadRate\n ? (duration * levelNextBitrate) / (8 * 0.8 * loadRate)\n : (duration * levelNextBitrate) / bwEstimate;\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 logger.warn(`Fragment ${frag.sn}${\n part ? ' part ' + part.index : ''\n } of level ${\n frag.level\n } is loading too slowly and will cause an underbuffer; aborting and switching to level ${nextLoadLevel}\n Current BW estimate: ${\n Number.isFinite(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown'\n } Kb/s\n Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s\n Estimated load time for the next fragment: ${fragLevelNextLoadedDelay.toFixed(\n 3\n )} s\n Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s`);\n hls.nextLoadLevel = nextLoadLevel;\n if (loadedFirstByte) {\n // If there has been loading progress, sample bandwidth\n this.bwEstimator.sample(requestDelay, stats.loaded);\n }\n this.clearTimer();\n if (frag.loader || frag.keyLoader) {\n this.fragCurrent = this.partCurrent = null;\n frag.abortRequests();\n }\n hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, { frag, part, stats });\n }\n\n protected onFragLoaded(\n event: Events.FRAG_LOADED,\n { frag, part }: FragLoadedData\n ) {\n if (\n frag.type === PlaylistLevelType.MAIN &&\n Number.isFinite(frag.sn as number)\n ) {\n const stats = part ? part.stats : frag.stats;\n const duration = part ? part.duration : frag.duration;\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const 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 }\n }\n }\n\n protected onFragBuffered(\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData\n ) {\n const { frag, part } = data;\n const stats = part ? part.stats : frag.stats;\n\n if (stats.aborted) {\n return;\n }\n // Only count non-alt-audio frags which were actually buffered in our BW calculations\n if (frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment') {\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 = stats.parsing.end - stats.loading.start;\n this.bwEstimator.sample(processingMs, stats.loaded);\n stats.bwEstimate = this.bwEstimator.getEstimate();\n if (frag.bitrateTest) {\n this.bitrateTestDelay = processingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n\n protected onError(event: Events.ERROR, data: ErrorData) {\n // stop timer in case of frag loading error\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n }\n\n clearTimer() {\n self.clearInterval(this.timer);\n this.timer = undefined;\n }\n\n // return next auto level\n get nextAutoLevel() {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this.bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && !bwEstimator.canEstimate()) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n let nextABRAutoLevel = this.getNextABRAutoLevel();\n // use forced auto level when ABR selected level has errored\n if (forcedAutoLevel !== -1 && this.hls.levels[nextABRAutoLevel].loadError) {\n return forcedAutoLevel;\n }\n // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);\n }\n\n return nextABRAutoLevel;\n }\n\n private getNextABRAutoLevel() {\n const { fragCurrent, partCurrent, hls } = this;\n const { maxAutoLevel, config, minAutoLevel, media } = hls;\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n const pos = media ? media.currentTime : 0;\n\n // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n const playbackRate =\n media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;\n const avgbw = this.bwEstimator\n ? this.bwEstimator.getEstimate()\n : config.abrEwmaDefaultEstimate;\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferInfo = hls.mainForwardBufferInfo;\n const bufferStarvationDelay =\n (bufferInfo ? bufferInfo.len : 0) / playbackRate;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n let bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay,\n config.abrBandWidthFactor,\n config.abrBandWidthUpFactor\n );\n if (bestLevel >= 0) {\n return bestLevel;\n }\n logger.trace(\n `${\n bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'\n }, finding optimal quality level`\n );\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxStarvationDelay)\n : config.maxStarvationDelay;\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\n if (!bufferStarvationDelay) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n const bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxLoadingDelay)\n : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.trace(\n `bitrate test took ${Math.round(\n 1000 * bitrateTestDelay\n )}ms, set first fragment max fetchDuration to ${Math.round(\n 1000 * maxStarvationDelay\n )} ms`\n );\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay + maxStarvationDelay,\n bwFactor,\n bwUpFactor\n );\n return Math.max(bestLevel, 0);\n }\n\n private findBestLevel(\n currentBw: number,\n minAutoLevel: number,\n maxAutoLevel: number,\n maxFetchDuration: number,\n bwFactor: number,\n bwUpFactor: number\n ): number {\n const {\n fragCurrent,\n partCurrent,\n lastLoadedFragLevel: currentLevel,\n } = this;\n const { levels } = this.hls;\n const level = levels[currentLevel];\n const live = !!level?.details?.live;\n const currentCodecSet = level?.codecSet;\n\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n const levelInfo = levels[i];\n\n if (\n !levelInfo ||\n (currentCodecSet && levelInfo.codecSet !== currentCodecSet)\n ) {\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 (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n const bitrate: number = levels[i].maxBitrate;\n const fetchDuration: number = (bitrate * avgDuration) / adjustedbw;\n\n logger.trace(\n `level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ${i}/${Math.round(\n adjustedbw\n )}/${bitrate}/${avgDuration}/${maxFetchDuration}/${fetchDuration}`\n );\n // if adjusted bw is greater than level bitrate AND\n if (\n adjustedbw > bitrate &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1\n (fetchDuration === 0 ||\n !Number.isFinite(fetchDuration) ||\n (live && !this.bitrateTestDelay) ||\n fetchDuration < maxFetchDuration)\n ) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n set nextAutoLevel(nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\n","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 { PlaylistLevelType } from '../types/loader';\nimport { Fragment, ElementaryStreamTypes, Part } from '../loader/fragment';\nimport ChunkCache from '../demux/chunk-cache';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport { fragmentWithinToleranceTest } from './fragment-finders';\nimport { alignMediaPlaylistByPDT } from '../utils/discontinuities';\nimport { ErrorDetails } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type { TransmuxerResult } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { TrackSet } from '../types/track';\nimport type {\n BufferCreatedData,\n AudioTracksUpdatedData,\n AudioTrackSwitchingData,\n LevelLoadedData,\n TrackLoadedData,\n BufferAppendingData,\n BufferFlushedData,\n InitPTSFoundData,\n FragLoadedData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n FragBufferedData,\n ErrorData,\n} from '../types/events';\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 audioSwitch: boolean = false;\n private trackId: number = -1;\n private waitingData: WaitingForPTSData | null = null;\n private mainDetails: LevelDetails | null = null;\n private bufferFlushed: boolean = false;\n private cachedTrackLoadedData: TrackLoadedData | null = null;\n\n constructor(hls: Hls, fragmentTracker: FragmentTracker) {\n super(hls, fragmentTracker, '[audio-stream-controller]');\n this._registerListeners();\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.mainDetails = null;\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value\n onInitPtsFound(\n event: Events.INIT_PTS_FOUND,\n { frag, id, initPTS }: 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] = initPTS;\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 this.fragLoadError = 0;\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(\n `Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(\n 3\n )}`\n );\n startPosition = lastCurrentTime;\n this.state = State.IDLE;\n } else {\n this.loadedmetadata = false;\n this.state = State.WAITING_TRACK;\n }\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n\n this.tick();\n }\n\n doTick() {\n switch (this.state) {\n case State.IDLE:\n this.doTickIdle();\n break;\n case State.WAITING_TRACK: {\n const { levels, trackId } = this;\n const details = levels?.[trackId]?.details;\n if (details) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.WAITING_INIT_PTS;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY: {\n const now = performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || this.media?.seeking) {\n this.log('RetryDate reached, switch back to IDLE state');\n this.resetStartWhenNotLoaded(this.trackId);\n this.state = State.IDLE;\n }\n break;\n }\n case State.WAITING_INIT_PTS: {\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingData = this.waitingData;\n if (waitingData) {\n const { frag, part, cache, complete } = waitingData;\n if (this.initPTS[frag.cc] !== undefined) {\n this.waitingData = null;\n this.waitingVideoCC = -1;\n this.state = State.FRAG_LOADING;\n const payload = cache.flush();\n const data: FragLoadedData = {\n frag,\n part,\n payload,\n networkDetails: null,\n };\n this._handleFragmentLoadProgress(data);\n if (complete) {\n super._handleFragmentLoadComplete(data);\n }\n } else if (this.videoTrackCC !== this.waitingVideoCC) {\n // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found\n this.log(\n `Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${this.videoTrackCC}`\n );\n this.clearWaitingFragment();\n } else {\n // Drop waiting fragment if an earlier fragment is needed\n const pos = this.getLoadPosition();\n const bufferInfo = BufferHelper.bufferInfo(\n this.mediaBuffer,\n pos,\n this.config.maxBufferHole\n );\n const waitingFragmentAtPosition = fragmentWithinToleranceTest(\n bufferInfo.end,\n this.config.maxFragLookUpTolerance,\n frag\n );\n if (waitingFragmentAtPosition < 0) {\n this.log(\n `Waiting fragment cc (${frag.cc}) @ ${frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`\n );\n this.clearWaitingFragment();\n }\n }\n } else {\n this.state = State.IDLE;\n }\n }\n }\n\n this.onTickEnd();\n }\n\n clearWaitingFragment() {\n const waitingData = this.waitingData;\n if (waitingData) {\n this.fragmentTracker.removeFragment(waitingData.frag);\n this.waitingData = null;\n this.waitingVideoCC = -1;\n this.state = State.IDLE;\n }\n }\n\n protected resetLoadingState() {\n this.clearWaitingFragment();\n super.resetLoadingState();\n }\n\n protected onTickEnd() {\n const { media } = this;\n if (!media || !media.readyState) {\n // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n return;\n }\n\n this.lastCurrentTime = media.currentTime;\n }\n\n private doTickIdle() {\n const { hls, levels, media, trackId } = this;\n const config = hls.config;\n\n if (!levels || !levels[trackId]) {\n return;\n }\n\n // if video not attached AND\n // start fragment already requested OR start frag prefetch not enabled\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!media && (this.startFragRequested || !config.startFragPrefetch)) {\n return;\n }\n\n const levelInfo = levels[trackId];\n\n const trackDetails = levelInfo.details;\n if (\n !trackDetails ||\n (trackDetails.live && this.levelLastLoaded !== trackId) ||\n this.waitForCdnTuneIn(trackDetails)\n ) {\n this.state = State.WAITING_TRACK;\n return;\n }\n\n const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (this.bufferFlushed && bufferable) {\n this.bufferFlushed = false;\n this.afterBufferFlushed(\n bufferable,\n ElementaryStreamTypes.AUDIO,\n PlaylistLevelType.AUDIO\n );\n }\n\n const bufferInfo = this.getFwdBufferInfo(\n bufferable,\n PlaylistLevelType.AUDIO\n );\n if (bufferInfo === null) {\n return;\n }\n const 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 const audioSwitch = this.audioSwitch;\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if (bufferLen >= maxBufLen && !audioSwitch) {\n return;\n }\n\n if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {\n hls.trigger(Events.BUFFER_EOS, { type: 'audio' });\n this.state = State.ENDED;\n return;\n }\n\n const fragments = trackDetails.fragments;\n const start = fragments[0].start;\n let targetBufferTime = bufferInfo.end;\n\n if (audioSwitch && media) {\n const pos = this.getLoadPosition();\n targetBufferTime = pos;\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 // buffer audio up to one target duration ahead of main buffer\n if (\n mainBufferInfo &&\n targetBufferTime > mainBufferInfo.end + trackDetails.targetduration\n ) {\n return;\n }\n // wait for main buffer after buffing some audio\n if ((!mainBufferInfo || !mainBufferInfo.len) && bufferInfo.len) {\n return;\n }\n\n const frag = this.getNextFragment(targetBufferTime, trackDetails);\n if (!frag) {\n this.bufferFlushed = true;\n return;\n }\n\n this.loadFragment(frag, trackDetails, targetBufferTime);\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 onMediaDetaching() {\n this.videoBuffer = null;\n super.onMediaDetaching();\n }\n\n onAudioTracksUpdated(\n event: Events.AUDIO_TRACKS_UPDATED,\n { audioTracks }: AudioTracksUpdatedData\n ) {\n this.resetTransmuxer();\n this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));\n }\n\n onAudioTrackSwitching(\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData\n ) {\n // if any URL found on new audio track, it is an alternate audio track\n const altAudio = !!data.url;\n this.trackId = data.id;\n const { fragCurrent } = this;\n\n if (fragCurrent) {\n fragCurrent.abortRequests();\n }\n this.fragCurrent = null;\n this.clearWaitingFragment();\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.audioSwitch = true;\n // main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state = State.IDLE;\n } else {\n this.state = State.STOPPED;\n }\n this.tick();\n }\n\n onManifestLoading() {\n this.mainDetails = null;\n this.fragmentTracker.removeAllFragments();\n this.startPosition = this.lastCurrentTime = 0;\n this.bufferFlushed = false;\n }\n\n onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n this.mainDetails = data.details;\n if (this.cachedTrackLoadedData !== null) {\n this.hls.trigger(Events.AUDIO_TRACK_LOADED, this.cachedTrackLoadedData);\n this.cachedTrackLoadedData = null;\n }\n }\n\n onAudioTrackLoaded(event: Events.AUDIO_TRACK_LOADED, data: TrackLoadedData) {\n if (this.mainDetails == null) {\n this.cachedTrackLoadedData = data;\n return;\n }\n const { levels } = this;\n const { details: newDetails, id: trackId } = data;\n if (!levels) {\n this.warn(`Audio tracks were reset while loading level ${trackId}`);\n return;\n }\n this.log(\n `Track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${newDetails.totalduration}`\n );\n\n const track = levels[trackId];\n let sliding = 0;\n if (newDetails.live || track.details?.live) {\n const mainDetails = this.mainDetails;\n if (!newDetails.fragments[0]) {\n newDetails.deltaUpdateFailed = true;\n }\n if (newDetails.deltaUpdateFailed || !mainDetails) {\n return;\n }\n if (\n !track.details &&\n newDetails.hasProgramDateTime &&\n mainDetails.hasProgramDateTime\n ) {\n // Make sure our audio rendition is aligned with the \"main\" rendition, using\n // pdt as our reference times.\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n sliding = newDetails.fragments[0].start;\n } else {\n sliding = this.alignPlaylists(newDetails, track.details);\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = trackId;\n\n // compute start position if we are aligned with the main playlist\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(track.details, sliding);\n }\n // only switch back to IDLE state if we were waiting for track to start downloading a new fragment\n if (\n this.state === State.WAITING_TRACK &&\n !this.waitForCdnTuneIn(newDetails)\n ) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n _handleFragmentLoadProgress(data: FragLoadedData) {\n const { frag, part, payload } = data;\n const { config, trackId, levels } = this;\n if (!levels) {\n this.warn(\n `Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`\n );\n return;\n }\n\n const track = levels[trackId] as Level;\n console.assert(track, 'Audio track is defined on fragment load progress');\n const details = track.details as LevelDetails;\n console.assert(\n details,\n 'Audio track details are defined on fragment load progress'\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 if ((this.videoBuffer || this.media)?.buffered.length) {\n this.loadedmetadata = true;\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: ${this.audioSwitch}`\n );\n return;\n }\n if (frag.sn !== 'initSegment') {\n this.fragPrevious = frag;\n if (this.audioSwitch) {\n this.audioSwitch = false;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, { id: this.trackId });\n }\n }\n this.fragBufferedComplete(frag, part);\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\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 // TODO: Skip fragments that do not belong to this.fragCurrent audio-group id\n this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);\n break;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received\n if (this.state !== State.ERROR && this.state !== State.STOPPED) {\n // if fatal error, stop processing, otherwise move to IDLE to retry loading\n this.state = data.fatal ? State.ERROR : State.IDLE;\n this.warn(\n `${data.details} while loading frag, switching to ${this.state} state`\n );\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (\n data.parent === 'audio' &&\n (this.state === State.PARSING || this.state === State.PARSED)\n ) {\n let flushBuffer = true;\n const bufferedInfo = this.getFwdBufferInfo(\n this.mediaBuffer,\n PlaylistLevelType.AUDIO\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 if (bufferedInfo && bufferedInfo.len > 0.5) {\n flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);\n }\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 also media.currentTime is not buffered, flush audio buffer'\n );\n this.fragCurrent = null;\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n }\n this.resetLoadingState();\n }\n break;\n default:\n break;\n }\n }\n\n private onBufferFlushed(\n event: Events.BUFFER_FLUSHED,\n { type }: BufferFlushedData\n ) {\n if (type === ElementaryStreamTypes.AUDIO) {\n this.bufferFlushed = true;\n }\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.warn(\n `The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`\n );\n this.resetStartWhenNotLoaded(chunkMeta.level);\n return;\n }\n const {\n frag,\n part,\n level: { details },\n } = context;\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 return;\n }\n\n this.state = State.PARSING;\n if (this.audioSwitch && audio) {\n this.completeAudioSwitch();\n }\n\n if (initSegment?.tracks) {\n this._bufferInitSegment(initSegment.tracks, frag, chunkMeta);\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag,\n id,\n tracks: initSegment.tracks,\n });\n // Only flush audio from old audio tracks when PTS is known on new audio track\n }\n if (audio) {\n const { startPTS, endPTS, startDTS, endDTS } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n }\n frag.setElementaryStreamInfo(\n ElementaryStreamTypes.AUDIO,\n startPTS,\n endPTS,\n startDTS,\n endDTS\n );\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n\n if (id3?.samples?.length) {\n const emittedID3: FragParsingMetadataData = Object.assign(\n {\n id,\n frag,\n details,\n },\n id3\n );\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (text) {\n const emittedText: FragParsingUserdataData = Object.assign(\n {\n id,\n frag,\n details,\n },\n text\n );\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n\n private _bufferInitSegment(\n tracks: TrackSet,\n frag: Fragment,\n chunkMeta: ChunkMetadata\n ) {\n if (this.state !== State.PARSING) {\n return;\n }\n // delete any video track found on audio transmuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n const track = tracks.audio;\n if (!track) {\n return;\n }\n\n track.levelCodec = track.codec;\n track.id = 'audio';\n this.log(\n `Init audio buffer, container:${track.container}, codecs[parsed]=[${track.codec}]`\n );\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n const initSegment = track.initSegment;\n if (initSegment?.byteLength) {\n const segment: BufferAppendingData = {\n type: 'audio',\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n data: initSegment,\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n }\n // trigger handler right now\n this.tick();\n }\n\n protected loadFragment(\n frag: Fragment,\n trackDetails: LevelDetails,\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.audioSwitch ||\n fragState === FragmentState.NOT_LOADED ||\n fragState === FragmentState.PARTIAL\n ) {\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, trackDetails);\n } else if (trackDetails.live && !Number.isFinite(this.initPTS[frag.cc])) {\n this.log(\n `Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`\n );\n this.state = State.WAITING_INIT_PTS;\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, trackDetails, targetBufferTime);\n }\n }\n }\n\n private completeAudioSwitch() {\n const { hls, media, trackId } = this;\n if (media) {\n this.log('Switching audio track : flushing all audio');\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n }\n this.audioSwitch = false;\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n}\nexport default AudioStreamController;\n","import { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport {\n ManifestParsedData,\n AudioTracksUpdatedData,\n ErrorData,\n LevelLoadingData,\n AudioTrackLoadedData,\n LevelSwitchingData,\n} from '../types/events';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType } from '../types/loader';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nclass AudioTrackController extends BasePlaylistController {\n private tracks: MediaPlaylist[] = [];\n private groupId: string | null = null;\n private tracksInGroup: MediaPlaylist[] = [];\n private trackId: number = -1;\n private trackName: string = '';\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 super.destroy();\n }\n\n protected onManifestLoading(): void {\n this.tracks = [];\n this.groupId = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.trackName = '';\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, details } = data;\n const currentTrack = this.tracksInGroup[id];\n\n if (!currentTrack) {\n this.warn(`Invalid audio track id ${id}`);\n return;\n }\n\n const curDetails = currentTrack.details;\n currentTrack.details = data.details;\n this.log(`audioTrack ${id} loaded [${details.startSN}-${details.endSN}]`);\n\n if (id === this.trackId) {\n this.retryCount = 0;\n this.playlistLoaded(id, data, curDetails);\n }\n }\n\n protected onLevelLoading(\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ): void {\n this.switchLevel(data.level);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.switchLevel(data.level);\n }\n\n private switchLevel(levelIndex: number) {\n const levelInfo = this.hls.levels[levelIndex];\n\n if (!levelInfo?.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.groupId !== audioGroupId) {\n this.groupId = audioGroupId;\n\n const audioTracks = this.tracks.filter(\n (track): boolean => !audioGroupId || track.groupId === audioGroupId\n );\n\n // Disable selectDefaultTrack if there are no default tracks\n if (\n this.selectDefaultTrack &&\n !audioTracks.some((track) => track.default)\n ) {\n this.selectDefaultTrack = false;\n }\n\n this.tracksInGroup = audioTracks;\n const audioTracksUpdated: AudioTracksUpdatedData = { audioTracks };\n this.log(\n `Updating audio tracks, ${audioTracks.length} track(s) found in \"${audioGroupId}\" group-id`\n );\n this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);\n\n this.selectInitialTrack();\n }\n }\n\n protected onError(event: Events.ERROR, data: ErrorData): void {\n super.onError(event, data);\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.AUDIO_TRACK &&\n data.context.id === this.trackId &&\n data.context.groupId === this.groupId\n ) {\n this.retryLoadingOrFail(data);\n }\n }\n\n get audioTracks(): MediaPlaylist[] {\n return this.tracksInGroup;\n }\n\n get audioTrack(): number {\n return this.trackId;\n }\n\n set audioTrack(newId: number) {\n // If audio track is selected from API then don't choose from the manifest default track\n this.selectDefaultTrack = false;\n this.setAudioTrack(newId);\n }\n\n private setAudioTrack(newId: number): void {\n const tracks = this.tracksInGroup;\n\n // check if level idx is valid\n if (newId < 0 || newId >= tracks.length) {\n this.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n const lastTrack = tracks[this.trackId];\n this.log(`Now switching to audio-track index ${newId}`);\n const track = tracks[newId];\n const { id, groupId = '', name, type, url } = track;\n this.trackId = newId;\n this.trackName = name;\n this.selectDefaultTrack = false;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, {\n id,\n groupId,\n name,\n type,\n url,\n });\n // Do not reload track unless live\n if (track.details && !track.details.live) {\n return;\n }\n const hlsUrlParameters = this.switchParams(track.url, lastTrack?.details);\n this.loadPlaylist(hlsUrlParameters);\n }\n\n private selectInitialTrack(): void {\n const audioTracks = this.tracksInGroup;\n console.assert(\n audioTracks.length,\n 'Initial audio track should be selected when tracks are known'\n );\n const currentAudioTrackName = this.trackName;\n const trackId =\n this.findTrackId(currentAudioTrackName) || this.findTrackId();\n\n if (trackId !== -1) {\n this.setAudioTrack(trackId);\n } else {\n this.warn(`No track found for running audio group-ID: ${this.groupId}`);\n\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true,\n });\n }\n }\n\n private findTrackId(name?: string): number {\n const audioTracks = this.tracksInGroup;\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (!this.selectDefaultTrack || track.default) {\n if (!name || name === track.name) {\n return track.id;\n }\n }\n }\n return -1;\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n super.loadPlaylist();\n const audioTrack = this.tracksInGroup[this.trackId];\n if (this.shouldLoadTrack(audioTrack)) {\n const id = audioTrack.id;\n const groupId = audioTrack.groupId as string;\n let url = audioTrack.url;\n if (hlsUrlParameters) {\n try {\n url = hlsUrlParameters.addDirectives(url);\n } catch (error) {\n this.warn(\n `Could not construct new URL with HLS Delivery Directives: ${error}`\n );\n }\n }\n // track not retrieved yet, or live playlist we need to (re)load it\n this.log(`loading audio-track playlist for id: ${id}`);\n this.clearTimer();\n this.hls.trigger(Events.AUDIO_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n}\n\nexport default AudioTrackController;\n","import type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport { getSkipValue, HlsSkip, HlsUrlParameters } from '../types/level';\nimport { computeReloadInterval, mergeDetails } from './level-helper';\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';\nimport { ErrorData } from '../types/events';\nimport { Events } from '../events';\nimport { ErrorTypes } from '../errors';\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 retryCount: number = 0;\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 onError(event: Events.ERROR, data: ErrorData): void {\n if (data.fatal && data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n }\n\n protected clearTimer(): void {\n clearTimeout(this.timer);\n this.timer = -1;\n }\n\n public startLoad(): void {\n this.canLoad = true;\n this.retryCount = 0;\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\n ): HlsUrlParameters | undefined {\n const renditionReports = previous?.renditionReports;\n if (renditionReports) {\n for (let i = 0; i < renditionReports.length; i++) {\n const attr = renditionReports[i];\n const uri = '' + attr.URI;\n if (uri === playlistUri.slice(-uri.length)) {\n const msn = parseInt(attr['LAST-MSN']);\n let part = parseInt(attr['LAST-PART']);\n if (previous && this.hls.config.lowLatencyMode) {\n const currentGoal = Math.min(\n previous.age - previous.partTarget,\n previous.targetduration\n );\n if (part !== undefined && currentGoal > previous.partTarget) {\n part += 1;\n }\n }\n if (Number.isFinite(msn)) {\n return new HlsUrlParameters(\n msn,\n Number.isFinite(part) ? part : undefined,\n HlsSkip.No\n );\n }\n }\n }\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n if (this.requestScheduled === -1) {\n this.requestScheduled = self.performance.now();\n }\n }\n\n protected shouldLoadTrack(track: MediaPlaylist): boolean {\n return (\n this.canLoad &&\n track &&\n !!track.url &&\n (!track.details || track.details.live)\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 : '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;\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 {\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) {\n this.requestScheduled = -1;\n } else if (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 {\n this.requestScheduled =\n (this.requestScheduled === -1 ? now : this.requestScheduled) +\n 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 + stats.loading.end - stats.loading.start)) /\n // 1000\n // }\n // reload interval ${reloadInterval / 1000}\n // target duration ${details.targetduration}\n // distance to edge ${distanceToLiveEdgeMs / 1000}`\n // );\n\n this.timer = self.setTimeout(\n () => this.loadPlaylist(deliveryDirectives),\n estimatedTimeUntilUpdate\n );\n } else {\n this.clearTimer();\n }\n }\n\n private getDeliveryDirectives(\n details: LevelDetails,\n previousDeliveryDirectives: HlsUrlParameters | null,\n msn?: number,\n part?: number\n ): HlsUrlParameters {\n let skip = getSkipValue(details, msn);\n if (previousDeliveryDirectives?.skip && details.deltaUpdateFailed) {\n msn = previousDeliveryDirectives.msn;\n part = previousDeliveryDirectives.part;\n skip = HlsSkip.No;\n }\n return new HlsUrlParameters(msn, part, skip);\n }\n\n protected retryLoadingOrFail(errorEvent: ErrorData): boolean {\n const { config } = this.hls;\n const retry = this.retryCount < config.levelLoadingMaxRetry;\n if (retry) {\n this.requestScheduled = -1;\n this.retryCount++;\n if (\n errorEvent.details.indexOf('LoadTimeOut') > -1 &&\n errorEvent.context?.deliveryDirectives\n ) {\n // The LL-HLS request already timed out so retry immediately\n this.warn(\n `retry playlist loading #${this.retryCount} after \"${errorEvent.details}\"`\n );\n this.loadPlaylist();\n } else {\n // exponential backoff capped to max retry timeout\n const delay = Math.min(\n Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay,\n config.levelLoadingMaxRetryTimeout\n );\n // Schedule level/track reload\n this.timer = self.setTimeout(() => this.loadPlaylist(), delay);\n this.warn(\n `retry playlist loading #${this.retryCount} in ${delay} ms after \"${errorEvent.details}\"`\n );\n }\n } else {\n this.warn(`cannot recover from error \"${errorEvent.details}\"`);\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n }\n return retry;\n }\n}\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 } 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 getFragmentWithSN,\n getPartWith,\n updateFragPTSDTS,\n} from './level-helper';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { Fragment, Part } from '../loader/fragment';\nimport FragmentLoader, {\n FragmentLoadProgressCallback,\n LoadError,\n} from '../loader/fragment-loader';\nimport KeyLoader from '../loader/key-loader';\nimport { LevelDetails } from '../loader/level-details';\nimport Decrypter from '../crypt/decrypter';\nimport TimeRanges from '../utils/time-ranges';\nimport { PlaylistLevelType } from '../types/loader';\nimport type {\n BufferAppendingData,\n ErrorData,\n FragLoadedData,\n PartsLoadedData,\n KeyLoadedData,\n MediaAttachingData,\n BufferFlushingData,\n LevelSwitchingData,\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';\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 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 loadedmetadata: boolean = false;\n protected fragLoadError: number = 0;\n protected retryDate: number = 0;\n protected levels: Array<Level> | null = null;\n protected fragmentLoader: FragmentLoader;\n protected keyLoader: KeyLoader;\n protected levelLastLoaded: number | null = null;\n protected startFragRequested: boolean = false;\n protected decrypter: Decrypter;\n protected initPTS: Array<number> = [];\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(hls: Hls, fragmentTracker: FragmentTracker, logPrefix: string) {\n super();\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 = new KeyLoader(hls.config);\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.decrypter = new Decrypter(hls.config);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, 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();\n const frag = this.fragCurrent;\n if (frag) {\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(bufferInfo, levelDetails: LevelDetails): boolean {\n const { fragCurrent, fragmentTracker } = this;\n // we just got done loading the final fragment and there is no other buffered range after ...\n // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between\n // so we should not switch to ENDED in that case, to be able to buffer them\n if (\n !levelDetails.live &&\n fragCurrent &&\n this.media &&\n // NOTE: Because of the way parts are currently parsed/represented in the playlist, we can end up\n // in situations where the current fragment is actually greater than levelDetails.endSN. While\n // this feels like the \"wrong place\" to account for that, this is a narrower/safer change than\n // updating e.g. M3U8Parser::parseLevelPlaylist().\n fragCurrent.sn >= levelDetails.endSN &&\n !bufferInfo.nextStart\n ) {\n const partList = levelDetails.partList;\n // Since the last part isn't guaranteed to correspond to fragCurrent for ll-hls, 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 const fragState = fragmentTracker.getState(fragCurrent);\n return (\n fragState === FragmentState.PARTIAL || fragState === FragmentState.OK\n );\n }\n return false;\n }\n\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachingData\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 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 (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 }\n this.resetLoadingState();\n }\n }\n }\n\n if (media) {\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 onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.fragLoadError = 0;\n }\n\n protected onHandlerDestroying() {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n protected onHandlerDestroyed() {\n this.state = State.STOPPED;\n this.hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\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 levelDetails: LevelDetails,\n targetBufferTime: number\n ) {\n this._loadFragForPlayback(frag, levelDetails, targetBufferTime);\n }\n\n private _loadFragForPlayback(\n frag: Fragment,\n levelDetails: LevelDetails,\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, levelDetails, 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 this.fragLoadError = 0;\n const state = this.state;\n if (this.fragContextChanged(frag)) {\n if (\n state === State.FRAG_LOADING ||\n (!this.fragCurrent && state === State.PARSING)\n ) {\n this.fragmentTracker.removeFragment(frag);\n this.state = State.IDLE;\n }\n return;\n }\n\n if ('payload' in data) {\n this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);\n this.hls.trigger(Events.FRAG_LOADED, data);\n }\n\n // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback\n this._handleFragmentLoadComplete(data);\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(reason);\n this.resetFragmentLoading(frag);\n });\n }\n\n protected 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 // Reset load errors on flush\n this.fragLoadError = 0;\n this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);\n }\n\n protected _loadInitSegment(frag: Fragment, details: LevelDetails) {\n this._doFragLoad(frag, details)\n .then((data) => {\n if (!data || this.fragContextChanged(frag) || !this.levels) {\n throw new Error('init load aborted');\n }\n\n return data;\n })\n .then((data: FragLoadedData) => {\n const { hls } = this;\n const { payload } = data;\n const decryptData = frag.decryptdata;\n\n // check to see if the payload needs to be decrypted\n if (\n payload &&\n payload.byteLength > 0 &&\n decryptData &&\n decryptData.key &&\n decryptData.iv &&\n decryptData.method === 'AES-128'\n ) {\n const startTime = self.performance.now();\n // decrypt the subtitles\n return this.decrypter\n .decrypt(\n new Uint8Array(payload),\n decryptData.key.buffer,\n decryptData.iv.buffer\n )\n .then((decryptedData) => {\n const endTime = self.performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime,\n },\n });\n data.payload = decryptedData;\n\n return data;\n });\n }\n\n return data;\n })\n .then((data: FragLoadedData) => {\n const { fragCurrent, hls, levels } = this;\n if (!levels) {\n throw new Error('init load aborted, missing levels');\n }\n\n const details = levels[frag.level].details as LevelDetails;\n console.assert(\n details,\n 'Level details are defined when init segment is loaded'\n );\n\n const stats = frag.stats;\n this.state = State.IDLE;\n this.fragLoadError = 0;\n frag.data = new Uint8Array(data.payload);\n stats.parsing.start = stats.buffering.start = self.performance.now();\n stats.parsing.end = stats.buffering.end = self.performance.now();\n\n // Silence FRAG_BUFFERED event if fragCurrent is null\n if (data.frag === fragCurrent) {\n hls.trigger(Events.FRAG_BUFFERED, {\n stats,\n frag: fragCurrent,\n part: null,\n id: frag.type,\n });\n }\n this.tick();\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(reason);\n this.resetFragmentLoading(frag);\n });\n }\n\n protected fragContextChanged(frag: Fragment | null) {\n const { fragCurrent } = this;\n return (\n !frag ||\n !fragCurrent ||\n frag.level !== fragCurrent.level ||\n frag.sn !== fragCurrent.sn ||\n frag.urlId !== fragCurrent.urlId\n );\n }\n\n protected fragBufferedComplete(frag: Fragment, part: Part | null) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n this.log(\n `Buffered ${frag.type} sn: ${frag.sn}${\n part ? ' part: ' + part.index : ''\n } of ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'} ${\n frag.level\n } ${\n media\n ? TimeRanges.toString(BufferHelper.getBuffered(media))\n : '(detached)'\n }`\n );\n this.state = State.IDLE;\n if (!media) {\n return;\n }\n if (\n !this.loadedmetadata &&\n frag.type == PlaylistLevelType.MAIN &&\n media.buffered.length &&\n this.fragCurrent?.sn === this.fragPrevious?.sn\n ) {\n this.loadedmetadata = true;\n this.seekToStartPos();\n }\n this.tick();\n }\n\n protected seekToStartPos() {}\n\n protected _handleFragmentLoadComplete(fragLoadedEndData: PartsLoadedData) {\n const { transmuxer } = this;\n if (!transmuxer) {\n return;\n }\n const { frag, part, partsLoaded } = fragLoadedEndData;\n // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data\n const complete =\n !partsLoaded ||\n partsLoaded.length === 0 ||\n partsLoaded.some((fragLoaded) => !fragLoaded);\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount + 1,\n 0,\n part ? part.index : -1,\n !complete\n );\n transmuxer.flush(chunkMeta);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected _handleFragmentLoadProgress(\n frag: PartsLoadedData | FragLoadedData\n ) {}\n\n protected _doFragLoad(\n frag: Fragment,\n details: LevelDetails,\n targetBufferTime: number | null = null,\n progressCallback?: FragmentLoadProgressCallback\n ): Promise<PartsLoadedData | FragLoadedData | null> {\n if (!this.levels) {\n throw new Error('frag load aborted, missing levels');\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 (keyLoadedData && !this.fragContextChanged(keyLoadedData.frag)) {\n this.hls.trigger(Events.KEY_LOADED, keyLoadedData);\n return keyLoadedData;\n }\n });\n this.hls.trigger(Events.KEY_LOADING, { frag });\n this.throwIfFragContextChanged('KEY_LOADING');\n }\n\n targetBufferTime = Math.max(frag.start, targetBufferTime || 0);\n if (this.config.lowLatencyMode && details) {\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 this.hls.trigger(Events.FRAG_LOADING, {\n frag,\n part: partList[partIndex],\n targetBufferTime,\n });\n this.throwIfFragContextChanged('FRAG_LOADING parts');\n if (keyLoadingPromise) {\n return 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 partList,\n partIndex,\n progressCallback\n );\n })\n .catch((error) => this.handleFragLoadError(error));\n }\n\n return this.doFragPartsLoad(\n frag,\n partList,\n partIndex,\n progressCallback\n ).catch((error: LoadError) => this.handleFragLoadError(error));\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 this.hls.trigger(Events.FRAG_LOADING, { frag, targetBufferTime });\n this.throwIfFragContextChanged('FRAG_LOADING');\n\n // Load key before streaming fragment data\n const dataOnProgress = this.config.progressive;\n if (dataOnProgress && keyLoadingPromise) {\n return 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 }\n\n // load unencrypted fragment data with progress event,\n // or handle fragment result after key and fragment are finished loading\n return 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\n private throwIfFragContextChanged(context: string): void | never {\n // exit if context changed during event loop\n if (this.fragCurrent === null) {\n throw new Error(`frag load aborted, context changed in ${context}`);\n }\n }\n\n private doFragPartsLoad(\n frag: Fragment,\n partList: Part[],\n partIndex: number,\n progressCallback: FragmentLoadProgressCallback\n ): Promise<PartsLoadedData | null> {\n return new Promise(\n (resolve: ResolveFragLoaded, reject: RejectFragLoaded) => {\n const partsLoaded: FragLoadedData[] = [];\n const loadPartIndex = (index: number) => {\n const part = partList[index];\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 = partList[index + 1];\n if (nextPart && nextPart.fragment === frag) {\n loadPartIndex(index + 1);\n } else {\n return resolve({\n frag,\n part: loadedPart,\n partsLoaded,\n });\n }\n })\n .catch(reject);\n };\n loadPartIndex(partIndex);\n }\n );\n }\n\n private handleFragLoadError({ data }: LoadError) {\n if (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 return null;\n }\n\n protected _handleTransmuxerFlush(chunkMeta: ChunkMetadata) {\n const context = this.getCurrentContext(chunkMeta);\n if (!context || this.state !== State.PARSING) {\n if (!this.fragCurrent) {\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 } = this;\n const { level: levelIndex, sn, part: partIndex } = chunkMeta;\n if (!levels || !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, this.fragCurrent);\n if (!frag) {\n return null;\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 ) {\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 || !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 // 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 { config } = this;\n const pos = this.getLoadPosition();\n if (!Number.isFinite(pos)) {\n return null;\n }\n const bufferInfo = BufferHelper.bufferInfo(\n bufferable,\n pos,\n config.maxBufferHole\n );\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, config.maxBufferHole)\n );\n }\n }\n return bufferInfo;\n }\n\n protected getMaxBufferLength(levelBitrate?: number): number {\n const { config } = this;\n let maxBufLen;\n if (levelBitrate) {\n maxBufLen = Math.max(\n (8 * config.maxBufferSize) / levelBitrate,\n config.maxBufferLength\n );\n } else {\n maxBufLen = config.maxBufferLength;\n }\n return Math.min(maxBufLen, config.maxMaxBufferLength);\n }\n\n protected reduceMaxBufferLength(threshold?: number) {\n const config = this.config;\n const minLength = threshold || config.maxBufferLength;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n this.warn(`Reduce max buffer length to ${config.maxMaxBufferLength}s`);\n return true;\n }\n return false;\n }\n\n protected getNextFragment(\n pos: number,\n levelDetails: LevelDetails\n ): Fragment | null {\n const fragments = levelDetails.fragments;\n const fragLen = fragments.length;\n\n if (!fragLen) {\n return null;\n }\n\n // find fragment index, contiguous with end of buffer position\n const { config } = this;\n const start = fragments[0].start;\n let frag;\n\n if (levelDetails.live) {\n const initialLiveManifestSize = config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n this.warn(\n `Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`\n );\n return null;\n }\n // The real fragment start times for a live stream are only known after the PTS range for that level is known.\n // In order to discover the range, we load the best matching fragment for that level and demux it.\n // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that\n // we get the fragment matching that start time\n if (\n !levelDetails.PTSKnown &&\n !this.startFragRequested &&\n this.startPosition === -1\n ) {\n frag = this.getInitialLiveFragment(levelDetails, fragments);\n this.startPosition = frag\n ? this.hls.liveSyncPosition || frag.start\n : pos;\n }\n } else if (pos <= start) {\n // VoD playlist: if loadPosition before start of playlist, load first fragment\n frag = fragments[0];\n }\n\n // If we haven't run into any special cases already, just load the fragment most closely matching the requested position\n if (!frag) {\n const end = config.lowLatencyMode\n ? levelDetails.partEnd\n : levelDetails.fragmentEnd;\n frag = this.getFragmentAtPosition(pos, end, levelDetails);\n }\n\n return this.mapToInitFragWhenRequired(frag);\n }\n\n 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 (\n !loaded &&\n (contiguous || part.independent || independentAttrOmitted) &&\n part.fragment === frag\n ) {\n nextPart = i;\n }\n contiguous = loaded;\n }\n return nextPart;\n }\n\n private loadedEndOfParts(\n partList: Part[],\n targetBufferTime: number\n ): boolean {\n const lastPart = partList[partList.length - 1];\n return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;\n }\n\n /*\n This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the\n \"sliding\" of the playlist, which is its offset from the start of playback. After sliding we can compute the real\n start and end times for each fragment in the playlist (after which this method will not need to be called).\n */\n protected getInitialLiveFragment(\n levelDetails: LevelDetails,\n fragments: Array<Fragment>\n ): Fragment | null {\n const fragPrevious = this.fragPrevious;\n let frag: Fragment | null = null;\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding\n this.log(\n `Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`\n );\n frag = findFragmentByPDT(\n fragments,\n fragPrevious.endProgramDateTime,\n this.config.maxFragLookUpTolerance\n );\n }\n if (!frag) {\n // SN does not need to be accurate between renditions, but depending on the packaging it may be so.\n const targetSN = (fragPrevious.sn as number) + 1;\n if (\n targetSN >= levelDetails.startSN &&\n targetSN <= levelDetails.endSN\n ) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n // Ensure that we're staying within the continuity range, since PTS resets upon a new range\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n this.log(\n `Live playlist, switching playlist, load frag with next SN: ${\n frag!.sn\n }`\n );\n }\n }\n // It's important to stay within the continuity range if available; otherwise the fragments in the playlist\n // will have the wrong start times\n if (!frag) {\n frag = findFragWithCC(fragments, fragPrevious.cc);\n if (frag) {\n this.log(\n `Live playlist, switching playlist, load frag with same CC: ${frag.sn}`\n );\n }\n }\n }\n } else {\n // Find a new start fragment when fragPrevious is null\n const liveStart = this.hls.liveSyncPosition;\n if (liveStart !== null) {\n frag = this.getFragmentAtPosition(\n liveStart,\n this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge,\n levelDetails\n );\n }\n }\n\n return frag;\n }\n\n /*\n This method finds the best matching fragment given the provided position.\n */\n protected getFragmentAtPosition(\n bufferEnd: number,\n end: number,\n levelDetails: LevelDetails\n ): Fragment | null {\n const { config } = this;\n let { fragPrevious } = this;\n let { fragments, endSN } = levelDetails;\n const { fragmentHint } = levelDetails;\n const tolerance = config.maxFragLookUpTolerance;\n\n const loadingParts = !!(\n config.lowLatencyMode &&\n levelDetails.partList &&\n fragmentHint\n );\n if (loadingParts && fragmentHint && !this.bitrateTest) {\n // Include incomplete fragment with parts at end\n fragments = fragments.concat(fragmentHint);\n endSN = fragmentHint.sn as number;\n }\n\n let frag;\n if (bufferEnd < end) {\n const lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPTS(\n fragPrevious,\n fragments,\n bufferEnd,\n lookupTolerance\n );\n } else {\n // reach end of playlist\n frag = fragments[fragments.length - 1];\n }\n\n if (frag) {\n const curSNIdx = frag.sn - levelDetails.startSN;\n // Move fragPrevious forward to support forcing the next fragment to load\n // when the buffer catches up to a previously buffered range.\n if (this.fragmentTracker.getState(frag) === FragmentState.OK) {\n fragPrevious = frag;\n }\n if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {\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 this.log(\n `SN ${frag.sn} just loaded, load next one: ${nextFrag.sn}`\n );\n frag = nextFrag;\n } else {\n frag = null;\n }\n }\n }\n }\n return frag;\n }\n\n protected synchronizeToLiveEdge(levelDetails: LevelDetails) {\n const { config, media } = this;\n if (!media) {\n return;\n }\n const liveSyncPosition = this.hls.liveSyncPosition;\n const currentTime = media.currentTime;\n const start = levelDetails.fragments[0].start;\n const end = levelDetails.edge;\n const withinSlidingWindow =\n currentTime >= start - config.maxFragLookUpTolerance &&\n currentTime <= end;\n // Continue if we can seek forward to sync position or if current time is outside of sliding window\n if (\n liveSyncPosition !== null &&\n media.duration > liveSyncPosition &&\n (currentTime < liveSyncPosition || !withinSlidingWindow)\n ) {\n // Continue if buffer is starving or if current time is behind max latency\n const maxLatency =\n config.liveMaxLatencyDuration !== undefined\n ? config.liveMaxLatencyDuration\n : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n if (\n (!withinSlidingWindow && media.readyState < 4) ||\n currentTime < end - maxLatency\n ) {\n if (!this.loadedmetadata) {\n this.nextLoadPosition = liveSyncPosition;\n }\n // Only seek if ready and there is not a significant forward buffer available for playback\n if (media.readyState) {\n this.warn(\n `Playback: ${currentTime.toFixed(\n 3\n )} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(\n 3\n )}`\n );\n media.currentTime = liveSyncPosition;\n }\n }\n }\n }\n\n protected alignPlaylists(\n details: LevelDetails,\n previousDetails?: LevelDetails\n ): number {\n const { levels, levelLastLoaded, fragPrevious } = this;\n const lastLevel: Level | null =\n levelLastLoaded !== null ? levels![levelLastLoaded] : null;\n\n // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,\n // this could all go in level-helper mergeDetails()\n const length = details.fragments.length;\n if (!length) {\n this.warn(`No fragments in live playlist`);\n return 0;\n }\n const slidingStart = details.fragments[0].start;\n const firstLevelLoad = !previousDetails;\n const aligned = details.alignedSliding && Number.isFinite(slidingStart);\n if (firstLevelLoad || (!aligned && !slidingStart)) {\n alignStream(fragPrevious, lastLevel, details);\n const alignedSlidingStart = details.fragments[0].start;\n this.log(\n `Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${\n previousDetails ? previousDetails.startSN : 'na'\n }->${details.startSN} prev-sn: ${\n fragPrevious ? fragPrevious.sn : 'na'\n } fragments: ${length}`\n );\n return alignedSlidingStart;\n }\n return slidingStart;\n }\n\n protected waitForCdnTuneIn(details: LevelDetails) {\n // Wait for Low-Latency CDN Tune-in to get an updated playlist\n const advancePartLimit = 3;\n return (\n details.live &&\n details.canBlockReload &&\n details.partTarget &&\n details.tuneInGoal >\n Math.max(details.partHoldBack, details.partTarget * advancePartLimit)\n );\n }\n\n protected setStartPosition(details: LevelDetails, sliding: number) {\n // compute start position if set to -1. use it straight away if value is defined\n let startPosition = this.startPosition;\n if (startPosition < sliding) {\n startPosition = -1;\n }\n if (startPosition === -1 || this.lastCurrentTime === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n const startTimeOffset = details.startTimeOffset!;\n if (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 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.fatal) {\n return;\n }\n const frag = data.frag;\n // Handle frag error related to caller's filterType\n if (!frag || frag.type !== filterType) {\n return;\n }\n const fragCurrent = this.fragCurrent;\n console.assert(\n fragCurrent &&\n frag.sn === fragCurrent.sn &&\n frag.level === fragCurrent.level &&\n frag.urlId === fragCurrent.urlId,\n 'Frag load error must match current frag to retry'\n );\n const config = this.config;\n // keep retrying until the limit will be reached\n if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n const delay = Math.min(\n Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay,\n config.fragLoadingMaxRetryTimeout\n );\n this.warn(\n `Fragment ${frag.sn} of ${filterType} ${frag.level} failed to load, retrying in ${delay}ms`\n );\n this.retryDate = self.performance.now() + delay;\n this.fragLoadError++;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else if (data.levelRetry) {\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 this.fragLoadError = 0;\n this.state = State.IDLE;\n } else {\n logger.error(\n `${data.details} reaches max retry, redispatch as fatal ...`\n );\n // switch error to fatal\n data.fatal = true;\n this.hls.stopLoad();\n this.state = State.ERROR;\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.fragCurrent = null;\n this.fragPrevious = null;\n this.state = State.IDLE;\n }\n\n protected resetStartWhenNotLoaded(level: number): void {\n // if loadedmetadata is not set, it means that first frag request failed\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n const details = this.levels ? this.levels[level].details : null;\n if (details?.live) {\n // Update the start position and return to IDLE to recover live start\n this.startPosition = -1;\n this.setStartPosition(details, 0);\n this.resetLoadingState();\n } else {\n this.nextLoadPosition = this.startPosition;\n }\n }\n }\n\n private updateLevelTiming(\n frag: Fragment,\n part: Part | null,\n level: Level,\n partial: boolean\n ) {\n const details = level.details as LevelDetails;\n console.assert(!!details, 'level.details must be defined');\n const parsed = Object.keys(frag.elementaryStreams).reduce(\n (result, type) => {\n const info = frag.elementaryStreams[type];\n if (info) {\n const parsedDuration = info.endPTS - info.startPTS;\n if (parsedDuration <= 0) {\n // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.\n // The new transmuxer will be configured with a time offset matching the next fragment start,\n // preventing the timeline from shifting.\n this.warn(\n `Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`\n );\n return result || false;\n }\n const drift = partial\n ? 0\n : updateFragPTSDTS(\n details,\n frag,\n info.startPTS,\n info.endPTS,\n info.startDTS,\n info.endDTS\n );\n this.hls.trigger(Events.LEVEL_PTS_UPDATED, {\n details,\n level,\n drift,\n type,\n frag,\n start: info.startPTS,\n end: info.endPTS,\n });\n return true;\n }\n return result;\n },\n false\n );\n if (!parsed) {\n this.warn(\n `Found no media in fragment ${frag.sn} of level ${level.id} resetting transmuxer to fallback to playlist timing`\n );\n this.resetTransmuxer();\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 set state(nextState) {\n const previousState = this._state;\n if (previousState !== nextState) {\n this._state = nextState;\n this.log(`${previousState}->${nextState}`);\n }\n }\n\n get state() {\n return this._state;\n }\n}\n","import { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport type { TrackSet } from '../types/track';\nimport BufferOperationQueue from './buffer-operation-queue';\nimport {\n BufferOperation,\n SourceBuffers,\n SourceBufferName,\n SourceBufferListeners,\n} from '../types/buffer';\nimport type {\n LevelUpdatedData,\n BufferAppendingData,\n MediaAttachingData,\n ManifestParsedData,\n BufferCodecsData,\n BufferEOSData,\n BufferFlushingData,\n FragParsedData,\n FragChangedData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport { LevelDetails } from '../loader/level-details';\n\nconst MediaSource = getMediaSource();\nconst VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\\.[^.,]+)+/;\n\nexport default class BufferController implements ComponentAPI {\n // The level details used to determine duration, target-duration and live\n private details: LevelDetails | null = null;\n // cache the self generated object url to detect hijack of video tag\n private _objectUrl: string | null = null;\n // A queue of buffer operations which require the SourceBuffer to not be updating upon execution\n private operationQueue!: BufferOperationQueue;\n // References to event listeners for each SourceBuffer, so that they can be referenced for event removal\n private listeners!: SourceBufferListeners;\n\n private hls: Hls;\n\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n public bufferCodecEventsExpected: number = 0;\n\n // The total number of BUFFER_CODEC events received\n private _bufferCodecEventsTotal: number = 0;\n\n // A reference to the attached media element\n public media: HTMLMediaElement | null = null;\n\n // A reference to the active media source\n public mediaSource: MediaSource | null = null;\n\n // counters\n public appendError: number = 0;\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer!: SourceBuffers;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this._initSourceBuffer();\n this.registerListeners();\n }\n\n public hasSourceTypes(): boolean {\n return (\n this.getSourceBufferTypes().length > 0 ||\n Object.keys(this.pendingTracks).length > 0\n );\n }\n\n public destroy() {\n this.unregisterListeners();\n this.details = null;\n }\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_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_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 }\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) {\n codecEvents = 1;\n }\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n this.details = null;\n logger.log(\n `${this.bufferCodecEventsExpected} bufferCodec event(s) expected`\n );\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n const media = (this.media = data.media);\n if (media && MediaSource) {\n const ms = (this.mediaSource = new MediaSource());\n // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\n // link video and media Source\n media.src = self.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n protected onMediaDetaching() {\n const { media, mediaSource, _objectUrl } = this;\n if (mediaSource) {\n logger.log('[buffer-controller]: media source detaching');\n if (mediaSource.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n mediaSource.endOfStream();\n } catch (err) {\n logger.warn(\n `[buffer-controller]: onMediaDetaching: ${err.message} while calling endOfStream`\n );\n }\n }\n // Clean up the SourceBuffers by invoking onBufferReset\n this.onBufferReset();\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);\n mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (media) {\n if (_objectUrl) {\n self.URL.revokeObjectURL(_objectUrl);\n }\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (media.src === _objectUrl) {\n media.removeAttribute('src');\n media.load();\n } else {\n logger.warn(\n '[buffer-controller]: media.src was changed by a third party - skip cleanup'\n );\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = null;\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n this.pendingTracks = {};\n this.tracks = {};\n }\n\n this.hls.trigger(Events.MEDIA_DETACHED, undefined);\n }\n\n protected onBufferReset() {\n this.getSourceBufferTypes().forEach((type) => {\n const sb = this.sourceBuffer[type];\n try {\n if (sb) {\n this.removeBufferListeners(type);\n if (this.mediaSource) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n // Synchronously remove the SB from the map before the next call in order to prevent an async function from\n // accessing it\n this.sourceBuffer[type] = undefined;\n }\n } catch (err) {\n logger.warn(\n `[buffer-controller]: Failed to reset the ${type} buffer`,\n err\n );\n }\n });\n this._initSourceBuffer();\n }\n\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData\n ) {\n const sourceBufferCount = this.getSourceBufferTypes().length;\n\n Object.keys(data).forEach((trackName) => {\n if (sourceBufferCount) {\n // check if SourceBuffer codec needs to change\n const track = this.tracks[trackName];\n if (track && typeof track.buffer.changeType === 'function') {\n const { id, codec, levelCodec, container, metadata } =\n data[trackName];\n const currentCodec = (track.levelCodec || track.codec).replace(\n VIDEO_CODEC_PROFILE_REPACE,\n '$1'\n );\n const nextCodec = (levelCodec || codec).replace(\n VIDEO_CODEC_PROFILE_REPACE,\n '$1'\n );\n if (currentCodec !== nextCodec) {\n const mimeType = `${container};codecs=${levelCodec || codec}`;\n this.appendChangeType(trackName, mimeType);\n logger.log(\n `[buffer-controller]: switching codec ${currentCodec} to ${nextCodec}`\n );\n this.tracks[trackName] = {\n buffer: track.buffer,\n codec,\n container,\n levelCodec,\n metadata,\n id,\n };\n }\n }\n } else {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n this.pendingTracks[trackName] = data[trackName];\n }\n });\n\n // if sourcebuffers already created, do nothing ...\n if (sourceBufferCount) {\n return;\n }\n\n this.bufferCodecEventsExpected = Math.max(\n this.bufferCodecEventsExpected - 1,\n 0\n );\n if (this.mediaSource && this.mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n protected appendChangeType(type, mimeType) {\n const { operationQueue } = this;\n const operation: BufferOperation = {\n execute: () => {\n const sb = this.sourceBuffer[type];\n if (sb) {\n logger.log(\n `[buffer-controller]: changing ${type} sourceBuffer type to ${mimeType}`\n );\n sb.changeType(mimeType);\n }\n operationQueue.shiftAndExecuteNext(type);\n },\n onStart: () => {},\n onComplete: () => {},\n onError: (e) => {\n logger.warn(\n `[buffer-controller]: Failed to change ${type} SourceBuffer type`,\n e\n );\n },\n };\n\n operationQueue.append(operation, type);\n }\n\n protected onBufferAppending(\n event: Events.BUFFER_APPENDING,\n eventData: BufferAppendingData\n ) {\n const { hls, operationQueue, tracks } = this;\n const { data, type, frag, part, chunkMeta } = eventData;\n const chunkStats = chunkMeta.buffering[type];\n\n const bufferAppendingStart = self.performance.now();\n chunkStats.start = bufferAppendingStart;\n const fragBuffering = frag.stats.buffering;\n const partBuffering = part ? part.stats.buffering : null;\n if (fragBuffering.start === 0) {\n fragBuffering.start = bufferAppendingStart;\n }\n if (partBuffering && partBuffering.start === 0) {\n partBuffering.start = bufferAppendingStart;\n }\n\n // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n const audioTrack = tracks.audio;\n const checkTimestampOffset =\n type === 'audio' &&\n chunkMeta.id === 1 &&\n audioTrack?.container === 'audio/mpeg';\n\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 = frag.start - sb.timestampOffset;\n if (Math.abs(delta) >= 0.1) {\n logger.log(\n `[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${frag.start} (delta: ${delta}) sn: ${frag.sn})`\n );\n sb.timestampOffset = frag.start;\n }\n }\n }\n this.appendExecutor(data, type);\n },\n onStart: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);\n const end = self.performance.now();\n chunkStats.executeEnd = chunkStats.end = end;\n if (fragBuffering.first === 0) {\n fragBuffering.first = end;\n }\n if (partBuffering && partBuffering.first === 0) {\n partBuffering.first = end;\n }\n\n const { sourceBuffer } = this;\n const timeRanges = {};\n for (const type in sourceBuffer) {\n timeRanges[type] = BufferHelper.getBuffered(sourceBuffer[type]);\n }\n this.appendError = 0;\n this.hls.trigger(Events.BUFFER_APPENDED, {\n type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n timeRanges,\n });\n },\n onError: (err) => {\n // in case any error occured while appending, put back segment in segments table\n logger.error(\n `[buffer-controller]: Error encountered while trying to append to the ${type} SourceBuffer`,\n err\n );\n const event = {\n type: ErrorTypes.MEDIA_ERROR,\n parent: frag.type,\n details: ErrorDetails.BUFFER_APPEND_ERROR,\n err,\n fatal: false,\n };\n\n if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n } else {\n this.appendError++;\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. Retrying can help recover.\n */\n if (this.appendError > hls.config.appendErrorMaxRetry) {\n logger.error(\n `[buffer-controller]: Failed ${hls.config.appendErrorMaxRetry} times to append segment in sourceBuffer`\n );\n event.fatal = true;\n hls.stopLoad();\n }\n }\n hls.trigger(Events.ERROR, event);\n },\n };\n operationQueue.append(operation, type);\n }\n\n protected onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData\n ) {\n const { operationQueue } = this;\n const flushOperation = (type: SourceBufferName): BufferOperation => ({\n execute: this.removeExecutor.bind(\n this,\n type,\n data.startOffset,\n data.endOffset\n ),\n onStart: () => {\n // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n this.hls.trigger(Events.BUFFER_FLUSHED, { type });\n },\n onError: (e) => {\n logger.warn(\n `[buffer-controller]: Failed to remove from ${type} SourceBuffer`,\n e\n );\n },\n });\n\n if (data.type) {\n operationQueue.append(flushOperation(data.type), data.type);\n } else {\n this.getSourceBufferTypes().forEach((type: SourceBufferName) => {\n operationQueue.append(flushOperation(type), type);\n });\n }\n }\n\n protected onFragParsed(event: Events.FRAG_PARSED, data: FragParsedData) {\n const { frag, part } = data;\n const buffersAppendedTo: Array<SourceBufferName> = [];\n const elementaryStreams = part\n ? part.elementaryStreams\n : frag.elementaryStreams;\n if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {\n buffersAppendedTo.push('audiovideo');\n } else {\n if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {\n buffersAppendedTo.push('audio');\n }\n if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {\n buffersAppendedTo.push('video');\n }\n }\n\n const onUnblocked = () => {\n const now = self.performance.now();\n frag.stats.buffering.end = now;\n if (part) {\n part.stats.buffering.end = now;\n }\n const stats = part ? part.stats : frag.stats;\n this.hls.trigger(Events.FRAG_BUFFERED, {\n frag,\n part,\n stats,\n id: frag.type,\n });\n };\n\n if (buffersAppendedTo.length === 0) {\n logger.warn(\n `Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`\n );\n }\n\n this.blockBuffers(onUnblocked, buffersAppendedTo);\n }\n\n private onFragChanged(event: Events.FRAG_CHANGED, data: FragChangedData) {\n this.flushBackBuffer();\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n // an undefined data.type will mark all buffers as EOS.\n protected onBufferEos(event: Events.BUFFER_EOS, data: BufferEOSData) {\n const ended = this.getSourceBufferTypes().reduce((acc, type) => {\n const sb = this.sourceBuffer[type];\n if (!data.type || data.type === type) {\n if (sb && !sb.ended) {\n sb.ended = true;\n logger.log(`[buffer-controller]: ${type} sourceBuffer now EOS`);\n }\n }\n return acc && !!(!sb || sb.ended);\n }, true);\n\n if (ended) {\n this.blockBuffers(() => {\n const { mediaSource } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n return;\n }\n // Allow this to throw and be caught by the enqueueing function\n mediaSource.endOfStream();\n });\n }\n }\n\n protected onLevelUpdated(\n event: Events.LEVEL_UPDATED,\n { details }: LevelUpdatedData\n ) {\n if (!details.fragments.length) {\n return;\n }\n this.details = details;\n\n if (this.getSourceBufferTypes().length) {\n this.blockBuffers(this.updateMediaElementDuration.bind(this));\n } else {\n this.updateMediaElementDuration();\n }\n }\n\n flushBackBuffer() {\n const { hls, details, media, sourceBuffer } = this;\n if (!media || details === null) {\n return;\n }\n\n const sourceBufferTypes = this.getSourceBufferTypes();\n if (!sourceBufferTypes.length) {\n return;\n }\n\n // Support for deprecated liveBackBufferLength\n const backBufferLength =\n details.live && hls.config.liveBackBufferLength !== null\n ? hls.config.liveBackBufferLength\n : hls.config.backBufferLength;\n\n if (!Number.isFinite(backBufferLength) || backBufferLength < 0) {\n return;\n }\n\n const currentTime = media.currentTime;\n const targetDuration = details.levelTargetDuration;\n const maxBackBufferLength = Math.max(backBufferLength, targetDuration);\n const targetBackBufferPosition =\n Math.floor(currentTime / targetDuration) * targetDuration -\n maxBackBufferLength;\n sourceBufferTypes.forEach((type: SourceBufferName) => {\n const sb = sourceBuffer[type];\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n // when target buffer start exceeds actual buffer start\n if (\n buffered.length > 0 &&\n targetBackBufferPosition > buffered.start(0)\n ) {\n hls.trigger(Events.BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n\n // Support for deprecated event:\n if (details.live) {\n hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n }\n\n hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: targetBackBufferPosition,\n type,\n });\n }\n }\n });\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n private updateMediaElementDuration() {\n if (\n !this.details ||\n !this.media ||\n !this.mediaSource ||\n this.mediaSource.readyState !== 'open'\n ) {\n return;\n }\n const { details, hls, media, mediaSource } = this;\n const levelDuration = details.fragments[0].start + details.totalduration;\n const mediaDuration = media.duration;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : 0;\n\n if (details.live && hls.config.liveDurationInfinity) {\n // Override duration to Infinity\n logger.log(\n '[buffer-controller]: Media Source duration is set to Infinity'\n );\n mediaSource.duration = Infinity;\n this.updateSeekableRange(details);\n } else if (\n (levelDuration > msDuration && levelDuration > mediaDuration) ||\n !Number.isFinite(mediaDuration)\n ) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(\n `[buffer-controller]: Updating Media Source duration to ${levelDuration.toFixed(\n 3\n )}`\n );\n mediaSource.duration = levelDuration;\n }\n }\n\n updateSeekableRange(levelDetails) {\n const mediaSource = this.mediaSource;\n const fragments = levelDetails.fragments;\n const len = fragments.length;\n if (len && levelDetails.live && mediaSource?.setLiveSeekableRange) {\n const start = Math.max(0, fragments[0].start);\n const end = Math.max(start, start + levelDetails.totalduration);\n mediaSource.setLiveSeekableRange(start, end);\n }\n }\n\n protected checkPendingTracks() {\n const { bufferCodecEventsExpected, operationQueue, pendingTracks } = this;\n\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n const pendingTracksCount = Object.keys(pendingTracks).length;\n if (\n (pendingTracksCount && !bufferCodecEventsExpected) ||\n pendingTracksCount === 2\n ) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n const buffers = this.getSourceBufferTypes();\n if (buffers.length === 0) {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n reason: 'could not create source buffer for media codec(s)',\n });\n return;\n }\n buffers.forEach((type: SourceBufferName) => {\n operationQueue.executeNext(type);\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 let tracksCreated = 0;\n for (const trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n const track = tracks[trackName as keyof TrackSet];\n if (!track) {\n throw Error(\n `source buffer exists for track ${trackName}, however track does not`\n );\n }\n // use levelCodec as first priority\n const codec = track.levelCodec || track.codec;\n const mimeType = `${track.container};codecs=${codec}`;\n logger.log(`[buffer-controller]: creating sourceBuffer(${mimeType})`);\n try {\n const sb = (sourceBuffer[trackName] =\n mediaSource.addSourceBuffer(mimeType));\n const sbName = trackName as SourceBufferName;\n this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);\n this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);\n this.addBufferListener(sbName, 'error', this._onSBUpdateError);\n this.tracks[trackName] = {\n buffer: sb,\n codec: codec,\n container: track.container,\n levelCodec: track.levelCodec,\n metadata: track.metadata,\n id: track.id,\n };\n tracksCreated++;\n } catch (err) {\n logger.error(\n `[buffer-controller]: error while trying to add sourceBuffer: ${err.message}`\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,\n fatal: false,\n error: err,\n mimeType: mimeType,\n });\n }\n }\n }\n if (tracksCreated) {\n this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks });\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 { hls, media, mediaSource } = this;\n logger.log('[buffer-controller]: Media source opened');\n if (media) {\n this.updateMediaElementDuration();\n hls.trigger(Events.MEDIA_ATTACHED, { media });\n }\n\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n }\n this.checkPendingTracks();\n };\n\n private _onMediaSourceClose = () => {\n logger.log('[buffer-controller]: Media source closed');\n };\n\n private _onMediaSourceEnded = () => {\n logger.log('[buffer-controller]: Media source ended');\n };\n\n private _onSBUpdateStart(type: SourceBufferName) {\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onStart();\n }\n\n private _onSBUpdateEnd(type: SourceBufferName) {\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onComplete();\n operationQueue.shiftAndExecuteNext(type);\n }\n\n private _onSBUpdateError(type: SourceBufferName, event: Event) {\n logger.error(`[buffer-controller]: ${type} SourceBuffer 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 fatal: false,\n });\n // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue\n const operation = this.operationQueue.current(type);\n if (operation) {\n operation.onError(event);\n }\n }\n\n // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually\n private removeExecutor(\n type: SourceBufferName,\n startOffset: number,\n endOffset: number\n ) {\n const { media, mediaSource, operationQueue, sourceBuffer } = this;\n const sb = sourceBuffer[type];\n if (!media || !mediaSource || !sb) {\n logger.warn(\n `[buffer-controller]: Attempting to remove from the ${type} SourceBuffer, but it does not exist`\n );\n operationQueue.shiftAndExecuteNext(type);\n return;\n }\n const mediaDuration = Number.isFinite(media.duration)\n ? media.duration\n : Infinity;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : Infinity;\n const removeStart = Math.max(0, startOffset);\n const removeEnd = Math.min(endOffset, mediaDuration, msDuration);\n if (removeEnd > removeStart) {\n logger.log(\n `[buffer-controller]: Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`\n );\n console.assert(!sb.updating, `${type} sourceBuffer must not be updating`);\n sb.remove(removeStart, removeEnd);\n } else {\n // Cycle the queue\n operationQueue.shiftAndExecuteNext(type);\n }\n }\n\n // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually\n private appendExecutor(data: Uint8Array, type: SourceBufferName) {\n const { operationQueue, sourceBuffer } = this;\n const sb = sourceBuffer[type];\n if (!sb) {\n logger.warn(\n `[buffer-controller]: Attempting to append to the ${type} SourceBuffer, but it does not exist`\n );\n operationQueue.shiftAndExecuteNext(type);\n return;\n }\n\n sb.ended = false;\n console.assert(!sb.updating, `${type} sourceBuffer must not be updating`);\n sb.appendBuffer(data);\n }\n\n // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises\n // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue\n // upon completion, since we already do it here\n private blockBuffers(\n onUnblocked: () => void,\n buffers: Array<SourceBufferName> = this.getSourceBufferTypes()\n ) {\n if (!buffers.length) {\n logger.log(\n '[buffer-controller]: Blocking operation requested, but no SourceBuffers exist'\n );\n Promise.resolve().then(onUnblocked);\n return;\n }\n const { operationQueue } = this;\n\n // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);\n const blockingOperations = buffers.map((type) =>\n operationQueue.appendBlocker(type as SourceBufferName)\n );\n Promise.all(blockingOperations).then(() => {\n // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);\n onUnblocked();\n buffers.forEach((type) => {\n const sb = this.sourceBuffer[type];\n // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to\n // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)\n // While this is a workaround, it's probably useful to have around\n if (!sb || !sb.updating) {\n operationQueue.shiftAndExecuteNext(type);\n }\n });\n });\n }\n\n private getSourceBufferTypes(): Array<SourceBufferName> {\n return Object.keys(this.sourceBuffer) as Array<SourceBufferName>;\n }\n\n private addBufferListener(\n type: SourceBufferName,\n event: string,\n fn: Function\n ) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n const listener = fn.bind(this, type);\n this.listeners[type].push({ event, listener });\n buffer.addEventListener(event, listener);\n }\n\n private removeBufferListeners(type: SourceBufferName) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n this.listeners[type].forEach((l) => {\n buffer.removeEventListener(l.event, l.listener);\n });\n }\n}\n","import { logger } from '../utils/logger';\nimport type {\n BufferOperation,\n BufferOperationQueues,\n SourceBuffers,\n SourceBufferName,\n} from '../types/buffer';\n\nexport default class BufferOperationQueue {\n private buffers: SourceBuffers;\n private queues: BufferOperationQueues = {\n video: [],\n audio: [],\n audiovideo: [],\n };\n\n constructor(sourceBufferReference: SourceBuffers) {\n this.buffers = sourceBufferReference;\n }\n\n public append(operation: BufferOperation, type: SourceBufferName) {\n const queue = this.queues[type];\n queue.push(operation);\n if (queue.length === 1 && this.buffers[type]) {\n this.executeNext(type);\n }\n }\n\n public insertAbort(operation: BufferOperation, type: SourceBufferName) {\n const queue = this.queues[type];\n queue.unshift(operation);\n this.executeNext(type);\n }\n\n public appendBlocker(type: SourceBufferName): Promise<{}> {\n let execute;\n const promise: Promise<{}> = new Promise((resolve) => {\n execute = resolve;\n });\n const operation: BufferOperation = {\n execute,\n onStart: () => {},\n onComplete: () => {},\n onError: () => {},\n };\n\n this.append(operation, type);\n return promise;\n }\n\n public executeNext(type: SourceBufferName) {\n const { buffers, queues } = this;\n const sb = buffers[type];\n const queue = queues[type];\n if (queue.length) {\n const operation: BufferOperation = queue[0];\n try {\n // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations\n // which do not end with this event must call _onSBUpdateEnd manually\n operation.execute();\n } catch (e) {\n logger.warn(\n '[buffer-operation-queue]: Unhandled exception executing the current operation'\n );\n operation.onError(e);\n\n // Only shift the current operation off, otherwise the updateend handler will do this for us\n if (!sb || !sb.updating) {\n queue.shift();\n this.executeNext(type);\n }\n }\n }\n }\n\n public shiftAndExecuteNext(type: SourceBufferName) {\n this.queues[type].shift();\n this.executeNext(type);\n }\n\n public current(type: SourceBufferName) {\n return this.queues[type][0];\n }\n}\n","/*\n * cap stream level to media size dimension controller\n */\n\nimport { Events } from '../events';\nimport type { Level } from '../types/level';\nimport type {\n ManifestParsedData,\n BufferCodecsData,\n MediaAttachingData,\n FPSDropLevelCappingData,\n} from '../types/events';\nimport StreamController from './stream-controller';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\n\nclass CapLevelController implements ComponentAPI {\n public autoLevelCapping: number;\n public firstLevel: number;\n public media: HTMLVideoElement | null;\n public restrictedLevels: Array<number>;\n public timer: number | undefined;\n\n private hls: Hls;\n private streamController?: StreamController;\n public clientRect: { width: number; height: number } | null;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = -1;\n this.media = null;\n this.restrictedLevels = [];\n this.timer = undefined;\n this.clientRect = null;\n\n this.registerListeners();\n }\n\n public setStreamController(streamController: StreamController) {\n this.streamController = streamController;\n }\n\n public destroy() {\n this.unregisterListener();\n if (this.hls.config.capLevelToPlayerSize) {\n this.stopCapping();\n }\n this.media = null;\n this.clientRect = null;\n // @ts-ignore\n this.hls = this.streamController = null;\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected unregisterListener() {\n const { hls } = this;\n hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected onFpsDropLevelCapping(\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData\n ) {\n // Don't add a restricted level more than once\n if (\n CapLevelController.isLevelAllowed(\n data.droppedLevel,\n this.restrictedLevels\n )\n ) {\n this.restrictedLevels.push(data.droppedLevel);\n }\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n this.media = data.media instanceof HTMLVideoElement ? data.media : null;\n this.clientRect = null;\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData\n ) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n\n protected onMediaDetaching() {\n this.stopCapping();\n }\n\n detectPlayerSize() {\n if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {\n const levels = this.hls.levels;\n if (levels.length) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);\n if (\n hls.autoLevelCapping > this.autoLevelCapping &&\n this.streamController\n ) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n this.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel(capLevelIndex: number): number {\n const levels = this.hls.levels;\n if (!levels.length) {\n return -1;\n }\n\n const validLevels = levels.filter(\n (level, index) =>\n CapLevelController.isLevelAllowed(index, this.restrictedLevels) &&\n index <= capLevelIndex\n );\n\n this.clientRect = null;\n return CapLevelController.getMaxLevelByMediaSize(\n validLevels,\n this.mediaWidth,\n this.mediaHeight\n );\n }\n\n startCapping() {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n self.clearInterval(this.timer);\n this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n stopCapping() {\n this.restrictedLevels = [];\n this.firstLevel = -1;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n self.clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n\n getDimensions(): { width: number; height: number } {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0,\n };\n\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width =\n clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height =\n clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n\n get mediaWidth(): number {\n return this.getDimensions().width * this.contentScaleFactor;\n }\n\n get mediaHeight(): number {\n return this.getDimensions().height * this.contentScaleFactor;\n }\n\n get contentScaleFactor(): number {\n let pixelRatio = 1;\n if (!this.hls.config.ignoreDevicePixelRatio) {\n try {\n pixelRatio = self.devicePixelRatio;\n } catch (e) {\n /* no-op */\n }\n }\n\n return pixelRatio;\n }\n\n static isLevelAllowed(\n level: number,\n restrictedLevels: Array<number> = []\n ): boolean {\n return restrictedLevels.indexOf(level) === -1;\n }\n\n static getMaxLevelByMediaSize(\n levels: Array<Level>,\n width: number,\n height: number\n ): number {\n if (!levels || !levels.length) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandwidth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n\n return (\n curLevel.width !== nextLevel.width ||\n curLevel.height !== nextLevel.height\n );\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if (\n (level.width >= width || level.height >= height) &&\n atGreatestBandwidth(level, levels[i + 1])\n ) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","import {\n FragmentLoaderConstructor,\n HlsConfig,\n PlaylistLoaderConstructor,\n} from '../config';\nimport { Events } from '../events';\nimport Hls, { Fragment } from '../hls';\nimport {\n CMCD,\n CMCDHeaders,\n CMCDObjectType,\n CMCDStreamingFormat,\n CMCDVersion,\n} from '../types/cmcd';\nimport { ComponentAPI } from '../types/component-api';\nimport { BufferCreatedData, MediaAttachedData } from '../types/events';\nimport {\n FragmentLoaderContext,\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n PlaylistLoaderContext,\n} from '../types/loader';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\n\n/**\n * Controller to deal with Common Media Client Data (CMCD)\n * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf\n */\nexport default class CMCDController implements ComponentAPI {\n private hls: Hls;\n private config: HlsConfig;\n private media?: HTMLMediaElement;\n private sid?: string;\n private cid?: string;\n private useHeaders: boolean = false;\n private initialized: boolean = false;\n private starved: boolean = false;\n private buffering: boolean = true;\n private audioBuffer?: SourceBuffer; // eslint-disable-line no-restricted-globals\n private videoBuffer?: SourceBuffer; // eslint-disable-line no-restricted-globals\n\n constructor(hls: Hls) {\n this.hls = hls;\n const config = (this.config = hls.config);\n const { cmcd } = config;\n\n if (cmcd != null) {\n config.pLoader = this.createPlaylistLoader();\n config.fLoader = this.createFragmentLoader();\n\n this.sid = cmcd.sessionId || CMCDController.uuid();\n this.cid = cmcd.contentId;\n this.useHeaders = cmcd.useHeaders === true;\n this.registerListeners();\n }\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n\n this.onMediaDetached();\n }\n\n destroy() {\n this.unregisterListeners();\n\n // @ts-ignore\n this.hls = this.config = this.audioBuffer = this.videoBuffer = null;\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) {\n this.media = data.media;\n this.media.addEventListener('waiting', this.onWaiting);\n this.media.addEventListener('playing', this.onPlaying);\n }\n\n private onMediaDetached() {\n if (!this.media) {\n return;\n }\n\n this.media.removeEventListener('waiting', this.onWaiting);\n this.media.removeEventListener('playing', this.onPlaying);\n\n // @ts-ignore\n this.media = null;\n }\n\n private onBufferCreated(\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData\n ) {\n this.audioBuffer = data.tracks.audio?.buffer;\n this.videoBuffer = data.tracks.video?.buffer;\n }\n\n private onWaiting = () => {\n if (this.initialized) {\n this.starved = true;\n }\n\n this.buffering = true;\n };\n\n private onPlaying = () => {\n if (!this.initialized) {\n this.initialized = true;\n }\n\n this.buffering = false;\n };\n\n /**\n * Create baseline CMCD data\n */\n private createData(): CMCD {\n return {\n v: CMCDVersion,\n sf: 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 if (this.useHeaders) {\n const headers = CMCDController.toHeaders(data);\n if (!Object.keys(headers).length) {\n return;\n }\n\n if (!context.headers) {\n context.headers = {};\n }\n\n Object.assign(context.headers, headers);\n } else {\n const query = CMCDController.toQuery(data);\n if (!query) {\n return;\n }\n\n context.url = CMCDController.appendQueryToUri(context.url, query);\n }\n }\n\n /**\n * Apply CMCD data to a manifest request.\n */\n private applyPlaylistData = (context: PlaylistLoaderContext) => {\n try {\n this.apply(context, {\n ot: CMCDObjectType.MANIFEST,\n su: !this.initialized,\n });\n } catch (error) {\n logger.warn('Could not generate manifest CMCD data.', error);\n }\n };\n\n /**\n * Apply CMCD data to a segment request\n */\n private applyFragmentData = (context: FragmentLoaderContext) => {\n try {\n const fragment = context.frag;\n const level = this.hls.levels[fragment.level];\n const ot = this.getObjectType(fragment);\n const data: CMCD = {\n d: fragment.duration * 1000,\n ot,\n };\n\n if (\n ot === CMCDObjectType.VIDEO ||\n ot === CMCDObjectType.AUDIO ||\n ot == CMCDObjectType.MUXED\n ) {\n data.br = level.bitrate / 1000;\n data.tb = this.getTopBandwidth(ot) / 1000;\n data.bl = this.getBufferLength(ot);\n }\n\n this.apply(context, data);\n } catch (error) {\n logger.warn('Could not generate segment CMCD data.', error);\n }\n };\n\n /**\n * The CMCD object type.\n */\n private getObjectType(fragment: Fragment): CMCDObjectType | undefined {\n const { type } = fragment;\n\n if (type === 'subtitle') {\n return CMCDObjectType.TIMED_TEXT;\n }\n\n if (fragment.sn === 'initSegment') {\n return CMCDObjectType.INIT;\n }\n\n if (type === 'audio') {\n return CMCDObjectType.AUDIO;\n }\n\n if (type === 'main') {\n if (!this.hls.audioTracks.length) {\n return CMCDObjectType.MUXED;\n }\n\n return CMCDObjectType.VIDEO;\n }\n\n return undefined;\n }\n\n /**\n * Get the highest bitrate.\n */\n private getTopBandwidth(type: CMCDObjectType) {\n let bitrate: number = 0;\n let levels;\n const hls = this.hls;\n\n if (type === CMCDObjectType.AUDIO) {\n levels = hls.audioTracks;\n } else {\n const max = hls.maxAutoLevel;\n const len = max > -1 ? max + 1 : hls.levels.length;\n levels = hls.levels.slice(0, len);\n }\n\n for (const level of levels) {\n if (level.bitrate > bitrate) {\n bitrate = level.bitrate;\n }\n }\n\n return bitrate > 0 ? bitrate : NaN;\n }\n\n /**\n * Get the buffer length for a media type in milliseconds\n */\n private getBufferLength(type: CMCDObjectType) {\n const media = this.hls.media;\n const buffer =\n type === CMCDObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;\n\n if (!buffer || !media) {\n return NaN;\n }\n\n const info = BufferHelper.bufferInfo(\n buffer,\n media.currentTime,\n this.config.maxBufferHole\n );\n\n return info.len * 1000;\n }\n\n /**\n * Create a playlist loader\n */\n private createPlaylistLoader(): PlaylistLoaderConstructor | undefined {\n const { pLoader } = this.config;\n const apply = this.applyPlaylistData;\n const Ctor = pLoader || (this.config.loader as PlaylistLoaderConstructor);\n\n return class CmcdPlaylistLoader {\n private loader: Loader<PlaylistLoaderContext>;\n\n constructor(config: HlsConfig) {\n this.loader = new Ctor(config);\n }\n\n get stats() {\n return this.loader.stats;\n }\n\n get context() {\n return this.loader.context;\n }\n\n destroy() {\n this.loader.destroy();\n }\n\n abort() {\n this.loader.abort();\n }\n\n load(\n context: PlaylistLoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<PlaylistLoaderContext>\n ) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n\n /**\n * Create a playlist loader\n */\n private createFragmentLoader(): FragmentLoaderConstructor | undefined {\n const { fLoader } = this.config;\n const apply = this.applyFragmentData;\n const Ctor = fLoader || (this.config.loader as FragmentLoaderConstructor);\n\n return class CmcdFragmentLoader {\n private loader: Loader<FragmentLoaderContext>;\n\n constructor(config: HlsConfig) {\n this.loader = new Ctor(config);\n }\n\n get stats() {\n return this.loader.stats;\n }\n\n get context() {\n return this.loader.context;\n }\n\n destroy() {\n this.loader.destroy();\n }\n\n abort() {\n this.loader.abort();\n }\n\n load(\n context: FragmentLoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<FragmentLoaderContext>\n ) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n\n /**\n * Generate a random v4 UUI\n *\n * @returns {string}\n */\n static uuid(): string {\n const url = URL.createObjectURL(new Blob());\n const uuid = url.toString();\n URL.revokeObjectURL(url);\n return uuid.slice(uuid.lastIndexOf('/') + 1);\n }\n\n /**\n * Serialize a CMCD data object according to the rules defined in the\n * section 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static serialize(data: CMCD): string {\n const results: string[] = [];\n const isValid = (value: any) =>\n !Number.isNaN(value) && value != null && value !== '' && value !== false;\n const toRounded = (value: number) => Math.round(value);\n const toHundred = (value: number) => toRounded(value / 100) * 100;\n const toUrlSafe = (value: string) => encodeURIComponent(value);\n const formatters = {\n br: toRounded,\n d: toRounded,\n bl: toHundred,\n dl: toHundred,\n mtp: toHundred,\n nor: toUrlSafe,\n rtp: toHundred,\n tb: toRounded,\n };\n\n const keys = Object.keys(data || {}).sort();\n\n for (const key of keys) {\n let value = data[key];\n\n // ignore invalid values\n if (!isValid(value)) {\n continue;\n }\n\n // Version should only be reported if not equal to 1.\n if (key === 'v' && value === 1) {\n continue;\n }\n\n // Playback rate should only be sent if not equal to 1.\n if (key == 'pr' && value === 1) {\n continue;\n }\n\n // Certain values require special formatting\n const formatter = formatters[key];\n if (formatter) {\n value = formatter(value);\n }\n\n // Serialize the key/value pair\n const type = typeof value;\n let result: string;\n\n if (key === 'ot' || key === 'sf' || key === 'st') {\n result = `${key}=${value}`;\n } else if (type === 'boolean') {\n result = key;\n } else if (type === 'number') {\n result = `${key}=${value}`;\n } else {\n result = `${key}=${JSON.stringify(value)}`;\n }\n\n results.push(result);\n }\n\n return results.join(',');\n }\n\n /**\n * Convert a CMCD data object to request headers according to the rules\n * defined in the section 2.1 and 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static toHeaders(data: CMCD): Partial<CMCDHeaders> {\n const keys = Object.keys(data);\n const headers = {};\n const headerNames = ['Object', 'Request', 'Session', 'Status'];\n const headerGroups = [{}, {}, {}, {}];\n const headerMap = {\n br: 0,\n d: 0,\n ot: 0,\n tb: 0,\n bl: 1,\n dl: 1,\n mtp: 1,\n nor: 1,\n nrr: 1,\n su: 1,\n cid: 2,\n pr: 2,\n sf: 2,\n sid: 2,\n st: 2,\n v: 2,\n bs: 3,\n rtp: 3,\n };\n\n for (const key of keys) {\n // Unmapped fields are mapped to the Request header\n const index = headerMap[key] != null ? headerMap[key] : 1;\n headerGroups[index][key] = data[key];\n }\n\n for (let i = 0; i < headerGroups.length; i++) {\n const value = CMCDController.serialize(headerGroups[i]);\n if (value) {\n headers[`CMCD-${headerNames[i]}`] = value;\n }\n }\n\n return headers;\n }\n\n /**\n * Convert a CMCD data object to query args according to the rules\n * defined in the section 2.2 and 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static toQuery(data: CMCD): string {\n return `CMCD=${encodeURIComponent(CMCDController.serialize(data))}`;\n }\n\n /**\n * Append query args to a uri.\n */\n static appendQueryToUri(uri, query) {\n if (!query) {\n return uri;\n }\n\n const separator = uri.includes('?') ? '&' : '?';\n return `${uri}${separator}${query}`;\n }\n}\n","/**\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';\n\nimport { logger } from '../utils/logger';\nimport type { DRMSystemOptions, EMEControllerConfig } from '../config';\nimport type { MediaKeyFunc } from '../utils/mediakeys-helper';\nimport { KeySystems } from '../utils/mediakeys-helper';\nimport type Hls from '../hls';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { MediaAttachedData, ManifestParsedData } from '../types/events';\n\nconst MAX_LICENSE_REQUEST_FAILURES = 3;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n */\n\nconst createWidevineMediaKeySystemConfigurations = function (\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n /* jshint ignore:line */\n const baseConfig: MediaKeySystemConfiguration = {\n // initDataTypes: ['keyids', 'mp4'],\n // label: \"\",\n // persistentState: \"not-allowed\", // or \"required\" ?\n // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n // sessionTypes: ['temporary'],\n audioCapabilities: [], // { contentType: 'audio/mp4; codecs=\"mp4a.40.2\"' }\n videoCapabilities: [], // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n };\n\n audioCodecs.forEach((codec) => {\n baseConfig.audioCapabilities!.push({\n contentType: `audio/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.audioRobustness || '',\n });\n });\n videoCodecs.forEach((codec) => {\n baseConfig.videoCapabilities!.push({\n contentType: `video/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.videoRobustness || '',\n });\n });\n\n return [baseConfig];\n};\n\n/**\n * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n * in order to work with the local requestMediaKeySystemAccess method.\n *\n * We can also rule-out platform-related key-system support at this point by throwing an error.\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @throws will throw an error if a unknown key system is passed\n * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects\n */\nconst getSupportedMediaKeySystemConfigurations = function (\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(\n audioCodecs,\n videoCodecs,\n drmSystemOptions\n );\n default:\n throw new Error(`Unknown key-system: ${keySystem}`);\n }\n};\n\ninterface MediaKeysListItem {\n mediaKeys?: MediaKeys;\n mediaKeysSession?: MediaKeySession;\n mediaKeysSessionInitialized: boolean;\n mediaKeySystemAccess: MediaKeySystemAccess;\n mediaKeySystemDomain: KeySystems;\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 private hls: Hls;\n private _widevineLicenseUrl?: string;\n private _licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void;\n private _licenseResponseCallback?: (\n xhr: XMLHttpRequest,\n url: string\n ) => ArrayBuffer;\n private _emeEnabled: boolean;\n private _requestMediaKeySystemAccess: MediaKeyFunc | null;\n private _drmSystemOptions: DRMSystemOptions;\n\n private _config: EMEControllerConfig;\n private _mediaKeysList: MediaKeysListItem[] = [];\n private _media: HTMLMediaElement | null = null;\n private _hasSetMediaKeys: boolean = false;\n private _requestLicenseFailureCount: number = 0;\n\n private mediaKeysPromise: Promise<MediaKeys> | null = null;\n private _onMediaEncrypted = this.onMediaEncrypted.bind(this);\n\n /**\n * @constructs\n * @param {Hls} hls Our Hls.js instance\n */\n constructor(hls: Hls) {\n this.hls = hls;\n this._config = hls.config;\n\n this._widevineLicenseUrl = this._config.widevineLicenseUrl;\n this._licenseXhrSetup = this._config.licenseXhrSetup;\n this._licenseResponseCallback = this._config.licenseResponseCallback;\n this._emeEnabled = this._config.emeEnabled;\n this._requestMediaKeySystemAccess =\n this._config.requestMediaKeySystemAccessFunc;\n this._drmSystemOptions = this._config.drmSystemOptions;\n\n this._registerListeners();\n }\n\n public destroy() {\n this._unregisterListeners();\n // @ts-ignore\n this.hls = this._onMediaEncrypted = null;\n this._requestMediaKeySystemAccess = 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_PARSED, this.onManifestParsed, 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_PARSED, this.onManifestParsed, this);\n }\n\n /**\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n * @throws if a unsupported keysystem is passed\n */\n getLicenseServerUrl(keySystem: KeySystems): string {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n if (!this._widevineLicenseUrl) {\n break;\n }\n return this._widevineLicenseUrl;\n }\n\n throw new Error(\n `no license server URL configured for key-system \"${keySystem}\"`\n );\n }\n\n /**\n * Requests access object and adds it to our list upon success\n * @private\n * @param {string} keySystem System ID (see `KeySystems`)\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @throws When a unsupported KeySystem is passed\n */\n private _attemptKeySystemAccess(\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[]\n ) {\n // This can throw, but is caught in event handler callpath\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(\n keySystem,\n audioCodecs,\n videoCodecs,\n this._drmSystemOptions\n );\n\n logger.log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n const keySystemAccessPromise = this.requestMediaKeySystemAccess(\n keySystem,\n mediaKeySystemConfigs\n );\n\n this.mediaKeysPromise = keySystemAccessPromise.then(\n (mediaKeySystemAccess) =>\n this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess)\n );\n\n keySystemAccessPromise.catch((err) => {\n logger.error(`Failed to obtain key-system \"${keySystem}\" access:`, err);\n });\n }\n\n get requestMediaKeySystemAccess() {\n if (!this._requestMediaKeySystemAccess) {\n throw new Error('No requestMediaKeySystemAccess function configured');\n }\n\n return this._requestMediaKeySystemAccess;\n }\n\n /**\n * Handles obtaining access to a key-system\n * @private\n * @param {string} keySystem\n * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n */\n private _onMediaKeySystemAccessObtained(\n keySystem: KeySystems,\n mediaKeySystemAccess: MediaKeySystemAccess\n ): Promise<MediaKeys> {\n logger.log(`Access for key-system \"${keySystem}\" obtained`);\n\n const mediaKeysListItem: MediaKeysListItem = {\n mediaKeysSessionInitialized: false,\n mediaKeySystemAccess: mediaKeySystemAccess,\n mediaKeySystemDomain: keySystem,\n };\n\n this._mediaKeysList.push(mediaKeysListItem);\n\n const mediaKeysPromise = Promise.resolve()\n .then(() => mediaKeySystemAccess.createMediaKeys())\n .then((mediaKeys) => {\n mediaKeysListItem.mediaKeys = mediaKeys;\n\n logger.log(`Media-keys created for key-system \"${keySystem}\"`);\n\n this._onMediaKeysCreated();\n\n return mediaKeys;\n });\n\n mediaKeysPromise.catch((err) => {\n logger.error('Failed to create media-keys:', err);\n });\n\n return mediaKeysPromise;\n }\n\n /**\n * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n * for all existing keys where no session exists yet.\n *\n * @private\n */\n private _onMediaKeysCreated() {\n // check for all key-list items if a session exists, otherwise, create one\n this._mediaKeysList.forEach((mediaKeysListItem) => {\n if (!mediaKeysListItem.mediaKeysSession) {\n // mediaKeys is definitely initialized here\n mediaKeysListItem.mediaKeysSession =\n mediaKeysListItem.mediaKeys!.createSession();\n this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n }\n });\n }\n\n /**\n * @private\n * @param {*} keySession\n */\n private _onNewMediaKeySession(keySession: MediaKeySession) {\n logger.log(`New key-system session ${keySession.sessionId}`);\n\n keySession.addEventListener(\n 'message',\n (event: MediaKeyMessageEvent) => {\n this._onKeySessionMessage(keySession, event.message);\n },\n false\n );\n }\n\n /**\n * @private\n * @param {MediaKeySession} keySession\n * @param {ArrayBuffer} message\n */\n private _onKeySessionMessage(\n keySession: MediaKeySession,\n message: ArrayBuffer\n ) {\n logger.log('Got EME message event, creating license request');\n\n this._requestLicense(message, (data: ArrayBuffer) => {\n logger.log(\n `Received license data (length: ${\n data ? data.byteLength : data\n }), updating key-session`\n );\n keySession.update(data).catch((err) => {\n logger.warn(`Updating key-session failed: ${err}`);\n });\n });\n }\n\n /**\n * @private\n * @param e {MediaEncryptedEvent}\n */\n private onMediaEncrypted(e: MediaEncryptedEvent) {\n logger.log(`Media is encrypted using \"${e.initDataType}\" init data type`);\n\n if (!this.mediaKeysPromise) {\n logger.error(\n 'Fatal: Media is encrypted but no CDM access or no keys have been requested'\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true,\n });\n return;\n }\n\n const finallySetKeyAndStartSession = (mediaKeys) => {\n if (!this._media) {\n return;\n }\n this._attemptSetMediaKeys(mediaKeys);\n this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);\n };\n\n // Could use `Promise.finally` but some Promise polyfills are missing it\n this.mediaKeysPromise\n .then(finallySetKeyAndStartSession)\n .catch(finallySetKeyAndStartSession);\n }\n\n /**\n * @private\n */\n private _attemptSetMediaKeys(mediaKeys?: MediaKeys) {\n if (!this._media) {\n throw new Error(\n 'Attempted to set mediaKeys without first attaching a media element'\n );\n }\n\n if (!this._hasSetMediaKeys) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem || !keysListItem.mediaKeys) {\n logger.error(\n 'Fatal: Media is encrypted but no CDM access or no keys have been obtained yet'\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true,\n });\n return;\n }\n\n logger.log('Setting keys for encrypted media');\n\n this._media.setMediaKeys(keysListItem.mediaKeys);\n this._hasSetMediaKeys = true;\n }\n }\n\n /**\n * @private\n */\n private _generateRequestWithPreferredKeySession(\n initDataType: string,\n initData: ArrayBuffer | null\n ) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error(\n 'Fatal: Media is encrypted but not any key-system access has been obtained yet'\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true,\n });\n return;\n }\n\n if (keysListItem.mediaKeysSessionInitialized) {\n logger.warn('Key-Session already initialized but requested again');\n return;\n }\n\n const keySession = keysListItem.mediaKeysSession;\n if (!keySession) {\n logger.error('Fatal: Media is encrypted but no key-session existing');\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: true,\n });\n return;\n }\n\n // initData is null if the media is not CORS-same-origin\n if (!initData) {\n logger.warn(\n 'Fatal: initData required for generating a key session is null'\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_INIT_DATA,\n fatal: true,\n });\n return;\n }\n\n logger.log(\n `Generating key-session request for \"${initDataType}\" init data type`\n );\n keysListItem.mediaKeysSessionInitialized = true;\n\n keySession\n .generateRequest(initDataType, initData)\n .then(() => {\n logger.debug('Key-session generation succeeded');\n })\n .catch((err) => {\n logger.error('Error generating key-session request:', err);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: false,\n });\n });\n }\n\n /**\n * @private\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n * @throws if XMLHttpRequest construction failed\n */\n private _createLicenseXhr(\n url: string,\n keyMessage: ArrayBuffer,\n callback: (data: ArrayBuffer) => void\n ): XMLHttpRequest {\n const xhr = new XMLHttpRequest();\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(\n this,\n xhr,\n url,\n keyMessage,\n callback\n );\n\n let licenseXhrSetup = this._licenseXhrSetup;\n if (licenseXhrSetup) {\n try {\n licenseXhrSetup.call(this.hls, xhr, url);\n licenseXhrSetup = undefined;\n } catch (e) {\n logger.error(e);\n }\n }\n try {\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 if (licenseXhrSetup) {\n licenseXhrSetup.call(this.hls, xhr, url);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n throw new Error(`issue setting up KeySystem license XHR ${e}`);\n }\n\n return xhr;\n }\n\n /**\n * @private\n * @param {XMLHttpRequest} xhr\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n */\n private _onLicenseRequestReadyStageChange(\n xhr: XMLHttpRequest,\n url: string,\n keyMessage: ArrayBuffer,\n callback: (data: ArrayBuffer) => void\n ) {\n switch (xhr.readyState) {\n case 4:\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n logger.log('License request succeeded');\n let data: ArrayBuffer = xhr.response;\n const licenseResponseCallback = this._licenseResponseCallback;\n if (licenseResponseCallback) {\n try {\n data = licenseResponseCallback.call(this.hls, xhr, url);\n } catch (e) {\n logger.error(e);\n }\n }\n callback(data);\n } else {\n logger.error(\n `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`\n );\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true,\n });\n return;\n }\n\n const attemptsLeft =\n MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n logger.warn(\n `Retrying license request, ${attemptsLeft} attempts left`\n );\n this._requestLicense(keyMessage, callback);\n }\n break;\n }\n }\n\n /**\n * @private\n * @param {MediaKeysListItem} keysListItem\n * @param {ArrayBuffer} keyMessage\n * @returns {ArrayBuffer} Challenge data posted to license server\n * @throws if KeySystem is unsupported\n */\n private _generateLicenseRequestChallenge(\n keysListItem: MediaKeysListItem,\n keyMessage: ArrayBuffer\n ): ArrayBuffer {\n switch (keysListItem.mediaKeySystemDomain) {\n // case KeySystems.PLAYREADY:\n // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n /*\n if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n } else {\n throw 'Cannot find <Challenge> in key message';\n }\n var headerNames = keyMessageXml.getElementsByTagName('name');\n var headerValues = keyMessageXml.getElementsByTagName('value');\n if (headerNames.length !== headerValues.length) {\n throw 'Mismatched header <name>/<value> pair in key message';\n }\n for (var i = 0; i < headerNames.length; i++) {\n xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n }\n }\n break;\n */\n case KeySystems.WIDEVINE:\n // For Widevine CDMs, the challenge is the keyMessage.\n return keyMessage;\n }\n\n throw new Error(\n `unsupported key-system: ${keysListItem.mediaKeySystemDomain}`\n );\n }\n\n /**\n * @private\n * @param keyMessage\n * @param callback\n */\n private _requestLicense(\n keyMessage: ArrayBuffer,\n callback: (data: ArrayBuffer) => void\n ) {\n logger.log('Requesting content license for key-system');\n\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error(\n 'Fatal error: Media is encrypted but no key-system access has been obtained yet'\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true,\n });\n return;\n }\n\n try {\n const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n const xhr = this._createLicenseXhr(url, keyMessage, callback);\n logger.log(`Sending license request to URL: ${url}`);\n const challenge = this._generateLicenseRequestChallenge(\n keysListItem,\n keyMessage\n );\n xhr.send(challenge);\n } catch (e) {\n logger.error(`Failure requesting DRM license: ${e}`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true,\n });\n }\n }\n\n onMediaAttached(event: Events.MEDIA_ATTACHED, data: MediaAttachedData) {\n if (!this._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 }\n\n onMediaDetached() {\n const media = this._media;\n const mediaKeysList = this._mediaKeysList;\n if (!media) {\n return;\n }\n media.removeEventListener('encrypted', this._onMediaEncrypted);\n this._media = null;\n this._mediaKeysList = [];\n // Close all sessions and remove media keys from the video element.\n Promise.all(\n mediaKeysList.map((mediaKeysListItem) => {\n if (mediaKeysListItem.mediaKeysSession) {\n return mediaKeysListItem.mediaKeysSession.close().catch(() => {\n // Ignore errors when closing the sessions. Closing a session that\n // generated no key requests will throw an error.\n });\n }\n })\n )\n .then(() => {\n return media.setMediaKeys(null);\n })\n .catch(() => {\n // Ignore any failures while removing media keys from the video element.\n });\n }\n\n onManifestParsed(event: Events.MANIFEST_PARSED, data: ManifestParsedData) {\n if (!this._emeEnabled) {\n return;\n }\n\n const audioCodecs = data.levels\n .map((level) => level.audioCodec)\n .filter(\n (audioCodec: string | undefined): audioCodec is string => !!audioCodec\n );\n const videoCodecs = data.levels\n .map((level) => level.videoCodec)\n .filter(\n (videoCodec: string | undefined): videoCodec is string => !!videoCodec\n );\n\n this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);\n }\n}\n\nexport default EMEController;\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);\n }\n\n destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.unregisterListeners();\n this.isVideoPlaybackQualityAvailable = false;\n this.media = null;\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const media =\n data.media instanceof self.HTMLVideoElement ? data.media : null;\n this.media = media;\n if (media && typeof media.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n self.clearInterval(this.timer);\n this.timer = self.setInterval(\n this.checkFPSInterval.bind(this),\n config.fpsDroppedMonitoringPeriod\n );\n }\n }\n\n checkFPS(\n video: HTMLVideoElement,\n decodedFrames: number,\n droppedFrames: number\n ) {\n const currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n const currentPeriod = currentTime - this.lastTime;\n const currentDropped = droppedFrames - this.lastDroppedFrames;\n const currentDecoded = decodedFrames - this.lastDecodedFrames;\n const droppedFPS = (1000 * currentDropped) / currentPeriod;\n const hls = this.hls;\n hls.trigger(Events.FPS_DROP, {\n currentDropped: currentDropped,\n currentDecoded: currentDecoded,\n totalDroppedFrames: droppedFrames,\n });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (\n currentDropped >\n hls.config.fpsDroppedMonitoringThreshold * currentDecoded\n ) {\n let currentLevel = hls.currentLevel;\n logger.warn(\n 'drop FPS ratio greater than max allowed value for currentLevel: ' +\n currentLevel\n );\n if (\n currentLevel > 0 &&\n (hls.autoLevelCapping === -1 ||\n hls.autoLevelCapping >= currentLevel)\n ) {\n currentLevel = currentLevel - 1;\n hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {\n level: currentLevel,\n droppedLevel: hls.currentLevel,\n });\n hls.autoLevelCapping = currentLevel;\n this.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval() {\n const video = this.media;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n const videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(\n video,\n videoPlaybackQuality.totalVideoFrames,\n videoPlaybackQuality.droppedVideoFrames\n );\n } else {\n // HTMLVideoElement doesn't include the webkit types\n this.checkFPS(\n video,\n (video as any).webkitDecodedFrameCount as number,\n (video as any).webkitDroppedFrameCount as number\n );\n }\n }\n }\n}\n\nexport default FPSController;\n","import BinarySearch from '../utils/binary-search';\nimport { Fragment } from '../loader/fragment';\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*|null} fragment - The best matching fragment\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 {Array} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentByPTS(\n fragPrevious: Fragment | null,\n fragments: Array<Fragment>,\n bufferEnd: number = 0,\n maxFragLookUpTolerance: number = 0\n): Fragment | null {\n let fragNext: Fragment | null = null;\n if (fragPrevious) {\n fragNext =\n fragments[\n (fragPrevious.sn as number) - (fragments[0].sn as number) + 1\n ] || null;\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (\n fragNext &&\n fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) ===\n 0\n ) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(\n fragments,\n fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance)\n );\n if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 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 {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {boolean} 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 { 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 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 activeFragment: Fragment | null = null;\n private activeParts: Part[] | null = 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\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 = this.timeRanges = null;\n }\n\n /**\n * Return a Fragment with an appended range that matches the position and levelType.\n * If not found any Fragment, return null\n */\n public getAppendedFrag(\n position: number,\n levelType: PlaylistLevelType\n ): Fragment | Part | null {\n if (levelType === PlaylistLevelType.MAIN) {\n const { activeFragment, activeParts } = this;\n if (!activeFragment) {\n return null;\n }\n if (activeParts) {\n for (let i = activeParts.length; i--; ) {\n const activePart = activeParts[i];\n const appendedPTS = activePart\n ? activePart.end\n : activeFragment.appendedPTS;\n if (\n activePart.start <= position &&\n appendedPTS !== undefined &&\n position <= appendedPTS\n ) {\n // 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.\n if (i > 9) {\n this.activeParts = activeParts.slice(i - 9);\n }\n return activePart;\n }\n }\n } else if (\n activeFragment.start <= position &&\n activeFragment.appendedPTS !== undefined &&\n position <= activeFragment.appendedPTS\n ) {\n return activeFragment;\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 ) {\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (!fragmentEntity.buffered) {\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 private 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) {\n return;\n }\n Object.keys(timeRanges).forEach((elementaryStream) => {\n const streamInfo = frag.elementaryStreams[elementaryStream];\n if (!streamInfo) {\n return;\n }\n const timeRange = timeRanges[elementaryStream];\n const partial = part !== null || 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 } else {\n // remove fragment if nothing was appended\n this.removeFragment(fragmentEntity.body);\n }\n }\n\n public fragBuffered(frag: Fragment) {\n const fragKey = getFragmentKey(frag);\n const fragmentEntity = this.fragments[fragKey];\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 = part ? part.start : fragment.start;\n const endPTS = part ? part.end : fragment.end;\n const minEndPTS = fragment.minEndPTS || endPTS;\n const maxStartPTS = fragment.maxStartPTS || startPTS;\n for (let i = 0; i < timeRange.length; i++) {\n const startTime = timeRange.start(i) - this.bufferPadding;\n const endTime = timeRange.end(i) + this.bufferPadding;\n if (maxStartPTS >= startTime && minEndPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i)),\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n buffered.partial = true;\n // Check for intersection with buffer\n // Get playable sections of the fragment\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i)),\n });\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n return buffered;\n }\n\n /**\n * Gets the partial fragment for a certain time\n */\n public getPartialFragment(time: number): Fragment | null {\n let bestFragment: Fragment | null = null;\n let timePadding: number;\n let startTime: number;\n let endTime: number;\n let bestOverlap: number = 0;\n const { bufferPadding, fragments } = this;\n Object.keys(fragments).forEach((key) => {\n const fragmentEntity = fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.start - bufferPadding;\n endTime = fragmentEntity.body.end + bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n public 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 // don't track parts for memory efficiency\n if (frag.sn === 'initSegment' || frag.bitrateTest || part) {\n return;\n }\n\n const fragKey = getFragmentKey(frag);\n this.fragments[fragKey] = {\n body: frag,\n loaded: data,\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.type === PlaylistLevelType.MAIN) {\n if (this.activeFragment !== frag) {\n this.activeFragment = frag;\n frag.appendedPTS = undefined;\n }\n if (part) {\n let activeParts = this.activeParts;\n if (!activeParts) {\n this.activeParts = activeParts = [];\n }\n activeParts.push(part);\n } else {\n this.activeParts = null;\n }\n }\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = timeRanges as { [key in SourceBufferName]: TimeRanges };\n Object.keys(timeRanges).forEach((elementaryStream: SourceBufferName) => {\n const timeRange = timeRanges[elementaryStream] as TimeRanges;\n this.detectEvictedFragments(elementaryStream, timeRange);\n if (!part && frag.type === PlaylistLevelType.MAIN) {\n const streamInfo = frag.elementaryStreams[elementaryStream];\n if (!streamInfo) {\n return;\n }\n for (let i = 0; i < timeRange.length; i++) {\n const rangeEnd = timeRange.end(i);\n if (rangeEnd <= streamInfo.endPTS && rangeEnd > streamInfo.startPTS) {\n frag.appendedPTS = Math.max(rangeEnd, frag.appendedPTS || 0);\n } else {\n frag.appendedPTS = streamInfo.endPTS;\n }\n }\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 removeFragmentsInRange(\n start: number,\n end: number,\n playlistType: PlaylistLevelType\n ) {\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (fragmentEntity.buffered) {\n const frag = fragmentEntity.body;\n if (\n frag.type === playlistType &&\n frag.start < end &&\n frag.end > start\n ) {\n this.removeFragment(frag);\n }\n }\n });\n }\n\n public removeFragment(fragment: Fragment) {\n const fragKey = getFragmentKey(fragment);\n fragment.stats.loaded = 0;\n fragment.clearElementaryStreamInfo();\n fragment.appendedPTS = undefined;\n delete this.fragments[fragKey];\n }\n\n public removeAllFragments() {\n this.fragments = Object.create(null);\n this.activeFragment = null;\n this.activeParts = null;\n }\n}\n\nfunction isPartial(fragmentEntity: FragmentEntity): boolean {\n return (\n fragmentEntity.buffered &&\n (fragmentEntity.range.video?.partial || fragmentEntity.range.audio?.partial)\n );\n}\n\nfunction getFragmentKey(fragment: Fragment): string {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n}\n","import type { BufferInfo } from '../utils/buffer-helper';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\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 {number} lastCurrentTime Previously read playhead position\n */\n public poll(lastCurrentTime: number, activeFrag: Fragment | null) {\n const { config, media, stalled } = this;\n if (media === null) {\n return;\n }\n const { currentTime, seeking } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n this.moved = true;\n if (stalled !== null) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n logger.warn(\n `playback not stuck anymore @${currentTime}, after ${Math.round(\n stalledDuration\n )}ms`\n );\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n this.stalled = null;\n }\n\n // The playhead should not be moving\n if (\n (media.paused && !seeking) ||\n media.ended ||\n media.playbackRate === 0 ||\n !BufferHelper.getBuffered(media).length\n ) {\n return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const isBuffered = bufferInfo.len > 0;\n const nextStart = bufferInfo.nextStart || 0;\n\n // There is no playable buffer (seeked, waiting for buffer)\n if (!isBuffered && !nextStart) {\n return;\n }\n\n if (seeking) {\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferGap =\n !nextStart ||\n (activeFrag && activeFrag.start <= currentTime) ||\n (nextStart - currentTime > MAX_START_GAP_JUMP &&\n !this.fragmentTracker.getPartialFragment(currentTime));\n if (hasEnoughBuffer || noBufferGap) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n if (!this.moved && this.stalled !== null) {\n // Jump start gaps within jump threshold\n const startJump =\n Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n\n // When joining a live stream with audio tracks, account for live playlist window sliding by allowing\n // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment\n // that begins over 1 target duration after the video start position.\n const level = this.hls.levels\n ? this.hls.levels[this.hls.currentLevel]\n : null;\n const isLive = level?.details?.live;\n const maxStartGapJump = isLive\n ? level!.details!.targetduration * 2\n : MAX_START_GAP_JUMP;\n if (startJump > 0 && startJump <= maxStartGapJump) {\n this._trySkipBufferHole(null);\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 don't handle a partial fragment\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 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 logger.warn(\n `Playback stalling at @${\n media.currentTime\n } due to low buffer (${JSON.stringify(bufferInfo)})`\n );\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\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 const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n const buffered = BufferHelper.getBuffered(media);\n for (let i = 0; i < buffered.length; i++) {\n const startTime = buffered.start(i);\n if (\n currentTime + config.maxBufferHole >= lastEndTime &&\n currentTime < startTime\n ) {\n const targetTime = Math.max(\n startTime + SKIP_BUFFER_RANGE_START,\n media.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) {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`,\n frag: partial,\n });\n }\n return targetTime;\n }\n lastEndTime = buffered.end(i);\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 logger.warn(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);\n media.currentTime = targetTime;\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false,\n });\n } else {\n logger.error(\n `Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`\n );\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true,\n });\n }\n }\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 { DateRange, DateRangeAttribute } 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\ntype Cue = VTTCue | TextTrackCue;\n\nconst MIN_CUE_DURATION = 0.25;\n\nfunction getCueClass() {\n // Attempt to recreate Safari functionality by creating\n // WebKitDataCue objects when available and store the decoded\n // ID3 data in the value property of the cue\n return (self.WebKitDataCue || self.VTTCue || self.TextTrackCue) as any;\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 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 { cues: Record<string, Cue>; dateRange: DateRange; durationKnown: boolean }\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 { frag: fragment, samples, details } = data;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const Cue = getCueClass();\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);\n\n const cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n if (type) {\n cue.type = type;\n }\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n\n updateId3CueEnds(startTime: number) {\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 (cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {\n cue.endTime = startTime;\n }\n }\n }\n }\n\n onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { startOffset, endOffset, type }: BufferFlushingData\n ) {\n const { id3Track, hls } = this;\n if (!hls) {\n return;\n }\n\n const {\n config: { enableEmsgMetadataCues, enableID3MetadataCues },\n } = hls;\n if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {\n let predicate;\n\n if (type === 'audio') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues;\n } else if (type === 'video') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues;\n } else {\n predicate = (cue) =>\n ((cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues) ||\n ((cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues);\n }\n removeCuesInRange(id3Track, startOffset, endOffset, predicate);\n }\n }\n\n onLevelUpdated(event: Events.LEVEL_UPDATED, { details }: LevelUpdatedData) {\n if (\n !this.media ||\n !details.hasProgramDateTime ||\n !this.hls.config.enableDateRangeMetadataCues\n ) {\n return;\n }\n const { dateRangeCuesAppended, id3Track } = this;\n const { dateRanges } = details;\n const ids = Object.keys(dateRanges);\n // Remove cues from track not found in details.dateRanges\n if (id3Track) {\n const idsToRemove = Object.keys(dateRangeCuesAppended).filter(\n (id) => !ids.includes(id)\n );\n for (let i = idsToRemove.length; i--; ) {\n const id = idsToRemove[i];\n Object.keys(dateRangeCuesAppended[id].cues).forEach((key) => {\n id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);\n });\n delete dateRangeCuesAppended[id];\n }\n }\n // Exit if the playlist does not have Date Ranges or does not have Program Date Time\n const lastFragment = details.fragments[details.fragments.length - 1];\n if (ids.length === 0 || !Number.isFinite(lastFragment?.programDateTime)) {\n return;\n }\n\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const dateTimeOffset =\n (lastFragment.programDateTime as number) / 1000 - lastFragment.start;\n const Cue = getCueClass();\n\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i];\n const dateRange = dateRanges[id];\n const appendedDateRangeCues = dateRangeCuesAppended[id];\n const cues = appendedDateRangeCues?.cues || {};\n let durationKnown = appendedDateRangeCues?.durationKnown || false;\n const startTime = dateRangeDateToTimelineSeconds(\n dateRange.startDate,\n dateTimeOffset\n );\n let endTime = MAX_CUE_ENDTIME;\n const endDate = dateRange.endDate;\n if (endDate) {\n endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);\n durationKnown = true;\n } else if (dateRange.endOnNext && !durationKnown) {\n const nextDateRangeWithSameClass = ids\n .reduce((filterMapArray, id) => {\n const candidate = dateRanges[id];\n if (\n candidate.class === dateRange.class &&\n candidate.id !== id &&\n candidate.startDate > dateRange.startDate\n ) {\n filterMapArray.push(candidate);\n }\n return filterMapArray;\n }, [] as DateRange[])\n .sort((a, b) => a.startDate.getTime() - b.startDate.getTime())[0];\n if (nextDateRangeWithSameClass) {\n endTime = dateRangeDateToTimelineSeconds(\n nextDateRangeWithSameClass.startDate,\n dateTimeOffset\n );\n durationKnown = true;\n }\n }\n\n const attributes = Object.keys(dateRange.attr);\n for (let j = 0; j < attributes.length; j++) {\n const key = attributes[j];\n if (\n key === DateRangeAttribute.ID ||\n key === DateRangeAttribute.CLASS ||\n key === DateRangeAttribute.START_DATE ||\n key === DateRangeAttribute.DURATION ||\n key === DateRangeAttribute.END_DATE ||\n key === DateRangeAttribute.END_ON_NEXT\n ) {\n continue;\n }\n let cue = cues[key] as any;\n if (cue) {\n if (durationKnown && !appendedDateRangeCues.durationKnown) {\n cue.endTime = endTime;\n }\n } else {\n let data = dateRange.attr[key];\n cue = new Cue(startTime, endTime, '');\n if (\n key === DateRangeAttribute.SCTE35_OUT ||\n key === DateRangeAttribute.SCTE35_IN\n ) {\n data = hexToArrayBuffer(data);\n }\n cue.value = { key, data };\n cue.type = MetadataSchema.dateRange;\n this.id3Track.addCue(cue);\n cues[key] = cue;\n }\n }\n dateRangeCuesAppended[id] = {\n cues,\n dateRange,\n durationKnown,\n };\n }\n }\n}\n\nexport default ID3TrackController;\n","import { LevelDetails } from '../loader/level-details';\nimport { ErrorDetails } from '../errors';\nimport { Events } from '../events';\nimport type {\n ErrorData,\n LevelUpdatedData,\n MediaAttachingData,\n} from '../types/events';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\n\nexport default class LatencyController implements ComponentAPI {\n private hls: Hls;\n private readonly config: HlsConfig;\n private media: HTMLMediaElement | null = null;\n private levelDetails: LevelDetails | null = null;\n private currentTime: number = 0;\n private stallCount: number = 0;\n private _latency: number | null = null;\n private timeupdateHandler = () => this.timeupdate();\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n\n get latency(): number {\n return this._latency || 0;\n }\n\n get maxLatency(): number {\n const { config, levelDetails } = this;\n if (config.liveMaxLatencyDuration !== undefined) {\n return config.liveMaxLatencyDuration;\n }\n return levelDetails\n ? config.liveMaxLatencyDurationCount * levelDetails.targetduration\n : 0;\n }\n\n get targetLatency(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n const { holdBack, partHoldBack, targetduration } = levelDetails;\n const { liveSyncDuration, liveSyncDurationCount, lowLatencyMode } =\n this.config;\n const userConfig = this.hls.userConfig;\n let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;\n if (\n userConfig.liveSyncDuration ||\n userConfig.liveSyncDurationCount ||\n targetLatency === 0\n ) {\n targetLatency =\n liveSyncDuration !== undefined\n ? liveSyncDuration\n : liveSyncDurationCount * targetduration;\n }\n const maxLiveSyncOnStallIncrease = targetduration;\n const liveSyncOnStallIncrease = 1.0;\n return (\n targetLatency +\n Math.min(\n this.stallCount * liveSyncOnStallIncrease,\n maxLiveSyncOnStallIncrease\n )\n );\n }\n\n get liveSyncPosition(): number | null {\n const liveEdge = this.estimateLiveEdge();\n const targetLatency = this.targetLatency;\n const levelDetails = this.levelDetails;\n if (liveEdge === null || targetLatency === null || levelDetails === null) {\n return null;\n }\n const edge = levelDetails.edge;\n const syncPosition = liveEdge - targetLatency - this.edgeStalled;\n const min = edge - levelDetails.totalduration;\n const max =\n edge -\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration);\n return Math.min(Math.max(min, syncPosition), max);\n }\n\n get drift(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 1;\n }\n return levelDetails.drift;\n }\n\n get edgeStalled(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 0;\n }\n const maxLevelUpdateAge =\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration) * 3;\n return Math.max(levelDetails.age - maxLevelUpdateAge, 0);\n }\n\n private get forwardBufferLength(): number {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return 0;\n }\n const bufferedRanges = media.buffered.length;\n return (\n (bufferedRanges\n ? media.buffered.end(bufferedRanges - 1)\n : levelDetails.edge) - this.currentTime\n );\n }\n\n public destroy(): void {\n this.unregisterListeners();\n this.onMediaDetaching();\n this.levelDetails = null;\n // @ts-ignore\n this.hls = this.timeupdateHandler = null;\n }\n\n private registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n this.hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached);\n this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching);\n this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading);\n this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated);\n this.hls.off(Events.ERROR, this.onError);\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 logger.warn(\n '[playback-rate-controller]: Stall detected, adjusting target latency'\n );\n }\n\n private timeupdate() {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return;\n }\n this.currentTime = media.currentTime;\n\n const latency = this.computeLatency();\n if (latency === null) {\n return;\n }\n this._latency = latency;\n\n // Adapt playbackRate to meet target latency in low-latency mode\n const { lowLatencyMode, maxLiveSyncPlaybackRate } = this.config;\n if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {\n return;\n }\n const targetLatency = this.targetLatency;\n if (targetLatency === null) {\n return;\n }\n const distanceFromTarget = latency - targetLatency;\n // Only adjust playbackRate when within one target duration of targetLatency\n // and more than one second from under-buffering.\n // Playback further than one target duration from target can be considered DVR playback.\n const liveMinLatencyDuration = Math.min(\n this.maxLatency,\n targetLatency + levelDetails.targetduration\n );\n const inLiveRange = distanceFromTarget < liveMinLatencyDuration;\n if (\n levelDetails.live &&\n inLiveRange &&\n distanceFromTarget > 0.05 &&\n this.forwardBufferLength > 1\n ) {\n const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));\n const rate =\n Math.round(\n (2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled))) *\n 20\n ) / 20;\n media.playbackRate = Math.min(max, Math.max(1, rate));\n } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {\n media.playbackRate = 1;\n }\n }\n\n private estimateLiveEdge(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n return levelDetails.edge + levelDetails.age;\n }\n\n private computeLatency(): number | null {\n const liveEdge = this.estimateLiveEdge();\n if (liveEdge === null) {\n return null;\n }\n return liveEdge - this.currentTime;\n }\n}\n","/*\n * Level Controller\n */\n\nimport {\n ManifestLoadedData,\n ManifestParsedData,\n LevelLoadedData,\n TrackSwitchedData,\n FragLoadedData,\n ErrorData,\n LevelSwitchingData,\n} from '../types/events';\nimport { Level } from '../types/level';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { isCodecSupportedInMp4 } from '../utils/codecs';\nimport { addGroupId, assignTrackIdsByGroup } from './level-helper';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters, LevelParsed } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nconst chromeOrFirefox: boolean = /chrome|firefox/.test(\n navigator.userAgent.toLowerCase()\n);\n\nexport default class LevelController extends BasePlaylistController {\n private _levels: Level[] = [];\n private _firstLevel: number = -1;\n private _startLevel?: number;\n private currentLevelIndex: number = -1;\n private manualLevelIndex: number = -1;\n\n public onParsedComplete!: Function;\n\n constructor(hls: Hls) {\n super(hls, '[level-controller]');\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this._unregisterListeners();\n this.manualLevelIndex = -1;\n this._levels.length = 0;\n super.destroy();\n }\n\n public startLoad(): void {\n const levels = this._levels;\n\n // clean up live level details to force reload them, and reset load errors\n levels.forEach((level) => {\n level.loadError = 0;\n });\n\n super.startLoad();\n }\n\n protected onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ): void {\n let levels: Level[] = [];\n let audioTracks: MediaPlaylist[] = [];\n let subtitleTracks: MediaPlaylist[] = [];\n let bitrateStart: number | undefined;\n const levelSet: { [key: string]: Level } = {};\n let levelFromSet: Level;\n let resolutionFound = false;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n // regroup redundant levels together\n data.levels.forEach((levelParsed: LevelParsed) => {\n const attributes = levelParsed.attrs;\n\n resolutionFound =\n resolutionFound || !!(levelParsed.width && levelParsed.height);\n videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;\n audioCodecFound = audioCodecFound || !!levelParsed.audioCodec;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n if (\n chromeOrFirefox &&\n levelParsed.audioCodec &&\n levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1\n ) {\n levelParsed.audioCodec = undefined;\n }\n\n const levelKey = `${levelParsed.bitrate}-${levelParsed.attrs.RESOLUTION}-${levelParsed.attrs.CODECS}`;\n levelFromSet = levelSet[levelKey];\n\n if (!levelFromSet) {\n levelFromSet = new Level(levelParsed);\n levelSet[levelKey] = levelFromSet;\n levels.push(levelFromSet);\n } else {\n levelFromSet.url.push(levelParsed.url);\n }\n\n if (attributes) {\n if (attributes.AUDIO) {\n addGroupId(levelFromSet, 'audio', attributes.AUDIO);\n }\n if (attributes.SUBTITLES) {\n addGroupId(levelFromSet, 'text', attributes.SUBTITLES);\n }\n }\n });\n\n // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled\n if ((resolutionFound || videoCodecFound) && audioCodecFound) {\n levels = levels.filter(\n ({ videoCodec, width, height }) => !!videoCodec || !!(width && height)\n );\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(({ audioCodec, videoCodec }) => {\n return (\n (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) &&\n (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'))\n );\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(\n (track) =>\n !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio')\n );\n // Assign ids after filtering as array indices by group-id\n assignTrackIdsByGroup(audioTracks);\n }\n\n if (data.subtitles) {\n subtitleTracks = data.subtitles;\n assignTrackIdsByGroup(subtitleTracks);\n }\n\n if (levels.length > 0) {\n // start bitrate is the first bitrate of the manifest\n bitrateStart = levels[0].bitrate;\n // sort level on bitrate\n levels.sort((a, b) => a.bitrate - b.bitrate);\n this._levels = levels;\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n this.log(\n `manifest loaded, ${levels.length} level(s) found, first bitrate: ${bitrateStart}`\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 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 } else {\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 reason: 'no level with compatible codecs found in manifest',\n });\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 if (this.currentLevelIndex === newLevel && levels[newLevel]?.details) {\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 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 reason: 'invalid level idx',\n });\n if (fatal) {\n return;\n }\n newLevel = Math.min(newLevel, levels.length - 1);\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n const lastLevelIndex = this.currentLevelIndex;\n const lastLevel = levels[lastLevelIndex];\n const level = levels[newLevel];\n this.log(`switching to level ${newLevel} from ${lastLevelIndex}`);\n this.currentLevelIndex = newLevel;\n\n const levelSwitchingData: LevelSwitchingData = Object.assign({}, level, {\n level: newLevel,\n maxBitrate: level.maxBitrate,\n uri: level.uri,\n urlId: level.urlId,\n });\n // @ts-ignore\n delete levelSwitchingData._urlId;\n this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);\n // check if we need to load playlist for this level\n const levelDetails = level.details;\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n const hlsUrlParameters = this.switchParams(level.uri, lastLevel?.details);\n this.loadPlaylist(hlsUrlParameters);\n }\n }\n\n get manualLevel(): number {\n return this.manualLevelIndex;\n }\n\n set manualLevel(newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel(): number {\n return this._firstLevel;\n }\n\n set firstLevel(newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel() {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n const configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel(newLevel) {\n this._startLevel = newLevel;\n }\n\n protected onError(event: Events.ERROR, data: ErrorData) {\n super.onError(event, data);\n if (data.fatal) {\n return;\n }\n\n // Switch to redundant level when track fails to load\n const context = data.context;\n const level = this._levels[this.currentLevelIndex];\n if (\n context &&\n ((context.type === PlaylistContextType.AUDIO_TRACK &&\n level.audioGroupIds &&\n context.groupId === level.audioGroupIds[level.urlId]) ||\n (context.type === PlaylistContextType.SUBTITLE_TRACK &&\n level.textGroupIds &&\n context.groupId === level.textGroupIds[level.urlId]))\n ) {\n this.redundantFailover(this.currentLevelIndex);\n return;\n }\n\n let levelError = false;\n let levelSwitch = true;\n let levelIndex;\n\n // try to recover not fatal errors\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 if (data.frag) {\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 =\n data.frag.type === PlaylistLevelType.MAIN\n ? data.frag.level\n : this.currentLevelIndex;\n const level = this._levels[variantLevelIndex];\n // Set levelIndex when we're out of fragment retries\n if (level) {\n level.fragmentError++;\n if (level.fragmentError > this.hls.config.fragLoadingMaxRetry) {\n levelIndex = variantLevelIndex;\n }\n } else {\n levelIndex = variantLevelIndex;\n }\n }\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n // Do not perform level switch if an error occurred using delivery directives\n // Attempt to reload level without directives first\n if (context) {\n if (context.deliveryDirectives) {\n levelSwitch = false;\n }\n levelIndex = context.level;\n }\n levelError = true;\n break;\n case ErrorDetails.REMUX_ALLOC_ERROR:\n levelIndex = data.level ?? this.currentLevelIndex;\n levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, levelSwitch);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n */\n private recoverLevel(\n errorEvent: ErrorData,\n levelIndex: number,\n levelError: boolean,\n levelSwitch: boolean\n ): void {\n const { details: errorDetails } = errorEvent;\n const level = this._levels[levelIndex];\n\n level.loadError++;\n\n if (levelError) {\n const retrying = this.retryLoadingOrFail(errorEvent);\n if (retrying) {\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n } else {\n this.currentLevelIndex = -1;\n return;\n }\n }\n\n if (levelSwitch) {\n const redundantLevels = level.url.length;\n // Try redundant fail-over until level.loadError reaches redundantLevels\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n errorEvent.levelRetry = true;\n this.redundantFailover(levelIndex);\n } else if (this.manualLevelIndex === -1) {\n // Search for next level to retry\n let nextLevel = -1;\n const levels = this._levels;\n for (let i = levels.length; i--; ) {\n const candidate = (i + this.currentLevelIndex) % levels.length;\n if (\n candidate !== this.currentLevelIndex &&\n levels[candidate].loadError === 0\n ) {\n nextLevel = candidate;\n break;\n }\n }\n if (nextLevel > -1 && this.currentLevelIndex !== nextLevel) {\n this.warn(`${errorDetails}: switch to ${nextLevel}`);\n errorEvent.levelRetry = true;\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n }\n }\n\n private redundantFailover(levelIndex: number) {\n const level = this._levels[levelIndex];\n const redundantLevels = level.url.length;\n if (redundantLevels > 1) {\n // Update the url id of all levels so that we stay on the same set of variants when level switching\n const newUrlId = (level.urlId + 1) % redundantLevels;\n this.warn(`Switching to redundant URL-id ${newUrlId}`);\n this._levels.forEach((level) => {\n level.urlId = newUrlId;\n });\n this.level = levelIndex;\n }\n }\n\n // reset errors on the successful load of a fragment\n protected onFragLoaded(event: Events.FRAG_LOADED, { frag }: FragLoadedData) {\n if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {\n const level = this._levels[frag.level];\n if (level !== undefined) {\n level.fragmentError = 0;\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 this.retryCount = 0;\n }\n this.playlistLoaded(level, data, curLevel.details);\n } else if (data.deliveryDirectives?.skip) {\n // received a delta playlist update that cannot be merged\n details.deltaUpdateFailed = true;\n }\n }\n\n protected onAudioTrackSwitched(\n event: Events.AUDIO_TRACK_SWITCHED,\n data: TrackSwitchedData\n ) {\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n let urlId = -1;\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n for (let i = 0; i < currentLevel.audioGroupIds.length; i++) {\n if (currentLevel.audioGroupIds[i] === audioGroupId) {\n urlId = i;\n break;\n }\n }\n\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters) {\n super.loadPlaylist();\n const level = this.currentLevelIndex;\n const currentLevel = this._levels[level];\n\n if (this.canLoad && currentLevel && currentLevel.url.length > 0) {\n const id = currentLevel.urlId;\n let url = currentLevel.url[id];\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 this.log(\n `Attempt loading level index ${level}${\n hlsUrlParameters\n ? ' at sn ' +\n hlsUrlParameters.msn +\n ' part ' +\n hlsUrlParameters.part\n : ''\n } with URL-id ${id} ${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,\n id,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n\n get nextLoadLevel() {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n\n removeLevel(levelIndex, urlId) {\n const filterLevelAndGroupByIdIndex = (url, id) => id !== urlId;\n const levels = this._levels\n .filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n\n if (level.url.length > 1 && urlId !== undefined) {\n level.url = level.url.filter(filterLevelAndGroupByIdIndex);\n if (level.audioGroupIds) {\n level.audioGroupIds = level.audioGroupIds.filter(\n filterLevelAndGroupByIdIndex\n );\n }\n if (level.textGroupIds) {\n level.textGroupIds = level.textGroupIds.filter(\n filterLevelAndGroupByIdIndex\n );\n }\n level.urlId = 0;\n return true;\n }\n return false;\n })\n .map((level, index) => {\n const { details } = level;\n if (details?.fragments) {\n details.fragments.forEach((fragment) => {\n fragment.level = index;\n });\n }\n return level;\n });\n this._levels = levels;\n\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n }\n}\n","/**\n * @module LevelHelper\n * Providing methods dealing with playlist sliding and drift\n * */\n\nimport { logger } from '../utils/logger';\nimport { Fragment, Part } from '../loader/fragment';\nimport { LevelDetails } from '../loader/level-details';\nimport type { Level } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport { DateRange } from '../loader/date-range';\n\ntype FragmentIntersection = (oldFrag: Fragment, newFrag: Fragment) => void;\ntype PartIntersection = (oldPart: Part, newPart: Part) => void;\n\nexport function addGroupId(level: Level, type: string, id: string): void {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function 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\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 // TODO? Drift can go either way, or the playlist could be completely accurate\n // console.assert(duration > 0,\n // `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);\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 frag.duration = endPTS - startPTS;\n\n const drift = startPTS - frag.start;\n frag.start = 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.appendedPTS = oldFrag.appendedPTS;\n newFrag.maxStartPTS = oldFrag.maxStartPTS;\n\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.endDTS = oldFrag.endDTS;\n newFrag.minEndPTS = oldFrag.minEndPTS;\n newFrag.duration =\n (oldFrag.endPTS as number) - (oldFrag.startPTS as number);\n\n if (newFrag.duration) {\n PTSFrag = newFrag;\n }\n\n // PTS is known when any segment has startPTS and endPTS\n newDetails.PTSKnown = newDetails.alignedSliding = true;\n }\n newFrag.elementaryStreams = oldFrag.elementaryStreams;\n newFrag.loader = oldFrag.loader;\n newFrag.stats = oldFrag.stats;\n newFrag.urlId = oldFrag.urlId;\n if (oldFrag.initSegment) {\n newFrag.initSegment = oldFrag.initSegment;\n currentInitSegment = oldFrag.initSegment;\n }\n }\n );\n\n if (currentInitSegment) {\n const fragmentsToCheck = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n fragmentsToCheck.forEach((frag) => {\n if (\n !frag.initSegment ||\n frag.initSegment.relurl === currentInitSegment?.relurl\n ) {\n frag.initSegment = currentInitSegment;\n }\n });\n }\n\n if (newDetails.skippedSegments) {\n newDetails.deltaUpdateFailed = newDetails.fragments.some((frag) => !frag);\n if (newDetails.deltaUpdateFailed) {\n logger.warn(\n '[level-helper] Previous playlist missing segments skipped in delta playlist'\n );\n for (let i = newDetails.skippedSegments; i--; ) {\n newDetails.fragments.shift();\n }\n newDetails.startSN = newDetails.fragments[0].sn as number;\n newDetails.startCC = newDetails.fragments[0].cc;\n } else if (newDetails.canSkipDateRanges) {\n newDetails.dateRanges = mergeDateRanges(\n oldDetails.dateRanges,\n newDetails.dateRanges,\n newDetails.recentlyRemovedDateranges\n );\n }\n }\n\n const newFragments = newDetails.fragments;\n if (ccOffset) {\n logger.warn('discontinuity sliding from playlist, take drift into account');\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n if (newDetails.skippedSegments) {\n newDetails.startCC = newDetails.fragments[0].cc;\n }\n\n // Merge parts\n mapPartIntersection(\n oldDetails.partList,\n newDetails.partList,\n (oldPart: Part, newPart: Part) => {\n newPart.elementaryStreams = oldPart.elementaryStreams;\n newPart.stats = oldPart.stats;\n }\n );\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(\n newDetails,\n PTSFrag,\n PTSFrag.startPTS,\n PTSFrag.endPTS,\n PTSFrag.startDTS,\n PTSFrag.endDTS\n );\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n\n if (newFragments.length) {\n newDetails.totalduration = newDetails.edge - newFragments[0].start;\n }\n\n newDetails.driftStartTime = oldDetails.driftStartTime;\n newDetails.driftStart = oldDetails.driftStart;\n const advancedDateTime = newDetails.advancedDateTime;\n if (newDetails.advanced && advancedDateTime) {\n const edge = newDetails.edge;\n if (!newDetails.driftStart) {\n newDetails.driftStartTime = advancedDateTime;\n newDetails.driftStart = edge;\n }\n newDetails.driftEndTime = advancedDateTime;\n newDetails.driftEnd = edge;\n } else {\n newDetails.driftEndTime = oldDetails.driftEndTime;\n newDetails.driftEnd = oldDetails.driftEnd;\n newDetails.advancedDateTime = oldDetails.advancedDateTime;\n }\n}\n\nfunction mergeDateRanges(\n oldDateRanges: Record<string, DateRange>,\n deltaDateRanges: Record<string, DateRange>,\n recentlyRemovedDateranges: string[] | undefined\n): Record<string, DateRange> {\n const dateRanges = Object.assign({}, oldDateRanges);\n if (recentlyRemovedDateranges) {\n recentlyRemovedDateranges.forEach((id) => {\n delete dateRanges[id];\n });\n }\n Object.keys(deltaDateRanges).forEach((id) => {\n const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);\n if (dateRange.isValid) {\n dateRanges[id] = dateRange;\n } else {\n logger.warn(\n `Ignoring invalid Playlist Delta Update DATERANGE tag: \"${JSON.stringify(\n deltaDateRanges[id].attr\n )}\"`\n );\n }\n });\n return dateRanges;\n}\n\nexport function mapPartIntersection(\n oldParts: Part[] | null,\n newParts: Part[] | null,\n intersectionFn: PartIntersection\n) {\n if (oldParts && newParts) {\n let delta = 0;\n for (let i = 0, len = oldParts.length; i <= len; i++) {\n const oldPart = oldParts[i];\n const newPart = newParts[i + delta];\n if (\n oldPart &&\n newPart &&\n oldPart.index === newPart.index &&\n oldPart.fragment.sn === newPart.fragment.sn\n ) {\n intersectionFn(oldPart, newPart);\n } else {\n delta--;\n }\n }\n }\n}\n\nexport function mapFragmentIntersection(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n intersectionFn: FragmentIntersection\n): void {\n const skippedSegments = newDetails.skippedSegments;\n const start =\n Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;\n const end =\n (oldDetails.fragmentHint ? 1 : 0) +\n (skippedSegments\n ? newDetails.endSN\n : Math.min(oldDetails.endSN, newDetails.endSN)) -\n newDetails.startSN;\n const delta = newDetails.startSN - oldDetails.startSN;\n const newFrags = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n const oldFrags = oldDetails.fragmentHint\n ? oldDetails.fragments.concat(oldDetails.fragmentHint)\n : oldDetails.fragments;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldFrags[delta + i];\n let newFrag = newFrags[i];\n if (skippedSegments && !newFrag && i < skippedSegments) {\n // Fill in skipped segments in delta playlist\n newFrag = newDetails.fragments[i] = oldFrag;\n }\n if (oldFrag && newFrag) {\n intersectionFn(oldFrag, newFrag);\n }\n }\n}\n\nexport function adjustSliding(\n oldDetails: LevelDetails,\n newDetails: LevelDetails\n): void {\n const delta =\n newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;\n const oldFragments = oldDetails.fragments;\n if (delta < 0 || delta >= oldFragments.length) {\n return;\n }\n addSliding(newDetails, oldFragments[delta].start);\n}\n\nexport function addSliding(details: LevelDetails, start: number) {\n if (start) {\n const fragments = details.fragments;\n for (let i = details.skippedSegments; i < fragments.length; i++) {\n fragments[i].start += start;\n }\n if (details.fragmentHint) {\n details.fragmentHint.start += start;\n }\n }\n}\n\nexport function computeReloadInterval(\n newDetails: LevelDetails,\n distanceToLiveEdgeMs: number = Infinity\n): number {\n let reloadInterval = 1000 * newDetails.targetduration;\n\n if (newDetails.updated) {\n // Use last segment duration when shorter than target duration and near live edge\n const fragments = newDetails.fragments;\n const liveEdgeMaxTargetDurations = 4;\n if (\n fragments.length &&\n reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs\n ) {\n const lastSegmentDuration =\n fragments[fragments.length - 1].duration * 1000;\n if (lastSegmentDuration < reloadInterval) {\n reloadInterval = lastSegmentDuration;\n }\n }\n } else {\n // estimate = 'miss half average';\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval /= 2;\n }\n\n return Math.round(reloadInterval);\n}\n\nexport function getFragmentWithSN(\n level: Level,\n sn: number,\n fragCurrent: Fragment | null\n): Fragment | null {\n if (!level || !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 || !level.details) {\n return null;\n }\n const partList = level.details.partList;\n if (partList) {\n for (let i = partList.length; i--; ) {\n const part = partList[i];\n if (part.index === partIndex && part.fragment.sn === sn) {\n return part;\n }\n }\n }\n return null;\n}\n","import BaseStreamController, { State } from './base-stream-controller';\nimport { changeTypeSupported } from '../is-supported';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport { Events } from '../events';\nimport { BufferHelper, BufferInfo } from '../utils/buffer-helper';\nimport type { FragmentTracker } from './fragment-tracker';\nimport { FragmentState } from './fragment-tracker';\nimport type { Level } from '../types/level';\nimport { PlaylistLevelType } from '../types/loader';\nimport { ElementaryStreamTypes, Fragment } from '../loader/fragment';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport type { TransmuxerResult } from '../types/transmuxer';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport GapController from './gap-controller';\nimport { ErrorDetails } from '../errors';\nimport type Hls from '../hls';\nimport type { LevelDetails } from '../loader/level-details';\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(hls: Hls, fragmentTracker: FragmentTracker) {\n super(hls, fragmentTracker, '[stream-controller]');\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this\n );\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this\n );\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.onMediaDetaching();\n }\n\n public startLoad(startPosition: number): void {\n if (this.levels) {\n const { lastCurrentTime, hls } = this;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n if (hls.config.testBandwidth && this.levels.length > 1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n } else {\n startLevel = hls.nextAutoLevel;\n }\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(\n `Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(\n 3\n )}`\n );\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n this.tick();\n } else {\n this._forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n public stopLoad() {\n this._forceStartLoad = false;\n super.stopLoad();\n }\n\n protected doTick() {\n switch (this.state) {\n case State.IDLE:\n this.doTickIdle();\n break;\n case State.WAITING_LEVEL: {\n const { levels, level } = this;\n const details = levels?.[level]?.details;\n if (details && (!details.live || this.levelLastLoaded === this.level)) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.IDLE;\n break;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY:\n {\n const now = self.performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || this.media?.seeking) {\n this.log('retryDate reached, switch back to IDLE state');\n this.resetStartWhenNotLoaded(this.level);\n this.state = State.IDLE;\n }\n }\n break;\n default:\n break;\n }\n // check buffer\n // check/update current fragment\n this.onTickEnd();\n }\n\n protected onTickEnd() {\n super.onTickEnd();\n this.checkBuffer();\n this.checkFragmentChanged();\n }\n\n private doTickIdle() {\n const { hls, levelLastLoaded, levels, media } = this;\n const { config, nextLoadLevel: level } = hls;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch not enabled\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (\n levelLastLoaded === null ||\n (!media && (this.startFragRequested || !config.startFragPrefetch))\n ) {\n return;\n }\n\n // If the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n return;\n }\n\n if (!levels || !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 // set next load level : this will trigger a playlist load if needed\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (\n !levelDetails ||\n this.state === State.WAITING_LEVEL ||\n (levelDetails.live && this.levelLastLoaded !== level)\n ) {\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null) {\n return;\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 (this._streamEnded(bufferInfo, levelDetails)) {\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 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\n if (\n frag &&\n this.fragmentTracker.getState(frag) === FragmentState.OK &&\n this.nextLoadPosition > targetBufferTime\n ) {\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 if (media) {\n this.afterBufferFlushed(media, type, PlaylistLevelType.MAIN);\n }\n frag = this.getNextFragment(this.nextLoadPosition, levelDetails);\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, levelDetails, targetBufferTime);\n }\n\n protected loadFragment(\n frag: Fragment,\n levelDetails: LevelDetails,\n targetBufferTime: number\n ) {\n // Check if fragment is not loaded\n const fragState = this.fragmentTracker.getState(frag);\n this.fragCurrent = frag;\n if (fragState === FragmentState.NOT_LOADED) {\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, levelDetails);\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, levelDetails);\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, levelDetails, targetBufferTime);\n }\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this.reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\n } else if (this.media?.buffered.length === 0) {\n // Stop gap for bad tracker / buffer flush behavior\n this.fragmentTracker.removeAllFragments();\n }\n }\n\n private getAppendedFrag(position): 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 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 if (!media.paused && levels) {\n // add a safety delay of 1s\n const nextLevelId = this.hls.nextLoadLevel;\n const nextLevel = levels[nextLevelId];\n const fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay =\n (this.fragCurrent.duration * nextLevel.maxBitrate) /\n (1000 * fragLastKbps) +\n 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // this.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n this.abortCurrentFrag();\n // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.\n const maxStart = nextBufferedFrag.maxStartPTS\n ? nextBufferedFrag.maxStartPTS\n : nextBufferedFrag.start;\n const fragDuration = nextBufferedFrag.duration;\n const startPts = Math.max(\n bufferedFrag.end,\n maxStart +\n Math.min(\n Math.max(\n fragDuration - this.config.maxFragLookUpTolerance,\n fragDuration * 0.5\n ),\n fragDuration * 0.75\n )\n );\n this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n private abortCurrentFrag() {\n const fragCurrent = this.fragCurrent;\n this.fragCurrent = null;\n this.backtrackFragment = null;\n if (fragCurrent) {\n fragCurrent.abortRequests();\n }\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 // tick to speed up FRAG_CHANGED triggering\n this.tick();\n }\n\n private onManifestLoading() {\n // reset buffer on manifest loading\n this.log('Trigger BUFFER_RESET');\n this.hls.trigger(Events.BUFFER_RESET, undefined);\n this.fragmentTracker.removeAllFragments();\n this.couldBacktrack = false;\n this.startPosition = this.lastCurrentTime = 0;\n this.fragPlaying = null;\n this.backtrackFragment = null;\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) {\n let aac = false;\n let heaac = false;\n let codec;\n data.levels.forEach((level) => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = aac && heaac && !changeTypeSupported();\n if (this.audioCodecSwitch) {\n this.log(\n 'Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'\n );\n }\n\n this.levels = data.levels;\n this.startFragRequested = false;\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { levels } = this;\n if (!levels || this.state !== State.IDLE) {\n return;\n }\n const level = levels[data.level];\n if (\n !level.details ||\n (level.details.live && this.levelLastLoaded !== data.level) ||\n this.waitForCdnTuneIn(level.details)\n ) {\n this.state = State.WAITING_LEVEL;\n }\n }\n\n private onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const { levels } = this;\n const newLevelId = data.level;\n const newDetails = data.details;\n const duration = newDetails.totalduration;\n\n if (!levels) {\n this.warn(`Levels were reset while loading level ${newLevelId}`);\n return;\n }\n this.log(\n `Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}], cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`\n );\n\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.state = State.IDLE;\n this.backtrackFragment = null;\n fragCurrent.abortRequests();\n }\n }\n\n const curLevel = levels[newLevelId];\n let sliding = 0;\n if (newDetails.live || curLevel.details?.live) {\n if (!newDetails.fragments[0]) {\n newDetails.deltaUpdateFailed = true;\n }\n if (newDetails.deltaUpdateFailed) {\n return;\n }\n sliding = this.alignPlaylists(newDetails, curLevel.details);\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = newLevelId;\n\n this.hls.trigger(Events.LEVEL_UPDATED, {\n details: newDetails,\n level: newLevelId,\n });\n\n // only switch back to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n if (this.waitForCdnTuneIn(newDetails)) {\n // Wait for Low-Latency CDN Tune-in\n return;\n }\n this.state = State.IDLE;\n }\n\n if (!this.startFragRequested) {\n this.setStartPosition(newDetails, sliding);\n } else if (newDetails.live) {\n this.synchronizeToLiveEdge(newDetails);\n }\n\n // trigger handler right now\n this.tick();\n }\n\n protected _handleFragmentLoadProgress(data: FragLoadedData) {\n const { frag, part, payload } = data;\n const { levels } = this;\n if (!levels) {\n this.warn(\n `Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`\n );\n return;\n }\n const currentLevel = levels[frag.level];\n const details = currentLevel.details as LevelDetails;\n if (!details) {\n this.warn(\n `Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`\n );\n 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 const trackId = data.id;\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 }\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: 'audio',\n });\n }\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, {\n id: trackId,\n });\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 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 this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (this.state !== State.ERROR) {\n if (data.fatal) {\n // if fatal error, stop processing\n this.warn(`${data.details}`);\n this.state = State.ERROR;\n } else {\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 (!data.levelRetry && this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n }\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (\n data.parent === 'main' &&\n (this.state === State.PARSING || this.state === State.PARSED)\n ) {\n let flushBuffer = true;\n const bufferedInfo = this.getFwdBufferInfo(\n this.media,\n PlaylistLevelType.MAIN\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 if (bufferedInfo && bufferedInfo.len > 0.5) {\n flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);\n }\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 buffer to recover\n this.warn(\n 'buffer full error also media.currentTime is not buffered, flush main'\n );\n // flush main buffer\n this.immediateLevelSwitch();\n }\n this.resetLoadingState();\n }\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 media =\n (type === ElementaryStreamTypes.VIDEO\n ? this.videoBuffer\n : this.mediaBuffer) || this.media;\n this.afterBufferFlushed(media, type, PlaylistLevelType.MAIN);\n }\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData\n ) {\n this.levels = data.levels;\n }\n\n public swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n */\n protected seekToStartPos() {\n const { media } = this;\n if (!media) {\n return;\n }\n const currentTime = media.currentTime;\n let startPosition = this.startPosition;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n if (startPosition >= 0 && currentTime < startPosition) {\n if (media.seeking) {\n this.log(\n `could not seek to ${startPosition}, already seeking at ${currentTime}`\n );\n return;\n }\n const buffered = BufferHelper.getBuffered(media);\n const bufferStart = buffered.length ? buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n if (\n delta > 0 &&\n (delta < this.config.maxBufferHole ||\n delta < this.config.maxFragLookUpTolerance)\n ) {\n this.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n this.log(\n `seek to target start position ${startPosition} from current time ${currentTime}`\n );\n media.currentTime = startPosition;\n }\n }\n\n private _getAudioCodec(currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap && audioCodec) {\n this.log('Swapping audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n\n return audioCodec;\n }\n\n private _loadBitrateTestFrag(frag: Fragment, levelDetails: LevelDetails) {\n frag.bitrateTest = true;\n this._doFragLoad(frag, levelDetails).then((data) => {\n const { hls } = this;\n if (!data || hls.nextLoadLevel || this.fragContextChanged(frag)) {\n return;\n }\n this.fragLoadError = 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.warn(\n `The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`\n );\n this.resetStartWhenNotLoaded(chunkMeta.level);\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 return;\n }\n\n this.state = State.PARSING;\n\n if (initSegment) {\n if (initSegment.tracks) {\n this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag,\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] = initPTS;\n hls.trigger(Events.INIT_PTS_FOUND, { frag, id, initPTS, timescale });\n }\n }\n\n // Avoid buffering if backtracking this fragment\n if (video && remuxResult.independent !== false) {\n if (details) {\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 (video.firstKeyFrame && video.independent && chunkMeta.id === 1) {\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 (targetBufferTime < startTime - this.config.maxBufferHole) {\n this.backtrack(frag);\n return;\n }\n // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n frag.start,\n endPTS,\n frag.start,\n endDTS,\n true\n );\n }\n }\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n startPTS,\n endPTS,\n startDTS,\n endDTS\n );\n if (this.backtrackFragment) {\n this.backtrackFragment = frag;\n }\n this.bufferFragmentData(video, frag, part, chunkMeta);\n }\n } else if (remuxResult.independent === false) {\n this.backtrack(frag);\n return;\n }\n\n if (audio) {\n const { startPTS, endPTS, startDTS, endDTS } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n }\n frag.setElementaryStreamInfo(\n ElementaryStreamTypes.AUDIO,\n startPTS,\n endPTS,\n startDTS,\n endDTS\n );\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n\n if (details && id3?.samples?.length) {\n const emittedID3: FragParsingMetadataData = {\n id,\n frag,\n details,\n samples: id3.samples,\n };\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (details && text) {\n const emittedText: FragParsingUserdataData = {\n id,\n frag,\n details,\n samples: text.samples,\n };\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n\n private _bufferInitSegment(\n currentLevel: Level,\n tracks: TrackSet,\n frag: Fragment,\n chunkMeta: ChunkMetadata\n ) {\n if (this.state !== State.PARSING) {\n return;\n }\n\n this.audioOnly = !!tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\n delete tracks.audio;\n }\n // include levelCodec in audio and video tracks\n const { audio, video, audiovideo } = tracks;\n if (audio) {\n let audioCodec = currentLevel.audioCodec;\n const ua = navigator.userAgent.toLowerCase();\n if (this.audioCodecSwitch) {\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // In the case that AAC and HE-AAC audio codecs are signalled in manifest,\n // force HE-AAC, as it seems that most browsers prefers it.\n // don't force HE-AAC if mono stream, or in Firefox\n if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {\n // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n this.log(`Android: force audio codec to ${audioCodec}`);\n }\n if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {\n this.log(\n `Swapping manifest audio codec \"${currentLevel.audioCodec}\" for \"${audioCodec}\"`\n );\n }\n audio.levelCodec = audioCodec;\n audio.id = 'main';\n this.log(\n `Init audio buffer, container:${\n audio.container\n }, codecs[selected/level/parsed]=[${audioCodec || ''}/${\n currentLevel.audioCodec || ''\n }/${audio.codec}]`\n );\n }\n if (video) {\n video.levelCodec = currentLevel.videoCodec;\n video.id = 'main';\n this.log(\n `Init video buffer, container:${\n video.container\n }, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${\n video.codec\n }]`\n );\n }\n if (audiovideo) {\n this.log(\n `Init audiovideo buffer, container:${\n audiovideo.container\n }, codecs[level/parsed]=[${currentLevel.attrs.CODECS || ''}/${\n audiovideo.codec\n }]`\n );\n }\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n Object.keys(tracks).forEach((trackName) => {\n const track = tracks[trackName];\n const initSegment = track.initSegment;\n if (initSegment?.byteLength) {\n this.hls.trigger(Events.BUFFER_APPENDING, {\n type: trackName as SourceBufferName,\n data: initSegment,\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n });\n }\n });\n // trigger handler right now\n this.tick();\n }\n\n public getMainFwdBufferInfo(): BufferInfo | null {\n return this.getFwdBufferInfo(\n this.mediaBuffer ? this.mediaBuffer : this.media,\n PlaylistLevelType.MAIN\n );\n }\n\n private backtrack(frag: Fragment) {\n this.couldBacktrack = true;\n // Causes findFragments to backtrack through fragments to find the keyframe\n this.backtrackFragment = frag;\n this.resetTransmuxer();\n this.flushBufferGap(frag);\n this.fragmentTracker.removeFragment(frag);\n this.fragPrevious = null;\n this.nextLoadPosition = frag.start;\n this.state = State.IDLE;\n }\n\n private checkFragmentChanged() {\n const video = this.media;\n let fragPlayingCurrent: Fragment | null = null;\n if (video && video.readyState > 1 && video.seeking === false) {\n const currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getAppendedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n this.backtrackFragment = null;\n const fragPlaying = this.fragPlaying;\n const fragCurrentLevel = fragPlayingCurrent.level;\n if (\n !fragPlaying ||\n fragPlayingCurrent.sn !== fragPlaying.sn ||\n fragPlaying.level !== fragCurrentLevel ||\n fragPlayingCurrent.urlId !== fragPlaying.urlId\n ) {\n this.fragPlaying = fragPlayingCurrent;\n this.hls.trigger(Events.FRAG_CHANGED, { frag: fragPlayingCurrent });\n if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {\n this.hls.trigger(Events.LEVEL_SWITCHED, {\n level: fragCurrentLevel,\n });\n }\n }\n }\n }\n }\n\n get nextLevel(): number {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get currentFrag(): Fragment | null {\n const media = this.media;\n if (media) {\n return this.fragPlaying || this.getAppendedFrag(media.currentTime);\n }\n return null;\n }\n\n get currentProgramDateTime(): Date | null {\n const media = this.media;\n if (media) {\n const currentTime = media.currentTime;\n const frag = this.currentFrag;\n if (\n frag &&\n Number.isFinite(currentTime) &&\n Number.isFinite(frag.programDateTime)\n ) {\n const epocMs =\n (frag.programDateTime as number) + (currentTime - frag.start) * 1000;\n return new Date(epocMs);\n }\n }\n return null;\n }\n\n get currentLevel(): number {\n const frag = this.currentFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get nextBufferedFrag() {\n const frag = this.currentFrag;\n if (frag) {\n return this.followingBufferedFrag(frag);\n }\n return null;\n }\n\n get forceStartLoad() {\n return this._forceStartLoad;\n }\n}\n","import { Events } from '../events';\nimport { Bufferable, BufferHelper } from '../utils/buffer-helper';\nimport { findFragmentByPTS } from './fragment-finders';\nimport { alignMediaPlaylistByPDT } from '../utils/discontinuities';\nimport { addSliding } from './level-helper';\nimport { FragmentState } from './fragment-tracker';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Level } from '../types/level';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { Fragment } from '../loader/fragment';\nimport type {\n ErrorData,\n FragLoadedData,\n SubtitleFragProcessed,\n SubtitleTracksUpdatedData,\n TrackLoadedData,\n TrackSwitchedData,\n BufferFlushingData,\n LevelLoadedData,\n FragBufferedData,\n} from '../types/events';\n\nconst TICK_INTERVAL = 500; // how often to tick in ms\n\ninterface TimeRange {\n start: number;\n end: number;\n}\n\nexport class SubtitleStreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n protected levels: Array<Level> = [];\n\n private currentTrackId: number = -1;\n private tracksBuffered: Array<TimeRange[]> = [];\n private mainDetails: LevelDetails | null = null;\n\n constructor(hls: Hls, fragmentTracker: FragmentTracker) {\n super(hls, fragmentTracker, '[subtitle-stream-controller]');\n this._registerListeners();\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.mainDetails = null;\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n startLoad(startPosition: number) {\n this.stopLoad();\n this.state = State.IDLE;\n\n this.setInterval(TICK_INTERVAL);\n\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n\n this.tick();\n }\n\n onManifestLoading() {\n this.mainDetails = null;\n this.fragmentTracker.removeAllFragments();\n }\n\n onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n this.mainDetails = data.details;\n }\n\n onSubtitleFragProcessed(\n event: Events.SUBTITLE_FRAG_PROCESSED,\n data: SubtitleFragProcessed\n ) {\n const { frag, success } = data;\n this.fragPrevious = frag;\n this.state = State.IDLE;\n if (!success) {\n return;\n }\n\n const buffered = this.tracksBuffered[this.currentTrackId];\n if (!buffered) {\n return;\n }\n\n // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n // so we can re-use the logic used to detect how much has been buffered\n let timeRange: TimeRange | undefined;\n const fragStart = frag.start;\n for (let i = 0; i < buffered.length; i++) {\n if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n timeRange = buffered[i];\n break;\n }\n }\n\n const fragEnd = frag.start + frag.duration;\n if (timeRange) {\n timeRange.end = fragEnd;\n } else {\n timeRange = {\n start: fragStart,\n end: fragEnd,\n };\n buffered.push(timeRange);\n }\n this.fragmentTracker.fragBuffered(frag);\n }\n\n onBufferFlushing(event: Events.BUFFER_FLUSHING, data: BufferFlushingData) {\n const { startOffset, endOffset } = data;\n if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {\n const { currentTrackId, levels } = this;\n if (\n !levels.length ||\n !levels[currentTrackId] ||\n !levels[currentTrackId].details\n ) {\n return;\n }\n const trackDetails = levels[currentTrackId].details as LevelDetails;\n const targetDuration = trackDetails.targetduration;\n const endOffsetSubtitles = endOffset - targetDuration;\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 // don't handle error not related to subtitle fragment\n if (!frag || frag.type !== PlaylistLevelType.SUBTITLE) {\n return;\n }\n\n if (this.fragCurrent) {\n this.fragCurrent.abortRequests();\n }\n\n this.state = State.IDLE;\n }\n\n // Got all new subtitle levels.\n onSubtitleTracksUpdated(\n event: Events.SUBTITLE_TRACKS_UPDATED,\n { subtitleTracks }: SubtitleTracksUpdatedData\n ) {\n this.tracksBuffered = [];\n this.levels = subtitleTracks.map(\n (mediaPlaylist) => new Level(mediaPlaylist)\n );\n this.fragmentTracker.removeAllFragments();\n this.fragPrevious = null;\n this.levels.forEach((level: Level) => {\n this.tracksBuffered[level.id] = [];\n });\n this.mediaBuffer = null;\n }\n\n onSubtitleTrackSwitch(\n event: Events.SUBTITLE_TRACK_SWITCH,\n data: TrackSwitchedData\n ) {\n this.currentTrackId = data.id;\n\n if (!this.levels.length || this.currentTrackId === -1) {\n this.clearInterval();\n return;\n }\n\n // Check if track has the necessary details to load fragments\n const currentTrack = this.levels[this.currentTrackId];\n if (currentTrack?.details) {\n this.mediaBuffer = this.mediaBufferTimeRanges;\n } else {\n this.mediaBuffer = null;\n }\n if (currentTrack) {\n this.setInterval(TICK_INTERVAL);\n }\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded(\n event: Events.SUBTITLE_TRACK_LOADED,\n data: TrackLoadedData\n ) {\n const { details: newDetails, id: trackId } = data;\n const { currentTrackId, levels } = this;\n if (!levels.length) {\n return;\n }\n const track: Level = levels[currentTrackId];\n if (trackId >= levels.length || trackId !== currentTrackId || !track) {\n return;\n }\n this.mediaBuffer = this.mediaBufferTimeRanges;\n let sliding = 0;\n if (newDetails.live || track.details?.live) {\n const mainDetails = this.mainDetails;\n if (newDetails.deltaUpdateFailed || !mainDetails) {\n return;\n }\n const mainSlidingStartFragment = mainDetails.fragments[0];\n if (!track.details) {\n if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n sliding = newDetails.fragments[0].start;\n } else if (mainSlidingStartFragment) {\n // line up live playlist with main so that fragments in range are loaded\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n } else {\n sliding = this.alignPlaylists(newDetails, track.details);\n if (sliding === 0 && mainSlidingStartFragment) {\n // realign with main when there is no overlap with last refresh\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = trackId;\n\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(track.details, sliding);\n }\n\n // trigger handler right now\n this.tick();\n\n // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload\n if (\n newDetails.live &&\n !this.fragCurrent &&\n this.media &&\n this.state === State.IDLE\n ) {\n const foundFrag = findFragmentByPTS(\n null,\n newDetails.fragments,\n this.media.currentTime,\n 0\n );\n if (!foundFrag) {\n this.warn('Subtitle playlist not aligned with playback');\n track.details = undefined;\n }\n }\n }\n\n _handleFragmentLoadComplete(fragLoadedData: FragLoadedData) {\n const { frag, payload } = fragLoadedData;\n const decryptData = frag.decryptdata;\n const hls = this.hls;\n\n if (this.fragContextChanged(frag)) {\n return;\n }\n // check to see if the payload needs to be decrypted\n if (\n payload &&\n payload.byteLength > 0 &&\n decryptData &&\n decryptData.key &&\n decryptData.iv &&\n decryptData.method === 'AES-128'\n ) {\n const startTime = performance.now();\n // decrypt the subtitles\n this.decrypter\n .decrypt(\n new Uint8Array(payload),\n decryptData.key.buffer,\n decryptData.iv.buffer\n )\n .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 if (\n !levels.length ||\n !levels[currentTrackId] ||\n !levels[currentTrackId].details\n ) {\n return;\n }\n\n // Expand range of subs loaded by one target-duration in either direction to make up for misaligned playlists\n const trackDetails = levels[currentTrackId].details as LevelDetails;\n const targetDuration = trackDetails.targetduration;\n const { config } = this;\n const currentTime = this.getLoadPosition();\n const bufferedInfo = BufferHelper.bufferedInfo(\n this.tracksBuffered[this.currentTrackId] || [],\n currentTime - targetDuration,\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 maxBufLen =\n this.getMaxBufferLength(mainBufferInfo?.len) + targetDuration;\n\n if (bufferLen > maxBufLen) {\n return;\n }\n\n console.assert(\n trackDetails,\n 'Subtitle track details are defined on idle subtitle stream controller tick'\n );\n const fragments = trackDetails.fragments;\n const fragLen = fragments.length;\n const end = trackDetails.edge;\n\n let foundFrag: Fragment | null;\n const fragPrevious = this.fragPrevious;\n if (targetBufferTime < end) {\n const { maxFragLookUpTolerance } = config;\n foundFrag = findFragmentByPTS(\n fragPrevious,\n fragments,\n Math.max(fragments[0].start, targetBufferTime),\n maxFragLookUpTolerance\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\n foundFrag = this.mapToInitFragWhenRequired(foundFrag);\n if (!foundFrag) {\n return;\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, trackDetails, 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 levelDetails: LevelDetails,\n targetBufferTime: number\n ) {\n this.fragCurrent = frag;\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, levelDetails);\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, levelDetails, targetBufferTime);\n }\n }\n\n get mediaBufferTimeRanges(): Bufferable {\n return new BufferableInstance(\n this.tracksBuffered[this.currentTrackId] || []\n );\n }\n}\n\nclass BufferableInstance implements Bufferable {\n public readonly buffered: TimeRanges;\n\n constructor(timeranges: TimeRange[]) {\n const getRange = (\n name: 'start' | 'end',\n index: number,\n length: number\n ): number => {\n index = index >>> 0;\n if (index > length - 1) {\n throw new DOMException(\n `Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`\n );\n }\n return timeranges[index][name];\n };\n this.buffered = {\n get length() {\n return timeranges.length;\n },\n end(index: number): number {\n return getRange('end', index, timeranges.length);\n },\n start(index: number): number {\n return getRange('start', index, timeranges.length);\n },\n };\n }\n}\n","import { Events } from '../events';\nimport { clearCurrentCues } from '../utils/texttrack-utils';\nimport BasePlaylistController from './base-playlist-controller';\nimport type { HlsUrlParameters } from '../types/level';\nimport type Hls from '../hls';\nimport type {\n TrackLoadedData,\n MediaAttachedData,\n SubtitleTracksUpdatedData,\n ManifestParsedData,\n LevelSwitchingData,\n} from '../types/events';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport { ErrorData, LevelLoadingData } from '../types/events';\nimport { PlaylistContextType } from '../types/loader';\n\nclass SubtitleTrackController extends BasePlaylistController {\n private media: HTMLMediaElement | null = null;\n private tracks: MediaPlaylist[] = [];\n private groupId: string | null = null;\n private tracksInGroup: MediaPlaylist[] = [];\n private trackId: number = -1;\n private selectDefaultTrack: boolean = true;\n private queuedDefaultTrack: number = -1;\n private trackChangeListener: () => void = () => this.onTextTracksChanged();\n private asyncPollTrackChange: () => void = () => this.pollTrackChange(0);\n private useTextTrackPolling: boolean = false;\n private subtitlePollingInterval: number = -1;\n private _subtitleDisplay: boolean = true;\n\n constructor(hls: Hls) {\n super(hls, '[subtitle-track-controller]');\n this.registerListeners();\n }\n\n public destroy() {\n this.unregisterListeners();\n this.tracks.length = 0;\n this.tracksInGroup.length = 0;\n this.trackChangeListener = this.asyncPollTrackChange = null as any;\n super.destroy();\n }\n\n public get subtitleDisplay(): boolean {\n return this._subtitleDisplay;\n }\n\n public set subtitleDisplay(value: boolean) {\n this._subtitleDisplay = value;\n if (this.trackId > -1) {\n this.toggleTrackModes(this.trackId);\n }\n }\n\n private registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ): void {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (this.queuedDefaultTrack > -1) {\n this.subtitleTrack = this.queuedDefaultTrack;\n this.queuedDefaultTrack = -1;\n }\n\n this.useTextTrackPolling = !(\n this.media.textTracks && 'onchange' in this.media.textTracks\n );\n if (this.useTextTrackPolling) {\n this.pollTrackChange(500);\n } else {\n this.media.textTracks.addEventListener(\n 'change',\n this.asyncPollTrackChange\n );\n }\n }\n\n private pollTrackChange(timeout: number) {\n self.clearInterval(this.subtitlePollingInterval);\n this.subtitlePollingInterval = self.setInterval(\n this.trackChangeListener,\n timeout\n );\n }\n\n protected onMediaDetaching(): void {\n if (!this.media) {\n return;\n }\n\n self.clearInterval(this.subtitlePollingInterval);\n if (!this.useTextTrackPolling) {\n this.media.textTracks.removeEventListener(\n 'change',\n this.asyncPollTrackChange\n );\n }\n\n if (this.trackId > -1) {\n this.queuedDefaultTrack = this.trackId;\n }\n\n const textTracks = filterSubtitleTracks(this.media.textTracks);\n // Clear loaded cues on media detachment from tracks\n textTracks.forEach((track) => {\n clearCurrentCues(track);\n });\n // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.\n this.subtitleTrack = -1;\n this.media = null;\n }\n\n protected onManifestLoading(): void {\n this.tracks = [];\n this.groupId = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.selectDefaultTrack = true;\n }\n\n // Fired whenever a new manifest is loaded.\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ): void {\n this.tracks = data.subtitleTracks;\n }\n\n protected onSubtitleTrackLoaded(\n event: Events.SUBTITLE_TRACK_LOADED,\n data: TrackLoadedData\n ): void {\n const { id, details } = data;\n const { trackId } = this;\n const currentTrack = this.tracksInGroup[trackId];\n\n if (!currentTrack) {\n this.warn(`Invalid subtitle track id ${id}`);\n return;\n }\n\n const curDetails = currentTrack.details;\n currentTrack.details = data.details;\n this.log(\n `subtitle track ${id} loaded [${details.startSN}-${details.endSN}]`\n );\n\n if (id === this.trackId) {\n this.retryCount = 0;\n this.playlistLoaded(id, data, curDetails);\n }\n }\n\n protected onLevelLoading(\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ): void {\n this.switchLevel(data.level);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.switchLevel(data.level);\n }\n\n private switchLevel(levelIndex: number) {\n const levelInfo = this.hls.levels[levelIndex];\n if (!levelInfo?.textGroupIds) {\n return;\n }\n\n const textGroupId = levelInfo.textGroupIds[levelInfo.urlId];\n if (this.groupId !== textGroupId) {\n const lastTrack = this.tracksInGroup\n ? this.tracksInGroup[this.trackId]\n : undefined;\n\n const subtitleTracks = this.tracks.filter(\n (track): boolean => !textGroupId || track.groupId === textGroupId\n );\n this.tracksInGroup = subtitleTracks;\n const initialTrackId =\n this.findTrackId(lastTrack?.name) || this.findTrackId();\n this.groupId = textGroupId;\n\n const subtitleTracksUpdated: SubtitleTracksUpdatedData = {\n subtitleTracks,\n };\n this.log(\n `Updating subtitle tracks, ${subtitleTracks.length} track(s) found in \"${textGroupId}\" group-id`\n );\n this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);\n\n if (initialTrackId !== -1) {\n this.setSubtitleTrack(initialTrackId, lastTrack);\n }\n }\n }\n\n private findTrackId(name?: string): number {\n const textTracks = this.tracksInGroup;\n for (let i = 0; i < textTracks.length; i++) {\n const track = textTracks[i];\n if (!this.selectDefaultTrack || track.default) {\n if (!name || name === track.name) {\n return track.id;\n }\n }\n }\n return -1;\n }\n\n protected onError(event: Events.ERROR, data: ErrorData): void {\n super.onError(event, data);\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.SUBTITLE_TRACK &&\n data.context.id === this.trackId &&\n data.context.groupId === this.groupId\n ) {\n this.retryLoadingOrFail(data);\n }\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks(): MediaPlaylist[] {\n return this.tracksInGroup;\n }\n\n /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/\n get subtitleTrack(): number {\n return this.trackId;\n }\n\n set subtitleTrack(newId: number) {\n this.selectDefaultTrack = false;\n const lastTrack = this.tracksInGroup\n ? this.tracksInGroup[this.trackId]\n : undefined;\n this.setSubtitleTrack(newId, lastTrack);\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n super.loadPlaylist();\n const currentTrack = this.tracksInGroup[this.trackId];\n if (this.shouldLoadTrack(currentTrack)) {\n const id = currentTrack.id;\n const groupId = currentTrack.groupId as string;\n let url = currentTrack.url;\n if (hlsUrlParameters) {\n try {\n url = hlsUrlParameters.addDirectives(url);\n } catch (error) {\n this.warn(\n `Could not construct new URL with HLS Delivery Directives: ${error}`\n );\n }\n }\n this.log(`Loading subtitle playlist for id ${id}`);\n this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n */\n private toggleTrackModes(newId: number): void {\n const { media, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n const groupTracks = textTracks.filter(\n (track) => (track as any).groupId === this.groupId\n );\n if (newId === -1) {\n [].slice.call(textTracks).forEach((track) => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = groupTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = groupTracks[newId];\n if (nextTrack) {\n nextTrack.mode = this.subtitleDisplay ? 'showing' : 'hidden';\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n */\n private setSubtitleTrack(\n newId: number,\n lastTrack: MediaPlaylist | undefined\n ): void {\n const tracks = this.tracksInGroup;\n\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (!this.media) {\n this.queuedDefaultTrack = newId;\n return;\n }\n\n if (this.trackId !== newId) {\n this.toggleTrackModes(newId);\n }\n\n // exit if track id as already set or invalid\n if (\n (this.trackId === newId && (newId === -1 || tracks[newId]?.details)) ||\n newId < -1 ||\n newId >= tracks.length\n ) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n const track = tracks[newId];\n this.log(`Switching to subtitle track ${newId}`);\n this.trackId = newId;\n if (track) {\n const { id, groupId = '', name, type, url } = track;\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {\n id,\n groupId,\n name,\n type,\n url,\n });\n const hlsUrlParameters = this.switchParams(track.url, lastTrack?.details);\n this.loadPlaylist(hlsUrlParameters);\n } else {\n // switch to -1\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, { id: newId });\n }\n }\n\n private onTextTracksChanged(): void {\n if (!this.useTextTrackPolling) {\n self.clearInterval(this.subtitlePollingInterval);\n }\n // Media is undefined when switching streams via loadSource()\n if (!this.media || !this.hls.config.renderTextTracksNatively) {\n return;\n }\n\n let trackId: number = -1;\n const tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n if (this.subtitleTrack !== trackId) {\n this.subtitleTrack = trackId;\n }\n }\n}\n\nfunction filterSubtitleTracks(textTrackList: TextTrackList): TextTrack[] {\n const tracks: TextTrack[] = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if (track.kind === 'subtitles' && track.label) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nexport default SubtitleTrackController;\n","import { Events } from '../events';\nimport Cea608Parser, { CaptionScreen } from '../utils/cea-608-parser';\nimport OutputFilter from '../utils/output-filter';\nimport { parseWebVTT } from '../utils/webvtt-parser';\nimport {\n sendAddTrackEvent,\n clearCurrentCues,\n addCueToTrack,\n removeCuesInRange,\n} from '../utils/texttrack-utils';\nimport { parseIMSC1, IMSC1_CODEC } from '../utils/imsc1-ttml-parser';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Fragment } from '../loader/fragment';\nimport {\n FragParsingUserdataData,\n FragLoadedData,\n FragDecryptedData,\n MediaAttachingData,\n ManifestLoadedData,\n InitPTSFoundData,\n SubtitleTracksUpdatedData,\n BufferFlushingData,\n FragLoadingData,\n} from '../types/events';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { HlsConfig } from '../config';\nimport type { CuesInterface } from '../utils/cues';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport type { VTTCCs } from '../types/vtt';\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: Array<number> = [];\n private timescale: Array<number> = [];\n private unparsedVttFrags: Array<FragLoadedData | FragDecryptedData> = [];\n private captionsTracks: Record<string, TextTrack> = {};\n private nonNativeCaptionsTracks: Record<string, NonNativeCaptionsTrack> = {};\n private cea608Parser1!: Cea608Parser;\n private cea608Parser2!: Cea608Parser;\n private lastSn: number = -1;\n private lastPartIndex: number = -1;\n private prevCC: number = -1;\n private vttCCs: VTTCCs = newVTTCCs();\n private captionsProperties: {\n textTrack1: TrackProperties;\n textTrack2: TrackProperties;\n textTrack3: TrackProperties;\n textTrack4: TrackProperties;\n };\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.Cues = hls.config.cueHandler;\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode,\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode,\n },\n textTrack3: {\n label: this.config.captionsTextTrack3Label,\n languageCode: this.config.captionsTextTrack3LanguageCode,\n },\n textTrack4: {\n label: this.config.captionsTextTrack4Label,\n languageCode: this.config.captionsTextTrack4LanguageCode,\n },\n };\n\n if (this.config.enableCEA708Captions) {\n const channel1 = new OutputFilter(this, 'textTrack1');\n const channel2 = new OutputFilter(this, 'textTrack2');\n const channel3 = new OutputFilter(this, 'textTrack3');\n const channel4 = new OutputFilter(this, 'textTrack4');\n this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);\n this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);\n }\n\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n }\n\n public destroy(): void {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n // @ts-ignore\n this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;\n }\n\n public addCues(\n trackName: string,\n startTime: number,\n endTime: number,\n screen: CaptionScreen,\n cueRanges: Array<[number, number]>\n ) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n let merged = false;\n for (let i = cueRanges.length; i--; ) {\n const cueRange = cueRanges[i];\n const overlap = intersection(\n cueRange[0],\n cueRange[1],\n startTime,\n endTime\n );\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if (overlap / (endTime - startTime) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n cueRanges.push([startTime, endTime]);\n }\n\n if (this.config.renderTextTracksNatively) {\n const track = this.captionsTracks[trackName];\n this.Cues.newCue(track, startTime, endTime, screen);\n } else {\n const cues = this.Cues.newCue(null, startTime, endTime, screen);\n this.hls.trigger(Events.CUES_PARSED, {\n type: 'captions',\n cues,\n track: trackName,\n });\n }\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n private onInitPtsFound(\n event: Events.INIT_PTS_FOUND,\n { frag, id, initPTS, timescale }: InitPTSFoundData\n ) {\n const { unparsedVttFrags } = this;\n if (id === 'main') {\n this.initPTS[frag.cc] = initPTS;\n this.timescale[frag.cc] = timescale;\n }\n\n // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (unparsedVttFrags.length) {\n this.unparsedVttFrags = [];\n unparsedVttFrags.forEach((frag) => {\n this.onFragLoaded(Events.FRAG_LOADED, frag as FragLoadedData);\n });\n }\n }\n\n private getExistingTrack(trackName: string): TextTrack | null {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n const textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n public createCaptionsTrack(trackName: string) {\n if (this.config.renderTextTracksNatively) {\n this.createNativeTrack(trackName);\n } else {\n this.createNonNativeTrack(trackName);\n }\n }\n\n private createNativeTrack(trackName: string) {\n if (this.captionsTracks[trackName]) {\n return;\n }\n const { captionsProperties, captionsTracks, media } = this;\n const { label, languageCode } = captionsProperties[trackName];\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], media as HTMLMediaElement);\n }\n }\n\n private createNonNativeTrack(trackName: string) {\n if (this.nonNativeCaptionsTracks[trackName]) {\n return;\n }\n // Create a list of a single track for the provider to consume\n const trackProperties: TrackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n const label = trackProperties.label as string;\n const track = {\n _id: trackName,\n label,\n kind: 'captions',\n default: trackProperties.media ? !!trackProperties.media.default : false,\n closedCaptions: trackProperties.media,\n };\n this.nonNativeCaptionsTracks[trackName] = track;\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] });\n }\n\n private createTextTrack(\n kind: TextTrackKind,\n label: string,\n lang?: string\n ): TextTrack | undefined {\n const media = this.media;\n if (!media) {\n return;\n }\n return media.addTextTrack(kind, label, lang);\n }\n\n private onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n this.media = data.media;\n this._cleanTracks();\n }\n\n private onMediaDetaching() {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach((trackName) => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n this.nonNativeCaptionsTracks = {};\n }\n\n private onManifestLoading() {\n this.lastSn = -1; // Detect discontinuity in fragment parsing\n this.lastPartIndex = -1;\n this.prevCC = -1;\n this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests\n this._cleanTracks();\n this.tracks = [];\n this.captionsTracks = {};\n this.nonNativeCaptionsTracks = {};\n this.textTracks = [];\n this.unparsedVttFrags = this.unparsedVttFrags || [];\n this.initPTS = [];\n this.timescale = [];\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 this.textTracks = [];\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 sameTracks =\n this.tracks && tracks && this.tracks.length === tracks.length;\n this.tracks = tracks || [];\n\n if (this.config.renderTextTracksNatively) {\n const inUseTracks = this.media ? this.media.textTracks : [];\n\n this.tracks.forEach((track, index) => {\n let textTrack: TextTrack | undefined;\n if (index < inUseTracks.length) {\n let inUseTrack: TextTrack | null = null;\n\n for (let i = 0; i < inUseTracks.length; i++) {\n if (canReuseVttTextTrack(inUseTracks[i], track)) {\n inUseTrack = inUseTracks[i];\n break;\n }\n }\n\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (textTrack) {\n clearCurrentCues(textTrack);\n } else {\n const textTrackKind =\n this._captionsOrSubtitlesFromCharacteristics(track);\n textTrack = this.createTextTrack(\n textTrackKind,\n track.name,\n track.lang\n );\n if (textTrack) {\n textTrack.mode = 'disabled';\n }\n }\n if (textTrack) {\n (textTrack as any).groupId = track.groupId;\n this.textTracks.push(textTrack);\n }\n });\n } else if (!sameTracks && this.tracks && this.tracks.length) {\n // Create a list of tracks for the provider to consume\n const tracksList = this.tracks.map((track) => {\n return {\n label: track.name,\n kind: track.type.toLowerCase(),\n default: track.default,\n subtitleTrack: track,\n };\n });\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {\n tracks: tracksList,\n });\n }\n }\n }\n\n private _captionsOrSubtitlesFromCharacteristics(\n track: MediaPlaylist\n ): TextTrackKind {\n if (track.attrs?.CHARACTERISTICS) {\n const transcribesSpokenDialog = /transcribes-spoken-dialog/gi.test(\n track.attrs.CHARACTERISTICS\n );\n const describesMusicAndSound = /describes-music-and-sound/gi.test(\n track.attrs.CHARACTERISTICS\n );\n\n if (transcribesSpokenDialog && describesMusicAndSound) {\n return 'captions';\n }\n }\n\n return 'subtitles';\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ) {\n if (this.config.enableCEA708Captions && data.captions) {\n data.captions.forEach((captionsTrack) => {\n const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(\n captionsTrack.instreamId as string\n );\n if (!instreamIdMatch) {\n return;\n }\n const trackName = `textTrack${instreamIdMatch[1]}`;\n const trackProperties: TrackProperties =\n this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n trackProperties.label = captionsTrack.name;\n if (captionsTrack.lang) {\n // optional attribute\n trackProperties.languageCode = captionsTrack.lang;\n }\n trackProperties.media = captionsTrack;\n });\n }\n }\n\n private closedCaptionsForLevel(frag: Fragment): string | undefined {\n const level = this.hls.levels[frag.level];\n return level?.attrs['CLOSED-CAPTIONS'];\n }\n\n private onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {\n const { cea608Parser1, cea608Parser2, lastSn, lastPartIndex } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n return;\n }\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (data.frag.type === PlaylistLevelType.MAIN) {\n const sn = data.frag.sn;\n const partIndex = data?.part?.index ?? -1;\n if (\n !(\n sn === lastSn + 1 ||\n (sn === lastSn && partIndex === lastPartIndex + 1)\n )\n ) {\n cea608Parser1.reset();\n cea608Parser2.reset();\n }\n this.lastSn = sn as number;\n this.lastPartIndex = partIndex;\n }\n }\n\n private onFragLoaded(\n event: Events.FRAG_LOADED,\n data: FragDecryptedData | FragLoadedData\n ) {\n const { frag, payload } = data;\n const { initPTS, unparsedVttFrags } = this;\n if (frag.type === PlaylistLevelType.SUBTITLE) {\n // If fragment is subtitle type, parse as WebVTT.\n if (payload.byteLength) {\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived.\n if (!Number.isFinite(initPTS[frag.cc])) {\n unparsedVttFrags.push(data);\n if (initPTS.length) {\n // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.\n this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag,\n error: new Error('Missing initial subtitle PTS'),\n });\n }\n return;\n }\n\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 (\n decryptData == null ||\n decryptData.key == null ||\n decryptData.method !== 'AES-128' ||\n decrypted\n ) {\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(frag, payload, vttCCs);\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 this.timescale[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(frag: Fragment, payload: ArrayBuffer, vttCCs: any) {\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.timescale[frag.cc],\n 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 this._fallbackToIMSC1(frag, payload);\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${error}`);\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 this.timescale[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 if (!Number.isFinite(this.initPTS[frag.cc])) {\n this.unparsedVttFrags.push(data as unknown as FragLoadedData);\n return;\n }\n this.onFragLoaded(Events.FRAG_LOADED, data as unknown as FragLoadedData);\n }\n }\n\n private onSubtitleTracksCleared() {\n this.tracks = [];\n this.captionsTracks = {};\n }\n\n private onFragParsingUserdata(\n event: Events.FRAG_PARSING_USERDATA,\n data: FragParsingUserdataData\n ) {\n const { cea608Parser1, cea608Parser2 } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n return;\n }\n\n const { frag, samples } = data;\n if (\n frag.type === PlaylistLevelType.MAIN &&\n this.closedCaptionsForLevel(frag) === 'NONE'\n ) {\n return;\n }\n // If the event contains captions (found in the bytes property), push all bytes into the parser immediately\n // It will create the proper timestamps based on the PTS value\n for (let i = 0; i < samples.length; i++) {\n const ccBytes = samples[i].bytes;\n if (ccBytes) {\n const ccdatas = this.extractCea608Data(ccBytes);\n cea608Parser1.addData(samples[i].pts, ccdatas[0]);\n cea608Parser2.addData(samples[i].pts, ccdatas[1]);\n }\n }\n }\n\n onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { startOffset, endOffset, endOffsetSubtitles, type }: BufferFlushingData\n ) {\n const { media } = this;\n if (!media || media.currentTime < endOffset) {\n return;\n }\n // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed\n // Forward cues are never removed because we can loose streamed 608 content from recent fragments\n if (!type || type === 'video') {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach((trackName) =>\n removeCuesInRange(captionsTracks[trackName], startOffset, endOffset)\n );\n }\n if (this.config.renderTextTracksNatively) {\n // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed\n if (startOffset === 0 && endOffsetSubtitles !== undefined) {\n const { textTracks } = this;\n Object.keys(textTracks).forEach((trackName) =>\n removeCuesInRange(\n textTracks[trackName],\n startOffset,\n endOffsetSubtitles\n )\n );\n }\n }\n }\n\n private extractCea608Data(byteArray: Uint8Array): number[][] {\n const actualCCBytes: number[][] = [[], []];\n const count = byteArray[0] & 0x1f;\n let position = 2;\n\n for (let j = 0; j < count; j++) {\n const tmpByte = byteArray[position++];\n const ccbyte1 = 0x7f & byteArray[position++];\n const ccbyte2 = 0x7f & byteArray[position++];\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n const ccValid = (0x04 & tmpByte) !== 0; // Support all four channels\n if (ccValid) {\n const ccType = 0x03 & tmpByte;\n if (\n 0x00 /* CEA608 field1*/ === ccType ||\n 0x01 /* CEA608 field2*/ === ccType\n ) {\n // Exclude CEA708 CC data.\n actualCCBytes[ccType].push(ccbyte1);\n actualCCBytes[ccType].push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nfunction canReuseVttTextTrack(inUseTrack, manifestTrack): boolean {\n return (\n inUseTrack &&\n inUseTrack.label === manifestTrack.name &&\n !(inUseTrack.textTrack1 || inUseTrack.textTrack2)\n );\n}\n\nfunction intersection(x1: number, x2: number, y1: number, y2: number): number {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\n\nfunction newVTTCCs(): VTTCCs {\n return {\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0,\n prevCC: -1,\n new: true,\n },\n };\n}\n","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","import { sliceUint8 } from '../utils/typed-array';\n\n// PKCS7\nexport function removePadding(array: Uint8Array): Uint8Array {\n const outputBytes = array.byteLength;\n const paddingBytes =\n outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return sliceUint8(array, 0, outputBytes - paddingBytes);\n }\n return array;\n}\n\nexport default class AESDecryptor {\n private rcon: Array<number> = [\n 0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,\n ];\n private subMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private invSubMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private sBox: Uint32Array = new Uint32Array(256);\n private invSBox: Uint32Array = new Uint32Array(256);\n private key: Uint32Array = new Uint32Array(0);\n\n private ksRows: number = 0;\n private keySize: number = 0;\n private keySchedule!: Uint32Array;\n private invKeySchedule!: Uint32Array;\n\n constructor() {\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_(arrayBuffer) {\n const view = new DataView(arrayBuffer);\n const newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n }\n\n initTable() {\n const sBox = this.sBox;\n const invSBox = this.invSBox;\n const subMix = this.subMix;\n const subMix0 = subMix[0];\n const subMix1 = subMix[1];\n const subMix2 = subMix[2];\n const subMix3 = subMix[3];\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n const x2 = d[x];\n const x4 = d[x2];\n const x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey(keyBuffer: ArrayBuffer) {\n // convert keyBuffer to Uint32Array\n const key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = key[offset] === this.key[offset];\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n const keySize = (this.keySize = key.length);\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n const ksRows = (this.ksRows = (keySize + 6 + 1) * 4);\n let ksRow;\n let invKsRow;\n\n const keySchedule = (this.keySchedule = new Uint32Array(ksRows));\n const invKeySchedule = (this.invKeySchedule = new Uint32Array(ksRows));\n const sbox = this.sBox;\n const rcon = this.rcon;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] =\n invSubMix0[sbox[t >>> 24]] ^\n invSubMix1[sbox[(t >>> 16) & 0xff]] ^\n invSubMix2[sbox[(t >>> 8) & 0xff]] ^\n invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap(word) {\n return (\n (word << 24) |\n ((word & 0xff00) << 8) |\n ((word & 0xff0000) >> 8) |\n (word >>> 24)\n );\n }\n\n decrypt(inputArrayBuffer: ArrayBuffer, offset: number, aesIV: ArrayBuffer) {\n const nRounds = this.keySize + 6;\n const invKeySchedule = this.invKeySchedule;\n const invSBOX = this.invSBox;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n const inputInt32 = new Int32Array(inputArrayBuffer);\n const outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n let ksRow, i;\n const swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 =\n invSubMix0[s0 >>> 24] ^\n invSubMix1[(s1 >> 16) & 0xff] ^\n invSubMix2[(s2 >> 8) & 0xff] ^\n invSubMix3[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n invSubMix0[s1 >>> 24] ^\n invSubMix1[(s2 >> 16) & 0xff] ^\n invSubMix2[(s3 >> 8) & 0xff] ^\n invSubMix3[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n invSubMix0[s2 >>> 24] ^\n invSubMix1[(s3 >> 16) & 0xff] ^\n invSubMix2[(s0 >> 8) & 0xff] ^\n invSubMix3[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n invSubMix0[s3 >>> 24] ^\n invSubMix1[(s0 >> 16) & 0xff] ^\n invSubMix2[(s1 >> 8) & 0xff] ^\n invSubMix3[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 =\n (invSBOX[s0 >>> 24] << 24) ^\n (invSBOX[(s1 >> 16) & 0xff] << 16) ^\n (invSBOX[(s2 >> 8) & 0xff] << 8) ^\n invSBOX[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n (invSBOX[s1 >>> 24] << 24) ^\n (invSBOX[(s2 >> 16) & 0xff] << 16) ^\n (invSBOX[(s3 >> 8) & 0xff] << 8) ^\n invSBOX[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n (invSBOX[s2 >>> 24] << 24) ^\n (invSBOX[(s3 >> 16) & 0xff] << 16) ^\n (invSBOX[(s0 >> 8) & 0xff] << 8) ^\n invSBOX[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n (invSBOX[s3 >>> 24] << 24) ^\n (invSBOX[(s0 >> 16) & 0xff] << 16) ^\n (invSBOX[(s1 >> 8) & 0xff] << 8) ^\n invSBOX[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return outputInt32.buffer;\n }\n}\n","import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor, { removePadding } from './aes-decryptor';\nimport { logger } from '../utils/logger';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { sliceUint8 } from '../utils/typed-array';\nimport type { HlsConfig } from '../config';\n\nconst CHUNK_SIZE = 16; // 16 bytes, 128 bits\n\nexport default class Decrypter {\n private logEnabled: boolean = true;\n private removePKCS7Padding: boolean;\n private subtle: SubtleCrypto | null = null;\n private softwareDecrypter: AESDecryptor | null = null;\n private key: ArrayBuffer | null = null;\n private fastAesKey: FastAESKey | null = null;\n private remainderData: Uint8Array | null = null;\n private currentIV: ArrayBuffer | null = null;\n private currentResult: ArrayBuffer | null = null;\n private useSoftware: boolean;\n\n constructor(config: HlsConfig, { removePKCS7Padding = true } = {}) {\n this.useSoftware = config.enableSoftwareAES;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = self.crypto;\n if (browserCrypto) {\n this.subtle =\n browserCrypto.subtle ||\n ((browserCrypto as any).webkitSubtle as SubtleCrypto);\n }\n } catch (e) {\n /* no-op */\n }\n }\n if (this.subtle === null) {\n this.useSoftware = true;\n }\n }\n\n destroy() {\n this.subtle = null;\n this.softwareDecrypter = null;\n this.key = null;\n this.fastAesKey = null;\n this.remainderData = null;\n this.currentIV = null;\n this.currentResult = null;\n }\n\n public isSync() {\n return this.useSoftware;\n }\n\n public flush(): Uint8Array | null {\n const { currentResult, remainderData } = this;\n if (!currentResult || remainderData) {\n logger.error(\n `[softwareDecrypt] ${\n remainderData\n ? 'overflow bytes: ' + remainderData.byteLength\n : 'no result'\n }`\n );\n this.reset();\n return null;\n }\n const data = new Uint8Array(currentResult);\n this.reset();\n if (this.removePKCS7Padding) {\n return removePadding(data);\n }\n return data;\n }\n\n public reset() {\n this.currentResult = null;\n this.currentIV = null;\n this.remainderData = null;\n if (this.softwareDecrypter) {\n this.softwareDecrypter = null;\n }\n }\n\n public decrypt(\n data: Uint8Array | ArrayBuffer,\n key: ArrayBuffer,\n iv: ArrayBuffer\n ): Promise<ArrayBuffer> {\n if (this.useSoftware) {\n return new Promise((resolve, reject) => {\n this.softwareDecrypt(new Uint8Array(data), key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n resolve(decryptResult.buffer);\n } else {\n reject(new Error('[softwareDecrypt] Failed to decrypt data'));\n }\n });\n }\n return this.webCryptoDecrypt(new Uint8Array(data), key, iv);\n }\n\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n public softwareDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer\n ): ArrayBuffer | null {\n const { currentIV, currentResult, remainderData } = this;\n this.logOnce('JS AES decrypt');\n // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call\n // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached\n // the end on flush(), but by that time we have already received all bytes for the segment.\n // Progressive decryption does not work with WebCrypto\n\n if (remainderData) {\n data = appendUint8Array(remainderData, data);\n this.remainderData = null;\n }\n\n // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)\n const currentChunk = this.getValidChunk(data);\n if (!currentChunk.length) {\n return null;\n }\n\n if (currentIV) {\n iv = currentIV;\n }\n\n let softwareDecrypter = this.softwareDecrypter;\n if (!softwareDecrypter) {\n softwareDecrypter = this.softwareDecrypter = new AESDecryptor();\n }\n softwareDecrypter.expandKey(key);\n\n const result = currentResult;\n\n this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);\n this.currentIV = sliceUint8(currentChunk, -16).buffer;\n\n if (!result) {\n return null;\n }\n return result;\n }\n\n public webCryptoDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer\n ): Promise<ArrayBuffer> {\n const subtle = this.subtle;\n if (this.key !== key || !this.fastAesKey) {\n this.key = key;\n this.fastAesKey = new FastAESKey(subtle, key);\n }\n return this.fastAesKey\n .expandKey()\n .then((aesKey) => {\n // decrypt using web crypto\n if (!subtle) {\n return Promise.reject(new Error('web crypto not initialized'));\n }\n this.logOnce('WebCrypto AES decrypt');\n const crypto = new AESCrypto(subtle, new Uint8Array(iv));\n return crypto.decrypt(data.buffer, aesKey);\n })\n .catch((err) => {\n logger.warn(\n `[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`\n );\n\n return this.onWebCryptoError(data, key, iv);\n });\n }\n\n private onWebCryptoError(data, key, iv): ArrayBuffer | never {\n this.useSoftware = true;\n this.logEnabled = true;\n this.softwareDecrypt(data, key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n return decryptResult.buffer;\n }\n throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');\n }\n\n private getValidChunk(data: Uint8Array): Uint8Array {\n let currentChunk = data;\n const splitPoint = data.length - (data.length % CHUNK_SIZE);\n if (splitPoint !== data.length) {\n currentChunk = sliceUint8(data, 0, splitPoint);\n this.remainderData = sliceUint8(data, splitPoint);\n }\n return currentChunk;\n }\n\n private logOnce(msg: string) {\n if (!this.logEnabled) {\n return;\n }\n logger.log(`[decrypter]: ${msg}`);\n this.logEnabled = false;\n }\n}\n","export default class FastAESKey {\n private subtle: any;\n private key: ArrayBuffer;\n\n constructor(subtle, key) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey() {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, [\n 'encrypt',\n 'decrypt',\n ]);\n }\n}\n","/**\n * AAC demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport * as ID3 from '../demux/id3';\nimport type { HlsEventEmitter } from '../events';\nimport type { HlsConfig } from '../config';\n\nclass AACDemuxer extends BaseAudioDemuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n\n constructor(observer, config) {\n super();\n this.observer = observer;\n this.config = config;\n }\n\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/adts',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'aac',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS\n static probe(data): boolean {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return ADTS.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n track.manifestCodec\n );\n const frame = ADTS.appendFrame(\n track,\n data,\n offset,\n this.basePTS as number,\n this.frameIndex\n );\n if (frame && frame.missing === 0) {\n return frame;\n }\n }\n}\n\nexport default AACDemuxer;\n","/**\n * ADTS parser helper\n * @link https://wiki.multimedia.cx/index.php?title=ADTS\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport type {\n DemuxedAudioTrack,\n AudioFrame,\n AudioSample,\n} from '../types/demuxer';\n\ntype AudioConfig = {\n config: number[];\n samplerate: number;\n channelCount: number;\n codec: string;\n manifestCodec: string;\n};\n\ntype FrameHeader = {\n headerLength: number;\n frameLength: number;\n};\n\nexport function getAudioConfig(\n observer,\n data: Uint8Array,\n offset: number,\n audioCodec: string\n): AudioConfig | void {\n let adtsObjectType: number;\n let adtsExtensionSamplingIndex: number;\n let adtsChannelConfig: number;\n let config: number[];\n const userAgent = navigator.userAgent.toLowerCase();\n const manifestCodec = audioCodec;\n const adtsSamplingRates = [\n 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025,\n 8000, 7350,\n ];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;\n const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;\n if (adtsSamplingIndex > adtsSamplingRates.length - 1) {\n observer.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: true,\n reason: `invalid ADTS sampling index:${adtsSamplingIndex}`,\n });\n return;\n }\n adtsChannelConfig = (data[offset + 2] & 0x01) << 2;\n // byte 3\n adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;\n logger.log(\n `manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`\n );\n // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/i.test(userAgent)) {\n if (adtsSamplingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi/Opera ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if (\n (audioCodec &&\n (audioCodec.indexOf('mp4a.40.29') !== -1 ||\n audioCodec.indexOf('mp4a.40.5') !== -1)) ||\n (!audioCodec && adtsSamplingIndex >= 6)\n ) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (\n (audioCodec &&\n audioCodec.indexOf('mp4a.40.2') !== -1 &&\n ((adtsSamplingIndex >= 6 && adtsChannelConfig === 1) ||\n /vivaldi/i.test(userAgent))) ||\n (!audioCodec && adtsChannelConfig === 1)\n ) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSamplingIndex & 0x0e) >> 1;\n config[1] |= (adtsSamplingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChannelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSamplingIndex\n config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;\n config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n return {\n config,\n samplerate: adtsSamplingRates[adtsSamplingIndex],\n channelCount: adtsChannelConfig,\n codec: 'mp4a.40.' + adtsObjectType,\n manifestCodec,\n };\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nexport function getHeaderLength(data: Uint8Array, offset: number): number {\n return data[offset + 1] & 0x01 ? 7 : 9;\n}\n\nexport function getFullFrameLength(data: Uint8Array, offset: number): number {\n return (\n ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xe0) >>> 5)\n );\n}\n\nexport function canGetFrameLength(data: Uint8Array, offset: number): boolean {\n return offset + 5 < data.length;\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n return (\n canGetFrameLength(data, offset) &&\n isHeaderPattern(data, offset) &&\n getFullFrameLength(data, offset) <= data.length - offset\n );\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (isHeader(data, offset)) {\n // ADTS header Length\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n const frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n\nexport function initTrackConfig(\n track: DemuxedAudioTrack,\n observer: HlsEventEmitter,\n data: Uint8Array,\n offset: number,\n audioCodec: string\n) {\n if (!track.samplerate) {\n const config = getAudioConfig(observer, data, offset, audioCodec);\n if (!config) {\n return;\n }\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(\n `parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`\n );\n }\n}\n\nexport function getFrameDuration(samplerate: number): number {\n return (1024 * 90000) / samplerate;\n}\n\nexport function parseFrameHeader(\n data: Uint8Array,\n offset: number\n): FrameHeader | void {\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength <= data.length) {\n // retrieve frame size\n const frameLength = getFullFrameLength(data, offset) - headerLength;\n if (frameLength > 0) {\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);\n return { headerLength, frameLength };\n }\n }\n}\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number\n): AudioFrame {\n const frameDuration = getFrameDuration(track.samplerate as number);\n const stamp = pts + frameIndex * frameDuration;\n const header = parseFrameHeader(data, offset);\n let unit: Uint8Array;\n if (header) {\n const { frameLength, headerLength } = header;\n const length = headerLength + frameLength;\n const missing = Math.max(0, offset + length - data.length);\n // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);\n if (missing) {\n unit = new Uint8Array(length - headerLength);\n unit.set(data.subarray(offset + headerLength, data.length), 0);\n } else {\n unit = data.subarray(offset + headerLength, offset + length);\n }\n\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n if (!missing) {\n track.samples.push(sample as AudioSample);\n }\n\n return { sample, length, missing };\n }\n // overflow incomplete header\n const length = data.length - offset;\n unit = new Uint8Array(length);\n unit.set(data.subarray(offset, data.length), 0);\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n return { sample, length, missing: -1 };\n}\n","import * as ID3 from '../demux/id3';\nimport {\n DemuxerResult,\n Demuxer,\n DemuxedAudioTrack,\n AudioFrame,\n DemuxedMetadataTrack,\n DemuxedVideoTrack,\n DemuxedUserdataTrack,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport { dummyTrack } from './dummy-demuxed-track';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { sliceUint8 } from '../utils/typed-array';\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: number | 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) {\n this.initPTS = deaultTimestamp;\n this.resetContiguity();\n }\n\n resetContiguity(): void {\n this.basePTS = null;\n this.lastPTS = null;\n this.frameIndex = 0;\n }\n\n canParse(data: Uint8Array, offset: number): boolean {\n return false;\n }\n\n appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number\n ): AudioFrame | void {}\n\n // feed incoming data to the front of the parsing pipeline\n demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n if (this.cachedData) {\n data = appendUint8Array(this.cachedData, data);\n this.cachedData = null;\n }\n\n let id3Data: Uint8Array | undefined = ID3.getID3Data(data, 0);\n let offset = id3Data ? id3Data.length : 0;\n let lastDataIndex;\n const track = this._audioTrack;\n const id3Track = this._id3Track;\n const timestamp = id3Data ? ID3.getTimeStamp(id3Data) : undefined;\n const length = data.length;\n\n if (\n this.basePTS === null ||\n (this.frameIndex === 0 && Number.isFinite(timestamp))\n ) {\n this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);\n this.lastPTS = this.basePTS;\n }\n\n if (this.lastPTS === null) {\n this.lastPTS = this.basePTS;\n }\n\n // more expressive than alternative: id3Data?.length\n if (id3Data && id3Data.length > 0) {\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n }\n\n while (offset < length) {\n if (this.canParse(data, offset)) {\n const frame = this.appendFrame(track, data, offset);\n if (frame) {\n this.frameIndex++;\n this.lastPTS = frame.sample.pts;\n offset += frame.length;\n lastDataIndex = offset;\n } else {\n offset = length;\n }\n } else if (ID3.canParse(data, offset)) {\n // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data\n id3Data = ID3.getID3Data(data, offset)!;\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n offset += id3Data.length;\n lastDataIndex = offset;\n } else {\n offset++;\n }\n if (offset === length && lastDataIndex !== length) {\n const partialData = sliceUint8(data, lastDataIndex);\n if (this.cachedData) {\n this.cachedData = appendUint8Array(this.cachedData, partialData);\n } else {\n this.cachedData = partialData;\n }\n }\n }\n\n return {\n audioTrack: track,\n videoTrack: dummyTrack() as DemuxedVideoTrack,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error(`[${this}] This demuxer does not support Sample-AES decryption`)\n );\n }\n\n flush(timeOffset: number): DemuxerResult {\n // Parse cache in case of remaining frames.\n const cachedData = this.cachedData;\n if (cachedData) {\n this.cachedData = null;\n this.demux(cachedData, 0);\n }\n\n return {\n audioTrack: this._audioTrack,\n videoTrack: dummyTrack() as DemuxedVideoTrack,\n id3Track: this._id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n destroy() {}\n}\n\n/**\n * Initialize PTS\n * <p>\n * use timestamp unless it is undefined, NaN or Infinity\n * </p>\n */\nexport const initPTSFn = (\n timestamp: number | undefined,\n timeOffset: number,\n initPTS: number | null\n): number => {\n if (Number.isFinite(timestamp as number)) {\n return timestamp! * 90;\n }\n return timeOffset * 90000 + (initPTS || 0);\n};\nexport default BaseAudioDemuxer;\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","/**\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 * @param data {Uint8Array} the bytes of a sequence parameter set\n * @return {object} 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","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 {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 header is found\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 {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 footer is found\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 {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {Uint8Array | undefined} - 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 {Uint8Array} data - Block of data containing one or more ID3 tags\n * @return {number | undefined} - The timestamp\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 * @param {ID3 frame} 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 {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags\n * @return {ID3.Frame[]} - Array of ID3 frame objects\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 if (!decoder && typeof self.TextDecoder !== 'undefined') {\n decoder = new self.TextDecoder('utf-8');\n }\n\n return decoder;\n}\n","/**\n * MP3 demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport * as MpegAudio from './mpegaudio';\n\nclass MP3Demuxer extends BaseAudioDemuxer {\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/mpeg',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'mp3',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n static probe(data): boolean {\n if (!data) {\n return false;\n }\n\n // check if data contains ID3 timestamp and MPEG sync word\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return MpegAudio.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n if (this.basePTS === null) {\n return;\n }\n return MpegAudio.appendFrame(\n track,\n data,\n offset,\n this.basePTS,\n this.frameIndex\n );\n }\n}\n\nexport default MP3Demuxer;\n","/**\n * MP4 demuxer\n */\nimport {\n Demuxer,\n DemuxerResult,\n PassthroughTrack,\n DemuxedAudioTrack,\n DemuxedUserdataTrack,\n DemuxedMetadataTrack,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport {\n findBox,\n segmentValidRange,\n appendUint8Array,\n parseEmsg,\n parseSamples,\n parseInitSegment,\n RemuxerTrackIdConfig,\n} from '../utils/mp4-tools';\nimport { dummyTrack } from './dummy-demuxed-track';\nimport type { HlsEventEmitter } from '../events';\nimport type { HlsConfig } from '../config';\n\nconst emsgSchemePattern = /\\/emsg[-/]ID3/i;\n\nclass MP4Demuxer implements Demuxer {\n private remainderData: Uint8Array | null = null;\n private timeOffset: number = 0;\n private config: HlsConfig;\n private videoTrack?: PassthroughTrack;\n private audioTrack?: DemuxedAudioTrack;\n private id3Track?: DemuxedMetadataTrack;\n private txtTrack?: DemuxedUserdataTrack;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig) {\n this.config = config;\n }\n\n public resetTimeStamp() {}\n\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n ) {\n const videoTrack = (this.videoTrack = dummyTrack(\n 'video',\n 1\n ) as PassthroughTrack);\n const audioTrack = (this.audioTrack = dummyTrack(\n 'audio',\n 1\n ) as DemuxedAudioTrack);\n const captionTrack = (this.txtTrack = dummyTrack(\n 'text',\n 1\n ) as DemuxedUserdataTrack);\n\n this.id3Track = dummyTrack('id3', 1) as DemuxedMetadataTrack;\n this.timeOffset = 0;\n\n if (!initSegment || !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\n static probe(data: Uint8Array) {\n // ensure we find a moof box in the first 16 kB\n data = data.length > 16384 ? data.subarray(0, 16384) : data;\n return findBox(data, ['moof']).length > 0;\n }\n\n public demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n this.timeOffset = timeOffset;\n // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter\n let videoSamples = data;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n if (this.config.progressive) {\n // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.\n // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee\n // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.\n if (this.remainderData) {\n videoSamples = appendUint8Array(this.remainderData, data);\n }\n const segmentedData = segmentValidRange(videoSamples);\n this.remainderData = segmentedData.remainder;\n videoTrack.samples = segmentedData.valid || new Uint8Array();\n } else {\n videoTrack.samples = videoSamples;\n }\n\n const id3Track = this.extractID3Track(videoTrack, timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: this.audioTrack as DemuxedAudioTrack,\n id3Track,\n textTrack: this.txtTrack as DemuxedUserdataTrack,\n };\n }\n\n public flush() {\n const timeOffset = this.timeOffset;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n videoTrack.samples = this.remainderData || new Uint8Array();\n this.remainderData = null;\n\n const id3Track = this.extractID3Track(videoTrack, this.timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: dummyTrack() as DemuxedAudioTrack,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n private extractID3Track(\n videoTrack: PassthroughTrack,\n timeOffset: number\n ): DemuxedMetadataTrack {\n const id3Track = this.id3Track as DemuxedMetadataTrack;\n if (videoTrack.samples.length) {\n const emsgs = findBox(videoTrack.samples, ['emsg']);\n if (emsgs) {\n emsgs.forEach((data: Uint8Array) => {\n const emsgInfo = parseEmsg(data);\n if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {\n const pts = Number.isFinite(emsgInfo.presentationTime)\n ? emsgInfo.presentationTime! / emsgInfo.timeScale\n : timeOffset +\n emsgInfo.presentationTimeDelta! / emsgInfo.timeScale;\n let duration =\n emsgInfo.eventDuration === 0xffffffff\n ? Number.POSITIVE_INFINITY\n : emsgInfo.eventDuration / emsgInfo.timeScale;\n // Safari takes anything <= 0.001 seconds and maps it to Infinity\n if (duration <= 0.001) {\n duration = Number.POSITIVE_INFINITY;\n }\n const payload = emsgInfo.payload;\n id3Track.samples.push({\n data: payload,\n len: payload.byteLength,\n dts: pts,\n pts: pts,\n type: MetadataSchema.emsg,\n duration: duration,\n });\n }\n });\n }\n }\n return id3Track;\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error('The MP4 demuxer does not support SAMPLE-AES decryption')\n );\n }\n\n destroy() {}\n}\n\nexport default MP4Demuxer;\n","/**\n * MPEG parser helper\n */\nimport { DemuxedAudioTrack } from '../types/demuxer';\n\nlet chromeVersion: number | null = null;\n\nconst BitratesMap = [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56,\n 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80,\n 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144,\n 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144,\n 160,\n];\n\nconst SamplingRateMap = [\n 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000,\n];\n\nconst SamplesCoefficients = [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0, // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n];\n\nconst BytesInSlot = [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4, // Layer1\n];\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number\n) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return;\n }\n\n const header = parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n const frameDuration = (header.samplesPerFrame * 90000) / header.sampleRate;\n const stamp = pts + frameIndex * frameDuration;\n const sample = {\n unit: data.subarray(offset, offset + header.frameLength),\n pts: stamp,\n dts: stamp,\n };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n\n return { sample, length: header.frameLength, missing: 0 };\n }\n}\n\nexport function parseHeader(data: Uint8Array, offset: number) {\n const mpegVersion = (data[offset + 1] >> 3) & 3;\n const mpegLayer = (data[offset + 1] >> 1) & 3;\n const bitRateIndex = (data[offset + 2] >> 4) & 15;\n const sampleRateIndex = (data[offset + 2] >> 2) & 3;\n if (\n mpegVersion !== 1 &&\n bitRateIndex !== 0 &&\n bitRateIndex !== 15 &&\n sampleRateIndex !== 3\n ) {\n const paddingBit = (data[offset + 2] >> 1) & 1;\n const channelMode = data[offset + 3] >> 6;\n const columnInBitrates =\n mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;\n const bitRate =\n BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;\n const columnInSampleRates =\n mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;\n const sampleRate =\n SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];\n const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];\n const bytesInSlot = BytesInSlot[mpegLayer];\n const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n const frameLength =\n Math.floor((sampleCoefficient * bitRate) / sampleRate + paddingBit) *\n bytesInSlot;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n const needChromeFix = !!chromeVersion && chromeVersion <= 87;\n\n if (\n needChromeFix &&\n mpegLayer === 2 &&\n bitRate >= 224000 &&\n channelMode === 0\n ) {\n // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)\n data[offset + 3] = data[offset + 3] | 0x80;\n }\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\n }\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return (\n data[offset] === 0xff &&\n (data[offset + 1] & 0xe0) === 0xe0 &&\n (data[offset + 1] & 0x06) !== 0x00\n );\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n const headerSize = 4;\n\n return isHeaderPattern(data, offset) && headerSize <= data.length - offset;\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n // MPEG header Length\n const headerLength = 4;\n // MPEG frame Length\n const header = parseHeader(data, offset);\n let frameLength = headerLength;\n if (header?.frameLength) {\n frameLength = header.frameLength;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n","/**\n * SAMPLE-AES decrypter\n */\n\nimport { HlsConfig } from '../config';\nimport Decrypter from '../crypt/decrypter';\nimport { HlsEventEmitter } from '../events';\nimport type {\n AudioSample,\n AvcSample,\n AvcSampleUnit,\n DemuxedVideoTrack,\n KeyData,\n} from '../types/demuxer';\nimport { discardEPB } from '../utils/mp4-tools';\n\nclass SampleAesDecrypter {\n private keyData: KeyData;\n private decrypter: Decrypter;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig, keyData: KeyData) {\n this.keyData = keyData;\n this.decrypter = new Decrypter(config, {\n removePKCS7Padding: false,\n });\n }\n\n decryptBuffer(encryptedData: Uint8Array | ArrayBuffer): Promise<ArrayBuffer> {\n return this.decrypter.decrypt(\n encryptedData,\n this.keyData.key.buffer,\n this.keyData.iv.buffer\n );\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n private decryptAacSample(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void\n ) {\n const curUnit = samples[sampleIndex].unit;\n if (curUnit.length <= 16) {\n // No encrypted portion in this sample (first 16 bytes is not\n // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),\n return;\n }\n const encryptedData = curUnit.subarray(\n 16,\n curUnit.length - (curUnit.length % 16)\n );\n const encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length\n );\n\n this.decryptBuffer(encryptedBuffer).then((decryptedBuffer: ArrayBuffer) => {\n const decryptedData = new Uint8Array(decryptedBuffer);\n curUnit.set(decryptedData, 16);\n\n if (!this.decrypter.isSync()) {\n this.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void\n ) {\n for (; ; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n this.decryptAacSample(samples, sampleIndex, callback);\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData(decodedData: Uint8Array) {\n const encryptedDataLen =\n Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n const encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (\n let inputPos = 32;\n inputPos < decodedData.length - 16;\n inputPos += 160, outputPos += 16\n ) {\n encryptedData.set(\n decodedData.subarray(inputPos, inputPos + 16),\n outputPos\n );\n }\n\n return encryptedData;\n }\n\n getAvcDecryptedUnit(\n decodedData: Uint8Array,\n decryptedData: ArrayLike<number> | ArrayBuffer | SharedArrayBuffer\n ) {\n const uint8DecryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (\n let outputPos = 32;\n outputPos < decodedData.length - 16;\n outputPos += 160, inputPos += 16\n ) {\n decodedData.set(\n uint8DecryptedData.subarray(inputPos, inputPos + 16),\n outputPos\n );\n }\n\n return decodedData;\n }\n\n decryptAvcSample(\n samples: AvcSample[],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void,\n curUnit: AvcSampleUnit\n ) {\n const decodedData = discardEPB(curUnit.data);\n const encryptedData = this.getAvcEncryptedData(decodedData);\n\n this.decryptBuffer(encryptedData.buffer).then(\n (decryptedBuffer: ArrayBuffer) => {\n curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);\n\n if (!this.decrypter.isSync()) {\n this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n }\n );\n }\n\n decryptAvcSamples(\n samples: DemuxedVideoTrack['samples'],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void\n ) {\n if (samples instanceof Uint8Array) {\n throw new Error('Cannot decrypt samples of type Uint8Array');\n }\n\n for (; ; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n const curUnits = samples[sampleIndex].units;\n for (; ; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n const curUnit = curUnits[unitIndex];\n if (\n curUnit.data.length <= 48 ||\n (curUnit.type !== 1 && curUnit.type !== 5)\n ) {\n continue;\n }\n\n this.decryptAvcSample(\n samples,\n sampleIndex,\n unitIndex,\n callback,\n curUnit\n );\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n }\n}\n\nexport default SampleAesDecrypter;\n","import work from './webworkify-webpack';\nimport { Events } from '../events';\nimport Transmuxer, {\n TransmuxConfig,\n TransmuxState,\n isPromise,\n} from '../demux/transmuxer';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { EventEmitter } from 'eventemitter3';\nimport { Fragment, Part } from '../loader/fragment';\nimport type { ChunkMetadata, TransmuxerResult } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { HlsEventEmitter } from '../events';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { TypeSupported } from './tsdemuxer';\n\nconst MediaSource = getMediaSource() || { isTypeSupported: () => false };\n\nexport default class TransmuxerInterface {\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 worker: any;\n private onwmsg?: Function;\n private transmuxer: Transmuxer | null = null;\n private onTransmuxComplete: (transmuxResult: TransmuxerResult) => void;\n private onFlush: (chunkMeta: ChunkMetadata) => void;\n\n constructor(\n hls: Hls,\n id: PlaylistLevelType,\n onTransmuxComplete: (transmuxResult: TransmuxerResult) => void,\n onFlush: (chunkMeta: ChunkMetadata) => void\n ) {\n const config = hls.config;\n this.hls = hls;\n this.id = id;\n this.useWorker = !!config.enableWorker;\n this.onTransmuxComplete = onTransmuxComplete;\n this.onFlush = onFlush;\n\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n this.hls.trigger(ev, data);\n };\n\n // forward events to main thread\n this.observer = new EventEmitter() as HlsEventEmitter;\n this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n this.observer.on(Events.ERROR, forwardMessage);\n\n const typeSupported: TypeSupported = {\n mp4: MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\n if (this.useWorker && typeof Worker !== 'undefined') {\n logger.log('demuxing in webworker');\n let worker;\n try {\n worker = this.worker = work(\n require.resolve('../demux/transmuxer-worker.ts')\n );\n this.onwmsg = this.onWorkerMessage.bind(this);\n worker.addEventListener('message', this.onwmsg);\n worker.onerror = (event) => {\n this.useWorker = false;\n logger.warn('Exception in webworker, 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: new Error(\n `${event.message} (${event.filename}:${event.lineno})`\n ),\n });\n };\n worker.postMessage({\n cmd: 'init',\n typeSupported: typeSupported,\n vendor: vendor,\n id: id,\n config: JSON.stringify(config),\n });\n } catch (err) {\n logger.warn('Error in worker:', err);\n logger.error(\n 'Error while initializing DemuxerWorker, fallback to inline'\n );\n if (worker) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(worker.objectURL);\n }\n this.transmuxer = new Transmuxer(\n this.observer,\n typeSupported,\n config,\n vendor,\n id\n );\n this.worker = null;\n }\n } else {\n this.transmuxer = new Transmuxer(\n this.observer,\n typeSupported,\n config,\n vendor,\n id\n );\n }\n }\n\n destroy(): void {\n const w = this.worker;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.worker = null;\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?: number\n ): void {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer, worker } = 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 (worker) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n 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 transmuxResult.then((data) => {\n this.handleTransmuxComplete(data);\n });\n } else {\n this.handleTransmuxComplete(transmuxResult as TransmuxerResult);\n }\n }\n }\n\n flush(chunkMeta: ChunkMetadata) {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer, worker } = this;\n if (worker) {\n worker.postMessage({\n cmd: 'flush',\n chunkMeta,\n });\n } else if (transmuxer) {\n const transmuxResult = transmuxer.flush(chunkMeta);\n if (isPromise(transmuxResult)) {\n transmuxResult.then((data) => {\n this.handleFlushResult(data, chunkMeta);\n });\n } else {\n this.handleFlushResult(\n transmuxResult as Array<TransmuxerResult>,\n chunkMeta\n );\n }\n }\n }\n\n private handleFlushResult(\n results: Array<TransmuxerResult>,\n chunkMeta: ChunkMetadata\n ) {\n results.forEach((result) => {\n this.handleTransmuxComplete(result);\n });\n this.onFlush(chunkMeta);\n }\n\n private onWorkerMessage(ev: any): void {\n const data = ev.data;\n const hls = this.hls;\n switch (data.event) {\n case 'init': {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(this.worker.objectURL);\n break;\n }\n\n case 'transmuxComplete': {\n this.handleTransmuxComplete(data.data);\n break;\n }\n\n case 'flush': {\n this.onFlush(data.data);\n break;\n }\n\n // pass logs from the worker thread to the main logger\n case 'workerLog':\n if (logger[data.data.logType]) {\n logger[data.data.logType](data.data.message);\n }\n break;\n\n default: {\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event, data.data);\n break;\n }\n }\n }\n\n private configureTransmuxer(config: TransmuxConfig) {\n const { worker, transmuxer } = this;\n if (worker) {\n 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","import Transmuxer, { isPromise } from '../demux/transmuxer';\nimport { Events } from '../events';\nimport { ILogFunction, enableLogs, logger } from '../utils/logger';\nimport { EventEmitter } from 'eventemitter3';\nimport type { RemuxedTrack, RemuxerResult } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\n\nexport default function TransmuxerWorker(self) {\n const observer = new EventEmitter();\n const forwardMessage = (ev, data) => {\n self.postMessage({ event: ev, data: data });\n };\n\n // forward events to main thread\n observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n observer.on(Events.ERROR, forwardMessage);\n\n // forward logger events to main thread\n const forwardWorkerLogs = () => {\n for (const logFn in logger) {\n const func: ILogFunction = (message?) => {\n forwardMessage('workerLog', {\n logType: logFn,\n message,\n });\n };\n\n logger[logFn] = func;\n }\n };\n\n self.addEventListener('message', (ev) => {\n const data = ev.data;\n switch (data.cmd) {\n case 'init': {\n const config = JSON.parse(data.config);\n self.transmuxer = new Transmuxer(\n observer,\n data.typeSupported,\n config,\n data.vendor,\n data.id\n );\n enableLogs(config.debug, data.id);\n forwardWorkerLogs();\n forwardMessage('init', null);\n break;\n }\n case 'configure': {\n self.transmuxer.configure(data.config);\n break;\n }\n case 'demux': {\n const transmuxResult: TransmuxerResult | Promise<TransmuxerResult> =\n self.transmuxer.push(\n data.data,\n data.decryptdata,\n data.chunkMeta,\n data.state\n );\n if (isPromise(transmuxResult)) {\n transmuxResult.then((data) => {\n emitTransmuxComplete(self, data);\n });\n } else {\n emitTransmuxComplete(self, transmuxResult);\n }\n break;\n }\n case 'flush': {\n const id = data.chunkMeta;\n const transmuxResult = self.transmuxer.flush(id);\n if (isPromise(transmuxResult)) {\n transmuxResult.then((results: Array<TransmuxerResult>) => {\n handleFlushResult(self, results as Array<TransmuxerResult>, id);\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 type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer, { TypeSupported } from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\nimport { logger } from '../utils/logger';\nimport type { Demuxer, DemuxerResult, KeyData } from '../types/demuxer';\nimport type { Remuxer } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\nimport type { HlsConfig } from '../config';\nimport type { LevelKey } from '../loader/level-key';\nimport type { PlaylistLevelType } from '../types/loader';\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 = self.Date.now;\n}\n\ntype MuxConfig =\n | { demux: typeof TSDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof MP4Demuxer; remux: typeof PassThroughRemuxer }\n | { demux: typeof AACDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof MP3Demuxer; remux: typeof MP4Remuxer };\n\nconst muxConfig: MuxConfig[] = [\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer },\n];\n\nexport default class Transmuxer {\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: LevelKey | 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 // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe\n if (discontinuity || trackSwitch || initSegmentChange) {\n this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);\n }\n\n if (discontinuity || initSegmentChange) {\n this.resetInitialTimestamp(defaultInitPts);\n }\n\n if (!contiguous) {\n this.resetContiguity();\n }\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 const decryptedData = decrypter.softwareDecrypt(\n uintData,\n keyData.key.buffer,\n keyData.iv.buffer\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 if (this.needsProbing(uintData, discontinuity, trackSwitch)) {\n this.configureTransmuxer(uintData, transmuxConfig);\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 this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: true,\n reason: 'no demux matching with content found',\n });\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: number | undefined) {\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 ) {\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(initSegmentData, audioCodec, videoCodec);\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(\n data: Uint8Array,\n transmuxConfig: TransmuxConfig\n ) {\n const { config, observer, typeSupported, vendor } = this;\n const {\n audioCodec,\n defaultInitPts,\n duration,\n initSegmentData,\n videoCodec,\n } = transmuxConfig;\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 // If probing previous configs fail, use mp4 passthrough\n logger.warn(\n 'Failed to find demuxer by probing frag, treating as mp4 passthrough'\n );\n mux = { demux: MP4Demuxer, remux: PassThroughRemuxer };\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 // Ensure that muxers are always initialized with an initSegment\n this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);\n this.resetInitialTimestamp(defaultInitPts);\n }\n\n private needsProbing(\n data: Uint8Array,\n discontinuity: boolean,\n trackSwitch: boolean\n ): 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: LevelKey | null\n): KeyData | null {\n let encryptionType: KeyData | null = null;\n if (\n data.byteLength > 0 &&\n decryptData != null &&\n decryptData.key != null &&\n decryptData.iv !== null &&\n decryptData.method != null\n ) {\n encryptionType = decryptData as KeyData;\n }\n return encryptionType;\n}\n\nconst emptyResult = (chunkMeta): TransmuxerResult => ({\n remuxResult: {},\n chunkMeta,\n});\n\nexport function isPromise<T>(p: Promise<T> | any): p is Promise<T> {\n return 'then' in p && p.then instanceof Function;\n}\n\nexport class TransmuxConfig {\n public audioCodec?: string;\n public videoCodec?: string;\n public initSegmentData?: Uint8Array;\n public duration: number;\n public defaultInitPts?: number;\n\n constructor(\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n initSegmentData: Uint8Array | undefined,\n duration: number,\n defaultInitPts?: number\n ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.initSegmentData = initSegmentData;\n this.duration = duration;\n this.defaultInitPts = defaultInitPts;\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","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n */\n\nimport * as ADTS from './adts';\nimport * as MpegAudio from './mpegaudio';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\nimport { Events } from '../events';\nimport {\n appendUint8Array,\n parseSEIMessageFromNALu,\n RemuxerTrackIdConfig,\n} from '../utils/mp4-tools';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport type { HlsConfig } from '../config';\nimport type { HlsEventEmitter } from '../events';\nimport {\n DemuxedAvcTrack,\n DemuxedAudioTrack,\n DemuxedTrack,\n Demuxer,\n DemuxerResult,\n AvcSample,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n ElementaryStreamData,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport { AudioFrame } from '../types/demuxer';\n\ntype ParsedTimestamp = {\n pts?: number;\n dts?: number;\n};\n\ntype PES = ParsedTimestamp & {\n data: Uint8Array;\n len: number;\n};\n\ntype ParsedAvcSample = ParsedTimestamp & Omit<AvcSample, 'pts' | 'dts'>;\n\nexport interface TypeSupported {\n mpeg: boolean;\n mp3: boolean;\n mp4: boolean;\n}\n\nconst PACKET_LENGTH = 188;\n\nclass TSDemuxer implements Demuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n private typeSupported: TypeSupported;\n\n private sampleAes: SampleAesDecrypter | null = null;\n private pmtParsed: boolean = false;\n private audioCodec?: string;\n private videoCodec?: string;\n private _duration: number = 0;\n private _pmtId: number = -1;\n\n private _avcTrack?: DemuxedAvcTrack;\n private _audioTrack?: DemuxedAudioTrack;\n private _id3Track?: DemuxedMetadataTrack;\n private _txtTrack?: DemuxedUserdataTrack;\n private aacOverFlow: AudioFrame | null = null;\n private avcSample: ParsedAvcSample | null = null;\n private remainderData: Uint8Array | null = null;\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported: TypeSupported\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n }\n\n static probe(data: Uint8Array) {\n const syncOffset = TSDemuxer.syncOffset(data);\n if (syncOffset > 0) {\n logger.warn(\n `MPEG2-TS detected but first sync word found @ offset ${syncOffset}`\n );\n }\n return syncOffset !== -1;\n }\n\n static syncOffset(data: Uint8Array) {\n const scanwindow =\n Math.min(PACKET_LENGTH * 5, data.length - PACKET_LENGTH * 2) + 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 if (data[i] === 0x47 && data[i + PACKET_LENGTH] === 0x47) {\n return i;\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 * @param type 'audio' | 'video' | 'id3' | 'text'\n * @param duration\n * @return TSDemuxer's internal track model\n */\n static createTrack(\n type: 'audio' | 'video' | 'id3' | 'text',\n duration?: number\n ): DemuxedTrack {\n return {\n container:\n type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n duration: type === 'audio' ? duration : undefined,\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n */\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string,\n videoCodec: string,\n trackDuration: number\n ) {\n this.pmtParsed = false;\n this._pmtId = -1;\n\n this._avcTrack = TSDemuxer.createTrack('video') as DemuxedAvcTrack;\n this._audioTrack = TSDemuxer.createTrack(\n 'audio',\n trackDuration\n ) as DemuxedAudioTrack;\n this._id3Track = TSDemuxer.createTrack('id3') as DemuxedMetadataTrack;\n this._txtTrack = TSDemuxer.createTrack('text') as DemuxedUserdataTrack;\n this._audioTrack.segmentCodec = 'aac';\n\n // flush any partial content\n this.aacOverFlow = null;\n this.avcSample = null;\n this.remainderData = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = trackDuration;\n }\n\n public resetTimeStamp() {}\n\n public resetContiguity(): void {\n const { _audioTrack, _avcTrack, _id3Track } = this;\n if (_audioTrack) {\n _audioTrack.pesData = null;\n }\n if (_avcTrack) {\n _avcTrack.pesData = null;\n }\n if (_id3Track) {\n _id3Track.pesData = null;\n }\n this.aacOverFlow = null;\n this.avcSample = null;\n this.remainderData = null;\n }\n\n public demux(\n data: Uint8Array,\n timeOffset: number,\n isSampleAes = false,\n flush = false\n ): DemuxerResult {\n if (!isSampleAes) {\n this.sampleAes = null;\n }\n\n let pes: PES | null;\n\n const videoTrack = this._avcTrack as DemuxedAvcTrack;\n const audioTrack = this._audioTrack as DemuxedAudioTrack;\n const id3Track = this._id3Track as DemuxedMetadataTrack;\n const textTrack = this._txtTrack as DemuxedUserdataTrack;\n\n let avcId = videoTrack.pid;\n let avcData = videoTrack.pesData;\n let audioId = audioTrack.pid;\n let id3Id = id3Track.pid;\n let audioData = audioTrack.pesData;\n let id3Data = id3Track.pesData;\n let unknownPID: number | null = null;\n let pmtParsed = this.pmtParsed;\n let pmtId = this._pmtId;\n\n let len = data.length;\n if (this.remainderData) {\n data = appendUint8Array(this.remainderData, data);\n len = data.length;\n this.remainderData = null;\n }\n\n if (len < PACKET_LENGTH && !flush) {\n this.remainderData = data;\n return {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n }\n\n const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));\n len -= (len - syncOffset) % PACKET_LENGTH;\n if (len < data.byteLength && !flush) {\n this.remainderData = new Uint8Array(\n data.buffer,\n len,\n data.buffer.byteLength - len\n );\n }\n\n // loop through TS packets\n let tsPacketErrors = 0;\n for (let start = syncOffset; start < len; start += PACKET_LENGTH) {\n if (data[start] === 0x47) {\n const stt = !!(data[start + 1] & 0x40);\n // pid is a 13-bit field starting at the last bit of TS[1]\n const pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n const atf = (data[start + 3] & 0x30) >> 4;\n\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n let offset: number;\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === start + PACKET_LENGTH) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\n this.parseAVCPES(videoTrack, textTrack, pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n avcData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n }\n }\n audioData = { data: [], size: 0 };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n audioData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case id3Id:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n }\n\n id3Data = { data: [], size: 0 };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));\n id3Data.size += start + PACKET_LENGTH - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId: {\n if (stt) {\n offset += data[offset] + 1;\n }\n\n const parsedPIDs = parsePMT(\n data,\n offset,\n this.typeSupported,\n isSampleAes\n );\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n avcId = parsedPIDs.avc;\n if (avcId > 0) {\n videoTrack.pid = avcId;\n }\n\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.pid = audioId;\n audioTrack.segmentCodec = parsedPIDs.segmentCodec;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.pid = id3Id;\n }\n\n if (unknownPID !== null && !pmtParsed) {\n logger.log(`unknown PID '${unknownPID}' in TS found`);\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 17:\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 this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n reason: `Found ${tsPacketErrors} TS packet/s that do not start with 0x47`,\n });\n }\n\n videoTrack.pesData = avcData;\n audioTrack.pesData = audioData;\n id3Track.pesData = id3Data;\n\n const demuxResult: DemuxerResult = {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n\n if (flush) {\n this.extractRemainingSamples(demuxResult);\n }\n\n return demuxResult;\n }\n\n public flush(): DemuxerResult | Promise<DemuxerResult> {\n const { remainderData } = this;\n this.remainderData = null;\n let result: DemuxerResult;\n if (remainderData) {\n result = this.demux(remainderData, -1, false, true);\n } else {\n result = {\n videoTrack: this._avcTrack as DemuxedAvcTrack,\n audioTrack: this._audioTrack as DemuxedAudioTrack,\n id3Track: this._id3Track as DemuxedMetadataTrack,\n textTrack: this._txtTrack as DemuxedUserdataTrack,\n };\n }\n this.extractRemainingSamples(result);\n if (this.sampleAes) {\n return this.decrypt(result, this.sampleAes);\n }\n return result;\n }\n\n private extractRemainingSamples(demuxResult: DemuxerResult) {\n const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult;\n const avcData = videoTrack.pesData;\n const audioData = audioTrack.pesData;\n const id3Data = id3Track.pesData;\n // try to parse last PES packets\n let pes: PES | null;\n if (avcData && (pes = parsePES(avcData))) {\n this.parseAVCPES(\n videoTrack as DemuxedAvcTrack,\n textTrack as DemuxedUserdataTrack,\n pes,\n true\n );\n videoTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n videoTrack.pesData = avcData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n }\n audioTrack.pesData = null;\n } else {\n if (audioData?.size) {\n logger.log(\n 'last AAC PES packet truncated,might overlap between fragments'\n );\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n }\n\n public demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number\n ): Promise<DemuxerResult> {\n const demuxResult = this.demux(\n data,\n timeOffset,\n true,\n !this.config.progressive\n );\n const sampleAes = (this.sampleAes = new SampleAesDecrypter(\n this.observer,\n this.config,\n keyData\n ));\n return this.decrypt(demuxResult, sampleAes);\n }\n\n private decrypt(\n demuxResult: DemuxerResult,\n sampleAes: SampleAesDecrypter\n ): Promise<DemuxerResult> {\n return new Promise((resolve) => {\n const { audioTrack, videoTrack } = demuxResult;\n if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {\n sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {\n if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n } else {\n resolve(demuxResult);\n }\n });\n } else if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n }\n });\n }\n\n public destroy() {\n this._duration = 0;\n }\n\n private parseAVCPES(\n track: DemuxedAvcTrack,\n textTrack: DemuxedUserdataTrack,\n pes: PES,\n last: boolean\n ) {\n const units = this.parseAVCNALu(track, pes.data);\n const debug = false;\n let avcSample = this.avcSample;\n let push: boolean;\n let spsfound = false;\n // free pes.data to save up some memory\n (pes as any).data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (avcSample && units.length && !track.audFound) {\n pushAccessUnit(avcSample, track);\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');\n }\n\n units.forEach((unit) => {\n switch (unit.type) {\n // NDR\n case 1: {\n push = true;\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(\n true,\n pes.pts,\n pes.dts,\n ''\n );\n }\n\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n 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 avcSample.key = true;\n }\n }\n break;\n // IDR\n }\n case 5:\n push = true;\n // handle PES not starting with AUD\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(\n true,\n pes.pts,\n pes.dts,\n ''\n );\n }\n\n if (debug) {\n avcSample.debug += 'IDR ';\n }\n\n avcSample.key = true;\n avcSample.frame = true;\n break;\n // SEI\n case 6: {\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'SEI ';\n }\n parseSEIMessageFromNALu(\n unit.data,\n 1,\n pes.pts as number,\n textTrack.samples\n );\n break;\n // SPS\n }\n case 7:\n push = true;\n spsfound = true;\n if (debug && avcSample) {\n avcSample.debug += 'SPS ';\n }\n\n if (!track.sps) {\n const expGolombDecoder = new ExpGolomb(unit.data);\n const config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.\n track.sps = [unit.data] as any;\n track.duration = this._duration;\n const codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (let i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n // PPS\n case 8:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n\n if (!track.pps) {\n // TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.\n track.pps = [unit.data] as any;\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccessUnit(avcSample, track);\n }\n\n avcSample = this.avcSample = createAVCSample(\n false,\n pes.pts,\n pes.dts,\n debug ? 'AUD ' : ''\n );\n break;\n // Filler Data\n case 12:\n push = true;\n break;\n default:\n push = false;\n if (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (avcSample && push) {\n const units = avcSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccessUnit(avcSample, track);\n this.avcSample = null;\n }\n }\n\n private getLastNalUnit(samples: AvcSample[]) {\n let avcSample = this.avcSample;\n let lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n avcSample = samples[samples.length - 1];\n }\n if (avcSample?.units) {\n const units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n private parseAVCNALu(\n track: DemuxedAvcTrack,\n array: Uint8Array\n ): Array<{\n data: Uint8Array;\n type: number;\n state?: number;\n }> {\n const len = array.byteLength;\n let state = track.naluState || 0;\n const lastState = state;\n const units = [] as Array<{\n data: Uint8Array;\n type: number;\n state?: number;\n }>;\n let i = 0;\n let value;\n let overflow;\n let unitType;\n let lastUnitStart = -1;\n let lastUnitType: number = 0;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n if (lastUnitStart >= 0) {\n const unit = {\n data: array.subarray(lastUnitStart, i - state - 1),\n type: lastUnitType,\n };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n if (lastState && i <= 4 - lastState) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(\n 0,\n lastUnit.data.byteLength - lastState\n );\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n overflow = i - state - 1;\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n const tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\n lastUnit.state = 0;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n const unit = {\n data: array.subarray(lastUnitStart, len),\n type: lastUnitType,\n state: state,\n };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n const tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\n }\n\n private parseAACPES(track: DemuxedAudioTrack, pes: PES) {\n let startOffset = 0;\n const aacOverFlow = this.aacOverFlow;\n let data = pes.data;\n if (aacOverFlow) {\n this.aacOverFlow = null;\n const frameMissingBytes = aacOverFlow.missing;\n const sampleLength = aacOverFlow.sample.unit.byteLength;\n // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);\n if (frameMissingBytes === -1) {\n const tmp = new Uint8Array(sampleLength + data.byteLength);\n tmp.set(aacOverFlow.sample.unit, 0);\n tmp.set(data, sampleLength);\n data = tmp;\n } else {\n const frameOverflowBytes = sampleLength - frameMissingBytes;\n aacOverFlow.sample.unit.set(\n data.subarray(0, frameMissingBytes),\n frameOverflowBytes\n );\n track.samples.push(aacOverFlow.sample);\n startOffset = aacOverFlow.missing;\n }\n }\n // look for ADTS header (0xFFFx)\n let offset: number;\n let len: number;\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset !== startOffset) {\n let reason;\n let fatal;\n if (offset < len - 1) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n fatal = false;\n } else {\n reason = 'no ADTS header found in AAC PES';\n fatal = true;\n }\n logger.warn(`parsing error:${reason}`);\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal,\n reason,\n });\n if (fatal) {\n return;\n }\n }\n\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n this.audioCodec as string\n );\n\n let pts: number;\n if (pes.pts !== undefined) {\n pts = pes.pts;\n } else if (aacOverFlow) {\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n const frameDuration = ADTS.getFrameDuration(track.samplerate as number);\n pts = aacOverFlow.sample.pts + frameDuration;\n } else {\n logger.warn('[tsdemuxer]: AAC PES unknown PTS');\n return;\n }\n\n // scan for aac samples\n let frameIndex = 0;\n let frame;\n while (offset < len) {\n frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n offset += frame.length;\n if (!frame.missing) {\n frameIndex++;\n for (; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n } else {\n this.aacOverFlow = frame;\n break;\n }\n }\n }\n\n private parseMPEGPES(track: DemuxedAudioTrack, pes: PES) {\n const data = pes.data;\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n const pts = pes.pts;\n if (pts === undefined) {\n logger.warn('[tsdemuxer]: MPEG PES unknown PTS');\n return;\n }\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n const frame = MpegAudio.appendFrame(\n track,\n data,\n offset,\n pts,\n frameIndex\n );\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n\n private parseID3PES(id3Track: DemuxedMetadataTrack, pes: PES) {\n if (pes.pts === undefined) {\n logger.warn('[tsdemuxer]: ID3 PES unknown PTS');\n return;\n }\n const id3Sample = Object.assign({}, pes as Required<PES>, {\n type: this._avcTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n id3Track.samples.push(id3Sample);\n }\n}\n\nfunction createAVCSample(\n key: boolean,\n pts: number | undefined,\n dts: number | undefined,\n debug: string\n): ParsedAvcSample {\n return {\n key,\n frame: false,\n pts,\n dts,\n units: [],\n debug,\n length: 0,\n };\n}\n\nfunction parsePAT(data, offset) {\n // skip the PSI header and parse the first PMT entry\n return ((data[offset + 10] & 0x1f) << 8) | data[offset + 11];\n // logger.log('PMT PID:' + this._pmtId);\n}\n\nfunction parsePMT(data, offset, typeSupported, isSampleAes) {\n const result = { audio: -1, avc: -1, id3: -1, segmentCodec: 'aac' };\n const sectionLength = ((data[offset + 1] & 0x0f) << 8) | data[offset + 2];\n const tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n const programInfoLength =\n ((data[offset + 10] & 0x0f) << 8) | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n const pid = ((data[offset + 1] & 0x1f) << 8) | data[offset + 2];\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logger.log(\n 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream'\n );\n break;\n }\n /* falls through */\n case 0x0f: // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n // logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logger.log(\n 'H.264 with AES-128-CBC slice encryption found in unencrypted stream'\n );\n break;\n }\n /* falls through */\n case 0x1b: // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n // logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (typeSupported.mpeg !== true && typeSupported.mp3 !== true) {\n logger.log('MPEG audio found, not supported in this browser');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.segmentCodec = 'mp3';\n }\n break;\n\n case 0x24:\n logger.warn('Unsupported HEVC stream type found');\n break;\n\n default:\n // logger.log('unknown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += (((data[offset + 3] & 0x0f) << 8) | data[offset + 4]) + 5;\n }\n return result;\n}\n\nfunction parsePES(stream: ElementaryStreamData): PES | null {\n let i = 0;\n let frag: Uint8Array;\n let pesLen: number;\n let pesHdrLen: number;\n let pesPts: number | undefined;\n let pesDts: number | undefined;\n const data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n const newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n\n const pesFlags = frag[7];\n if (pesFlags & 0xc0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts =\n (frag[9] & 0x0e) * 536870912 + // 1 << 29\n (frag[10] & 0xff) * 4194304 + // 1 << 22\n (frag[11] & 0xfe) * 16384 + // 1 << 14\n (frag[12] & 0xff) * 128 + // 1 << 7\n (frag[13] & 0xfe) / 2;\n\n if (pesFlags & 0x40) {\n pesDts =\n (frag[14] & 0x0e) * 536870912 + // 1 << 29\n (frag[15] & 0xff) * 4194304 + // 1 << 22\n (frag[16] & 0xfe) * 16384 + // 1 << 14\n (frag[17] & 0xff) * 128 + // 1 << 7\n (frag[18] & 0xfe) / 2;\n\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(\n `${Math.round(\n (pesPts - pesDts) / 90000\n )}s delta between PTS and DTS, align them`\n );\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n let payloadStartOffset = pesHdrLen + 9;\n if (stream.size <= payloadStartOffset) {\n return null;\n }\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n const pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };\n }\n return null;\n}\n\nfunction pushAccessUnit(avcSample: ParsedAvcSample, avcTrack: DemuxedAvcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (avcSample.pts === undefined) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n avcSample.pts = lastSample.pts;\n avcSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n avcTrack.dropped++;\n return;\n }\n }\n avcTrack.samples.push(avcSample as AvcSample);\n }\n if (avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n}\n\nexport default TSDemuxer;\n","/*\n * Fork of webworkify-webpack with support for Webpack 5\n * https://github.com/wupeng-engineer/webworkify-webpack/blob/db0de7/index.js\n*/\n\nconst webpackBootstrapFunc = function () {// webpackBootstrap\n /******/ \tvar __webpack_modules__ = ENTRY_MODULE\n /************************************************************************/\n /******/ // The module cache\n /******/ var __webpack_module_cache__ = {};\n /******/ \n /******/ // The require function\n /******/ var __webpack_require__ = function __webpack_require__(moduleId) {\n /******/ // Check if module is in cache\n /******/ var cachedModule = __webpack_module_cache__[moduleId];\n /******/ if (cachedModule !== undefined) {\n /******/ return cachedModule.exports;\n /******/ }\n /******/ // Create a new module (and put it into the cache)\n /******/ var module = __webpack_module_cache__[moduleId] = {\n /******/ // no module.id needed\n /******/ // no module.loaded needed\n /******/ exports: {}\n /******/ };\n /******/ \n /******/ // Execute the module function\n /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n /******/ \n /******/ // Return the exports of the module\n /******/ return module.exports;\n /******/ }\n /******/ \n /******/ // expose the modules object (__webpack_modules__)\n /******/ __webpack_require__.m = __webpack_modules__;\n /******/ \n /************************************************************************/\n /******/ /* webpack/runtime/compat get default export */\n /******/ (() => {\n /******/ // getDefaultExport function for compatibility with non-harmony modules\n /******/ __webpack_require__.n = (module) => {\n /******/ var getter = module && module.__esModule ?\n /******/ () => (module['default']) :\n /******/ () => (module);\n /******/ __webpack_require__.d(getter, { a: getter });\n /******/ return getter;\n /******/ };\n /******/ })();\n /******/ \n /******/ /* webpack/runtime/define property getters */\n /******/ (() => {\n /******/ // define getter functions for harmony exports\n /******/ __webpack_require__.d = (exports, definition) => {\n /******/ for(var key in definition) {\n /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n /******/ }\n /******/ }\n /******/ };\n /******/ })();\n /******/ \n /******/ /* webpack/runtime/hasOwnProperty shorthand */\n /******/ (() => {\n /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))\n /******/ })();\n /******/ \n /******/ /* webpack/runtime/make namespace object */\n /******/ (() => {\n /******/ // define __esModule on exports\n /******/ __webpack_require__.r = (exports) => {\n /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n /******/ }\n /******/ Object.defineProperty(exports, '__esModule', { value: true });\n /******/ };\n /******/ })();\n /******/ \n /************************************************************************/\n /******/ \n /******/ // module factories are used so entry inlining is disabled\n /******/ // startup\n /******/ // Load entry module and return exports\n /******/ \tvar result = __webpack_require__(ENTRY_MODULE)\n /******/ return result.default || result\n}\n\nvar webpackBootstrapFuncArr = webpackBootstrapFunc.toString().split('ENTRY_MODULE');\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+';\nvar dependencyRegExp = '\\\\(\\\\s*(\\/\\\\*.*?\\\\*\\/)?\\\\s*.*?(' + moduleNameReqExp + ').*?\\\\)';\n\nfunction quoteRegExp(str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&');\n}\n\nfunction isNumeric(n) {\n return !isNaN(1 * n);\n}\n\nfunction getModuleDependencies(sources, module, queueName) {\n var retval = {};\n retval[queueName] = [];\n var fnString = module.toString().replace(/^\"[^\"]+\"/,'function');;\n var wrapperSignature = fnString.match(/^function\\s?\\w*\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/) || fnString.match(/^\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)\\s?\\=\\s?\\>/);\n if (!wrapperSignature) return retval;\n var webpackRequireName = wrapperSignature[1];\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g');\n var match;\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue;\n retval[queueName].push(match[3]);\n }\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g');\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1]);\n sources[match[2]] = __webpack_require__(match[1]).m;\n }\n retval[match[2]] = retval[match[2]] || [];\n retval[match[2]].push(match[4]);\n }\n var keys = Object.keys(retval);\n for (var i = 0; i < keys.length; i++) {\n for (var j = 0; j < retval[keys[i]].length; j++) {\n if (isNumeric(retval[keys[i]][j])) {\n retval[keys[i]][j] = 1 * retval[keys[i]][j];\n }\n }\n }\n return retval;\n}\n\nfunction hasValuesInQueues(queues) {\n var keys = Object.keys(queues);\n return keys.reduce((hasValues, key) => hasValues || queues[key].length > 0, false);\n}\n\nfunction getRequiredModules(sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n };\n var requiredModules = {\n main: []\n };\n var seenModules = {\n main: {}\n };\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue);\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i];\n var queue = modulesQueue[queueName];\n var moduleToCheck = queue.pop();\n seenModules[queueName] = seenModules[queueName] || {};\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue;\n seenModules[queueName][moduleToCheck] = true;\n requiredModules[queueName] = requiredModules[queueName] || [];\n requiredModules[queueName].push(moduleToCheck);\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName);\n var newModulesKeys = Object.keys(newModules);\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || [];\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]);\n }\n }\n }\n return requiredModules;\n}\n\nfunction getWebpackString(requiredModules, sources, entryModule, key) {\n const moduleString = requiredModules[key].map((id) => `\"${id}\": ${sources[key][id].toString().replace(/^\"[^\"]+\"/,'function')}`).join(\",\");\n return `${webpackBootstrapFuncArr[0]}{${moduleString}}${webpackBootstrapFuncArr[1]}\"${entryModule}\"${webpackBootstrapFuncArr[2]}`;\n}\n\nexport default function (moduleId, options) {\n options = options || {};\n var sources = {\n main: __webpack_modules__\n };\n var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId);\n var src = '';\n Object.keys(requiredModules).filter((m) => m !== 'main').forEach((module) => {\n var entryModule = 0;\n while (requiredModules[module][entryModule]) {\n entryModule++;\n }\n requiredModules[module].push(entryModule);\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })';\n src = src + `var ${module} = (${getWebpackString(requiredModules, sources, entryModule, modules)})();\\n`;\n });\n src = src + `new ((${getWebpackString(requiredModules, sources, moduleId, 'main')})())(self);`;\n var blob = new window.Blob([src], {\n type: 'text/javascript'\n });\n var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;\n var workerUrl = URL.createObjectURL(blob);\n var worker = new window.Worker(workerUrl);\n worker.objectURL = workerUrl;\n return worker;\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\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\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_LICENSE_REQUEST_FAILED = 'keySystemLicenseRequestFailed',\n KEY_SYSTEM_NO_INIT_DATA = 'keySystemNoInitData',\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 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 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","import {\n ManifestLoadedData,\n ManifestLoadingData,\n MediaAttachedData,\n MediaAttachingData,\n LevelLoadingData,\n LevelLoadedData,\n ManifestParsedData,\n LevelUpdatedData,\n LevelsUpdatedData,\n FragParsingUserdataData,\n FragDecryptedData,\n FragLoadedData,\n InitPTSFoundData,\n CuesParsedData,\n SubtitleFragProcessedData,\n NonNativeTextTracksData,\n FragLoadingData,\n AudioTrackLoadedData,\n SubtitleTrackLoadedData,\n ErrorData,\n AudioTrackSwitchingData,\n AudioTrackSwitchedData,\n KeyLoadedData,\n KeyLoadingData,\n SubtitleTrackSwitchData,\n SubtitleTracksUpdatedData,\n LevelSwitchedData,\n FragChangedData,\n BufferAppendingData,\n BufferCodecsData,\n FragParsingMetadataData,\n FragParsingInitSegmentData,\n FragBufferedData,\n BufferFlushingData,\n BufferEOSData,\n LevelSwitchingData,\n FPSDropLevelCappingData,\n FPSDropData,\n BufferCreatedData,\n BufferAppendedData,\n LevelPTSUpdatedData,\n FragParsedData,\n AudioTracksUpdatedData,\n FragLoadEmergencyAbortedData,\n BackBufferData,\n LiveBackBufferData,\n TrackLoadingData,\n BufferFlushedData,\n} from './types/events';\n\n/**\n * @readonly\n * @enum {string}\n */\nexport enum Events {\n // Fired before MediaSource is attaching to media element\n MEDIA_ATTACHING = 'hlsMediaAttaching',\n // Fired when MediaSource has been successfully attached to media element\n MEDIA_ATTACHED = 'hlsMediaAttached',\n // Fired before detaching MediaSource from media element\n MEDIA_DETACHING = 'hlsMediaDetaching',\n // Fired when MediaSource has been detached from media element\n MEDIA_DETACHED = 'hlsMediaDetached',\n // Fired when the buffer is going to be reset\n BUFFER_RESET = 'hlsBufferReset',\n // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS = 'hlsBufferCodecs',\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n BUFFER_CREATED = 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING = 'hlsBufferAppending',\n // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}\n BUFFER_APPENDED = 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n BUFFER_EOS = 'hlsBufferEos',\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n BUFFER_FLUSHING = 'hlsBufferFlushing',\n // fired when the media buffer has been flushed - data: { }\n BUFFER_FLUSHED = 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING = 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }\n MANIFEST_LOADED = 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED = 'hlsManifestParsed',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING = 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED = 'hlsLevelSwitched',\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n LEVEL_LOADING = 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }\n LEVEL_LOADED = 'hlsLevelLoaded',\n // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }\n LEVEL_UPDATED = 'hlsLevelUpdated',\n // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }\n LEVEL_PTS_UPDATED = 'hlsLevelPtsUpdated',\n // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }\n LEVELS_UPDATED = 'hlsLevelsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED = 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING = 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED = 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING = 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }\n AUDIO_TRACK_LOADED = 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED = 'hlsSubtitleTracksUpdated',\n // fired to notify that subtitle tracks were cleared as a result of stopping the media\n SUBTITLE_TRACKS_CLEARED = 'hlsSubtitleTracksCleared',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH = 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING = 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }\n SUBTITLE_TRACK_LOADED = 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED = 'hlsSubtitleFragProcessed',\n // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n CUES_PARSED = 'hlsCuesParsed',\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n NON_NATIVE_TEXT_TRACKS_FOUND = 'hlsNonNativeTextTracksFound',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }\n INIT_PTS_FOUND = 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING = 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED = 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }\n FRAG_LOADED = 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED = 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n FRAG_PARSING_INIT_SEGMENT = 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA = 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA = 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n // FRAG_PARSING_DATA = 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED = 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }\n FRAG_BUFFERED = 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED = 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP = 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }\n FPS_DROP_LEVEL_CAPPING = 'hlsFpsDropLevelCapping',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n ERROR = 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n DESTROYING = 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING = 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : LoaderStats }\n KEY_LOADED = 'hlsKeyLoaded',\n // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }\n LIVE_BACK_BUFFER_REACHED = 'hlsLiveBackBufferReached',\n // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }\n BACK_BUFFER_REACHED = 'hlsBackBufferReached',\n}\n\nexport interface HlsListeners {\n [Events.MEDIA_ATTACHING]: (\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) => void;\n [Events.MEDIA_ATTACHED]: (\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) => void;\n [Events.MEDIA_DETACHING]: (event: Events.MEDIA_DETACHING) => void;\n [Events.MEDIA_DETACHED]: (event: Events.MEDIA_DETACHED) => void;\n [Events.BUFFER_RESET]: (event: Events.BUFFER_RESET) => void;\n [Events.BUFFER_CODECS]: (\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData\n ) => void;\n [Events.BUFFER_CREATED]: (\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData\n ) => void;\n [Events.BUFFER_APPENDING]: (\n event: Events.BUFFER_APPENDING,\n data: BufferAppendingData\n ) => void;\n [Events.BUFFER_APPENDED]: (\n event: Events.BUFFER_APPENDED,\n data: BufferAppendedData\n ) => void;\n [Events.BUFFER_EOS]: (event: Events.BUFFER_EOS, data: BufferEOSData) => void;\n [Events.BUFFER_FLUSHING]: (\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData\n ) => void;\n [Events.BUFFER_FLUSHED]: (\n event: Events.BUFFER_FLUSHED,\n data: BufferFlushedData\n ) => void;\n [Events.MANIFEST_LOADING]: (\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData\n ) => void;\n [Events.MANIFEST_LOADED]: (\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ) => void;\n [Events.MANIFEST_PARSED]: (\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) => void;\n [Events.LEVEL_SWITCHING]: (\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ) => void;\n [Events.LEVEL_SWITCHED]: (\n event: Events.LEVEL_SWITCHED,\n data: LevelSwitchedData\n ) => void;\n [Events.LEVEL_LOADING]: (\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ) => void;\n [Events.LEVEL_LOADED]: (\n event: Events.LEVEL_LOADED,\n data: LevelLoadedData\n ) => void;\n [Events.LEVEL_UPDATED]: (\n event: Events.LEVEL_UPDATED,\n data: LevelUpdatedData\n ) => void;\n [Events.LEVEL_PTS_UPDATED]: (\n event: Events.LEVEL_PTS_UPDATED,\n data: LevelPTSUpdatedData\n ) => void;\n [Events.LEVELS_UPDATED]: (\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData\n ) => void;\n [Events.AUDIO_TRACKS_UPDATED]: (\n event: Events.AUDIO_TRACKS_UPDATED,\n data: AudioTracksUpdatedData\n ) => void;\n [Events.AUDIO_TRACK_SWITCHING]: (\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData\n ) => void;\n [Events.AUDIO_TRACK_SWITCHED]: (\n event: Events.AUDIO_TRACK_SWITCHED,\n data: AudioTrackSwitchedData\n ) => void;\n [Events.AUDIO_TRACK_LOADING]: (\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData\n ) => void;\n [Events.AUDIO_TRACK_LOADED]: (\n event: Events.AUDIO_TRACK_LOADED,\n data: AudioTrackLoadedData\n ) => void;\n [Events.SUBTITLE_TRACKS_UPDATED]: (\n event: Events.SUBTITLE_TRACKS_UPDATED,\n data: SubtitleTracksUpdatedData\n ) => void;\n [Events.SUBTITLE_TRACKS_CLEARED]: (\n event: Events.SUBTITLE_TRACKS_CLEARED\n ) => void;\n [Events.SUBTITLE_TRACK_SWITCH]: (\n event: Events.SUBTITLE_TRACK_SWITCH,\n data: SubtitleTrackSwitchData\n ) => void;\n [Events.SUBTITLE_TRACK_LOADING]: (\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData\n ) => void;\n [Events.SUBTITLE_TRACK_LOADED]: (\n event: Events.SUBTITLE_TRACK_LOADED,\n data: SubtitleTrackLoadedData\n ) => void;\n [Events.SUBTITLE_FRAG_PROCESSED]: (\n event: Events.SUBTITLE_FRAG_PROCESSED,\n data: SubtitleFragProcessedData\n ) => void;\n [Events.CUES_PARSED]: (\n event: Events.CUES_PARSED,\n data: CuesParsedData\n ) => void;\n [Events.NON_NATIVE_TEXT_TRACKS_FOUND]: (\n event: Events.NON_NATIVE_TEXT_TRACKS_FOUND,\n data: NonNativeTextTracksData\n ) => void;\n [Events.INIT_PTS_FOUND]: (\n event: Events.INIT_PTS_FOUND,\n data: InitPTSFoundData\n ) => void;\n [Events.FRAG_LOADING]: (\n event: Events.FRAG_LOADING,\n data: FragLoadingData\n ) => void;\n // [Events.FRAG_LOAD_PROGRESS]: TodoEventType\n [Events.FRAG_LOAD_EMERGENCY_ABORTED]: (\n event: Events.FRAG_LOAD_EMERGENCY_ABORTED,\n data: FragLoadEmergencyAbortedData\n ) => void;\n [Events.FRAG_LOADED]: (\n event: Events.FRAG_LOADED,\n data: FragLoadedData\n ) => void;\n [Events.FRAG_DECRYPTED]: (\n event: Events.FRAG_DECRYPTED,\n data: FragDecryptedData\n ) => void;\n [Events.FRAG_PARSING_INIT_SEGMENT]: (\n event: Events.FRAG_PARSING_INIT_SEGMENT,\n data: FragParsingInitSegmentData\n ) => void;\n [Events.FRAG_PARSING_USERDATA]: (\n event: Events.FRAG_PARSING_USERDATA,\n data: FragParsingUserdataData\n ) => void;\n [Events.FRAG_PARSING_METADATA]: (\n event: Events.FRAG_PARSING_METADATA,\n data: FragParsingMetadataData\n ) => void;\n // [Events.FRAG_PARSING_DATA]: TodoEventType\n [Events.FRAG_PARSED]: (\n event: Events.FRAG_PARSED,\n data: FragParsedData\n ) => void;\n [Events.FRAG_BUFFERED]: (\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData\n ) => void;\n [Events.FRAG_CHANGED]: (\n event: Events.FRAG_CHANGED,\n data: FragChangedData\n ) => void;\n [Events.FPS_DROP]: (event: Events.FPS_DROP, data: FPSDropData) => void;\n [Events.FPS_DROP_LEVEL_CAPPING]: (\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData\n ) => void;\n [Events.ERROR]: (event: Events.ERROR, data: ErrorData) => void;\n [Events.DESTROYING]: (event: Events.DESTROYING) => void;\n [Events.KEY_LOADING]: (\n event: Events.KEY_LOADING,\n data: KeyLoadingData\n ) => void;\n [Events.KEY_LOADED]: (event: Events.KEY_LOADED, data: KeyLoadedData) => void;\n [Events.LIVE_BACK_BUFFER_REACHED]: (\n event: Events.LIVE_BACK_BUFFER_REACHED,\n data: LiveBackBufferData\n ) => void;\n [Events.BACK_BUFFER_REACHED]: (\n event: Events.BACK_BUFFER_REACHED,\n data: BackBufferData\n ) => void;\n}\nexport interface HlsEventEmitter {\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context\n ): void;\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context\n ): void;\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E): void;\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E],\n context?: Context,\n once?: boolean\n ): void;\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][];\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1]\n ): boolean;\n listenerCount<E extends keyof HlsListeners>(event: E): number;\n}\n","import * as URLToolkit 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 StreamController from './controller/stream-controller';\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { enableStreamingMode, hlsDefaultConfig, mergeConfig } from './config';\nimport { EventEmitter } from 'eventemitter3';\nimport { Events } from './events';\nimport { ErrorTypes, ErrorDetails } from './errors';\nimport type { HlsEventEmitter, HlsListeners } from './events';\nimport type AudioTrackController from './controller/audio-track-controller';\nimport type AbrController from './controller/abr-controller';\nimport type BufferController from './controller/buffer-controller';\nimport type CapLevelController from './controller/cap-level-controller';\nimport type CMCDController from './controller/cmcd-controller';\nimport type EMEController from './controller/eme-controller';\nimport type SubtitleTrackController from './controller/subtitle-track-controller';\nimport type { ComponentAPI, NetworkComponentAPI } from './types/component-api';\nimport type { MediaPlaylist } from './types/media-playlist';\nimport type { HlsConfig } from './config';\nimport type { Level } from './types/level';\nimport type { Fragment } from './loader/fragment';\nimport { BufferInfo } from './utils/buffer-helper';\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls implements HlsEventEmitter {\n private static defaultConfig?: HlsConfig;\n\n public readonly config: HlsConfig;\n public readonly userConfig: Partial<HlsConfig>;\n\n private coreComponents: ComponentAPI[];\n private networkControllers: NetworkComponentAPI[];\n\n private _emitter: HlsEventEmitter = new EventEmitter();\n private _autoLevelCapping: number;\n private abrController: AbrController;\n private bufferController: BufferController;\n private capLevelController: CapLevelController;\n private latencyController: LatencyController;\n private levelController: LevelController;\n private streamController: StreamController;\n private audioTrackController: AudioTrackController;\n private subtitleTrackController: SubtitleTrackController;\n private emeController: EMEController;\n private cmcdController: CMCDController;\n\n private _media: HTMLMediaElement | null = null;\n private url: string | null = null;\n\n static get version(): string {\n return __VERSION__;\n }\n\n static isSupported(): boolean {\n return isSupported();\n }\n\n static get Events() {\n return Events;\n }\n\n static get ErrorTypes() {\n return ErrorTypes;\n }\n\n static get ErrorDetails() {\n return ErrorDetails;\n }\n\n static get DefaultConfig(): HlsConfig {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\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 *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor(userConfig: Partial<HlsConfig> = {}) {\n const config = (this.config = mergeConfig(Hls.DefaultConfig, userConfig));\n this.userConfig = userConfig;\n enableLogs(config.debug, 'Hls instance');\n\n this._autoLevelCapping = -1;\n\n if (config.progressive) {\n enableStreamingMode(config);\n }\n\n // core controllers and network loaders\n const {\n abrController: ConfigAbrController,\n bufferController: ConfigBufferController,\n capLevelController: ConfigCapLevelController,\n fpsController: ConfigFpsController,\n } = config;\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 // network controllers\n const levelController = (this.levelController = new LevelController(this));\n // FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n const streamController = (this.streamController = new StreamController(\n this,\n fragmentTracker\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 = [\n playListLoader,\n levelController,\n streamController,\n ];\n\n this.networkControllers = networkControllers;\n const coreComponents = [\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker,\n ];\n\n this.audioTrackController = this.createController(\n config.audioTrackController,\n null,\n networkControllers\n );\n this.createController(\n config.audioStreamController,\n fragmentTracker,\n networkControllers\n );\n // subtitleTrackController must be defined before because the order of event handling is important\n this.subtitleTrackController = this.createController(\n config.subtitleTrackController,\n null,\n networkControllers\n );\n this.createController(\n config.subtitleStreamController,\n fragmentTracker,\n networkControllers\n );\n this.createController(config.timelineController, null, coreComponents);\n this.emeController = this.createController(\n config.emeController,\n null,\n coreComponents\n );\n this.cmcdController = this.createController(\n config.cmcdController,\n null,\n coreComponents\n );\n this.latencyController = this.createController(\n LatencyController,\n null,\n coreComponents\n );\n\n this.coreComponents = coreComponents;\n }\n\n createController(ControllerClass, fragmentTracker, components) {\n if (ControllerClass) {\n const controllerInstance = fragmentTracker\n ? new ControllerClass(this, fragmentTracker)\n : new ControllerClass(this);\n if (components) {\n components.push(controllerInstance);\n }\n return controllerInstance;\n }\n return null;\n }\n\n // Delegate the EventEmitter through the public API of Hls.js\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any\n ) {\n this._emitter.on(event, listener, context);\n }\n\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any\n ) {\n this._emitter.once(event, listener, context);\n }\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E | undefined) {\n this._emitter.removeAllListeners(event);\n }\n\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E] | undefined,\n context: Context = this as any,\n once?: boolean | undefined\n ) {\n this._emitter.off(event, listener, context, once);\n }\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][] {\n return this._emitter.listeners(event);\n }\n\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1]\n ): boolean {\n return this._emitter.emit(event, name, eventObject);\n }\n\n trigger<E extends keyof HlsListeners>(\n event: E,\n eventObject: Parameters<HlsListeners[E]>[1]\n ): boolean {\n if (this.config.debug) {\n return this.emit(event, event, eventObject);\n } else {\n try {\n return this.emit(event, event, eventObject);\n } catch (e) {\n logger.error(\n 'An internal error happened while handling event ' +\n event +\n '. Error message: \"' +\n e.message +\n '\". Here is a stacktrace:',\n e\n );\n this.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal: false,\n event: event,\n error: e,\n });\n }\n }\n return false;\n }\n\n listenerCount<E extends keyof HlsListeners>(event: E): number {\n return this._emitter.listenerCount(event);\n }\n\n /**\n * Dispose of the instance\n */\n destroy() {\n logger.log('destroy');\n this.trigger(Events.DESTROYING, undefined);\n this.detachMedia();\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n this.url = null;\n\n this.networkControllers.forEach((component) => component.destroy());\n this.networkControllers.length = 0;\n\n this.coreComponents.forEach((component) => component.destroy());\n this.coreComponents.length = 0;\n }\n\n /**\n * Attaches Hls.js to a media element\n * @param {HTMLMediaElement} media\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 * @param {string} url\n */\n loadSource(url: string) {\n this.stopLoad();\n const media = this.media;\n const loadedSource = this.url;\n const loadingSource = (this.url = URLToolkit.buildAbsoluteURL(\n self.location.href,\n url,\n {\n alwaysNormalize: true,\n }\n ));\n logger.log(`loadSource:${loadingSource}`);\n if (\n media &&\n loadedSource &&\n loadedSource !== loadingSource &&\n 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 {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad(startPosition: number = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach((controller) => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad() {\n logger.log('stopLoad');\n this.networkControllers.forEach((controller) => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec() {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError() {\n logger.log('recoverMediaError');\n const media = this._media;\n this.detachMedia();\n if (media) {\n this.attachMedia(media);\n }\n }\n\n removeLevel(levelIndex, urlId = 0) {\n this.levelController.removeLevel(levelIndex, urlId);\n }\n\n /**\n * @type {Level[]}\n */\n get levels(): Array<Level> {\n const levels = this.levelController.levels;\n return levels ? levels : [];\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel(): number {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n set currentLevel(newLevel: number) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.abrController.clearTimer();\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\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 * @type {number} -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 * @type {number}\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 * @type {number} newLevel -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 * @type {number}\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 * @type {number} level\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 * @type {number}\n */\n get firstLevel(): number {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel(newLevel: number) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel(): number {\n return this.levelController.startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number} newLevel\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 * Get the current setting for capLevelToPlayerSize\n *\n * @type {boolean}\n */\n get capLevelToPlayerSize(): boolean {\n return this.config.capLevelToPlayerSize;\n }\n\n /**\n * set dynamically set capLevelToPlayerSize against (`CapLevelController`)\n *\n * @type {boolean}\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 * @type {number}\n */\n get autoLevelCapping(): number {\n return this._autoLevelCapping;\n }\n\n /**\n * get bandwidth estimate\n * @type {number}\n */\n get bandwidthEstimate(): number {\n const { bwEstimator } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimate();\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping(newLevel: number) {\n if (this._autoLevelCapping !== newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled(): boolean {\n return this.levelController.manualLevel === -1;\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\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 * @type {number}\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 * @type {number}\n */\n get maxAutoLevel(): number {\n const { levels, autoLevelCapping } = this;\n\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\n get nextAutoLevel(): number {\n // ensure next auto level is between min and max auto level\n return Math.min(\n Math.max(this.abrController.nextAutoLevel, this.minAutoLevel),\n this.maxAutoLevel\n );\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon successful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel(nextLevel: number) {\n this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);\n }\n\n /**\n * get the datetime value relative to media.currentTime for the active level Program Date Time if present\n * @type {Date}\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 * @type {AudioTrack[]}\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 * @type {number}\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 * @type {number}\n */\n set audioTrack(audioTrackId: number) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {MediaPlaylist[]}\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 * @type {number}\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 * @type {number}\n */\n set subtitleTrack(subtitleTrackId: number) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\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 * @type {boolean}\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 * @type {boolean}\n */\n get lowLatencyMode() {\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 * @type {boolean}\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 * @type {number}\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 * @type {number}\n */\n get latency() {\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 * @type {number}\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 * @type {number}\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 * @type {number}\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 * @type {boolean}\n */\n get forceStartLoad(): boolean {\n return this.streamController.forceStartLoad;\n }\n}\n\nexport type {\n MediaPlaylist,\n ErrorDetails,\n ErrorTypes,\n Events,\n Level,\n HlsListeners,\n HlsEventEmitter,\n HlsConfig,\n Fragment,\n};\n\nexport type {\n ABRControllerConfig,\n BufferControllerConfig,\n CapLevelControllerConfig,\n CMCDControllerConfig,\n EMEControllerConfig,\n DRMSystemOptions,\n FPSControllerConfig,\n FragmentLoaderConfig,\n FragmentLoaderConstructor,\n LevelControllerConfig,\n MP4RemuxerConfig,\n PlaylistLoaderConfig,\n PlaylistLoaderConstructor,\n StreamControllerConfig,\n LatencyControllerConfig,\n MetadataControllerConfig,\n TimelineControllerConfig,\n TSDemuxerConfig,\n} from './config';\nexport type { CuesInterface } from './utils/cues';\nexport type { MediaKeyFunc, KeySystems } 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 LevelParsed,\n LevelAttributes,\n HlsUrlParameters,\n HlsSkip,\n} from './types/level';\nexport type {\n PlaylistLevelType,\n HlsChunkPerformanceTiming,\n HlsPerformanceTiming,\n PlaylistContextType,\n PlaylistLoaderContext,\n FragmentLoaderContext,\n KeyLoaderContext,\n Loader,\n LoaderStats,\n LoaderContext,\n LoaderResponse,\n LoaderConfiguration,\n LoaderCallbacks,\n LoaderOnProgress,\n LoaderOnAbort,\n LoaderOnError,\n LoaderOnSuccess,\n LoaderOnTimeout,\n HlsProgressivePerformanceTiming,\n} from './types/loader';\nexport type {\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 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 ManifestLoadedData,\n ManifestLoadingData,\n ManifestParsedData,\n MediaAttachedData,\n MediaAttachingData,\n NonNativeTextTrack,\n NonNativeTextTracksData,\n SubtitleFragProcessedData,\n SubtitleTrackLoadedData,\n SubtitleTracksUpdatedData,\n SubtitleTrackSwitchData,\n} from './types/events';\nexport type { AttrList } from './utils/attr-list';\n","import { getMediaSource } from './utils/mediasource-helper';\nimport type { ExtendedSourceBuffer } from './types/buffer';\n\nfunction getSourceBuffer(): typeof self.SourceBuffer {\n return self.SourceBuffer || (self as any).WebKitSourceBuffer;\n}\n\nexport function isSupported(): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n const sourceBuffer = getSourceBuffer();\n const isTypeSupported =\n mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n\n // if SourceBuffer is exposed ensure its API is valid\n // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBufferValidAPI =\n !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n\nexport function changeTypeSupported(): boolean {\n const sourceBuffer = getSourceBuffer();\n return (\n typeof (sourceBuffer?.prototype as ExtendedSourceBuffer)?.changeType ===\n 'function'\n );\n}\n","import { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\n\nexport 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 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 { ErrorTypes, ErrorDetails } from '../errors';\nimport { Fragment } from './fragment';\nimport {\n Loader,\n LoaderConfiguration,\n FragmentLoaderContext,\n} from '../types/loader';\nimport type { HlsConfig } from '../config';\nimport type { BaseSegment, Part } from './fragment';\nimport type { FragLoadedData, PartsLoadedData } 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 {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n networkDetails: null,\n },\n `Fragment does not have a ${url ? 'part list' : 'url'}`\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 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 loaderConfig: LoaderConfiguration = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout,\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) => {\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,\n networkDetails,\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 networkDetails,\n })\n );\n },\n onTimeout: (response, 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 networkDetails,\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 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 const loaderConfig: LoaderConfiguration = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout,\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) => {\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 networkDetails,\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 networkDetails,\n })\n );\n },\n onTimeout: (response, 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 networkDetails,\n })\n );\n },\n });\n });\n }\n\n private updateStatsFromPart(frag: Fragment, part: Part) {\n const fragStats = frag.stats;\n const partStats = part.stats;\n const partTotal = partStats.total;\n fragStats.loaded += partStats.loaded;\n if (partTotal) {\n const estTotalParts = Math.round(frag.duration / part.duration);\n const estLoadedParts = Math.min(\n Math.round(fragStats.loaded / partTotal),\n estTotalParts\n );\n const estRemainingParts = estTotalParts - estLoadedParts;\n const estRemainingBytes =\n estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);\n fragStats.total = fragStats.loaded + estRemainingBytes;\n } else {\n fragStats.total = Math.max(fragStats.loaded, fragStats.total);\n }\n const fragLoading = fragStats.loading;\n const partLoading = partStats.loading;\n if (fragLoading.start) {\n // add to fragment loader latency\n fragLoading.first += partLoading.first - partLoading.start;\n } else {\n fragLoading.start = partLoading.start;\n fragLoading.first = partLoading.first;\n }\n fragLoading.end = partLoading.end;\n }\n\n private resetLoader(frag: Fragment, loader: Loader<FragmentLoaderContext>) {\n frag.loader = null;\n if (this.loader === loader) {\n self.clearTimeout(this.partLoadTimeout);\n this.loader = null;\n }\n loader.destroy();\n }\n}\n\nfunction createLoaderContext(\n frag: Fragment,\n part: Part | null = null\n): FragmentLoaderContext {\n const segment: BaseSegment = part || frag;\n const loaderContext: FragmentLoaderContext = {\n frag,\n part,\n responseType: 'arraybuffer',\n url: segment.url,\n headers: {},\n rangeStart: 0,\n rangeEnd: 0,\n };\n const start = segment.byteRangeStartOffset;\n const end = segment.byteRangeEndOffset;\n if (Number.isFinite(start) && Number.isFinite(end)) {\n let byteRangeStart = start;\n let byteRangeEnd = end;\n if (frag.sn === 'initSegment' && frag.decryptdata?.method === 'AES-128') {\n // MAP segment encrypted with method 'AES-128', when served with HTTP Range,\n // has the unencrypted size specified in the range.\n // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6\n const fragmentLen = end - start;\n if (fragmentLen % 16) {\n byteRangeEnd = end + (16 - (fragmentLen % 16));\n }\n if (start !== 0) {\n loaderContext.resetIV = true;\n byteRangeStart = start - 16;\n }\n }\n loaderContext.rangeStart = byteRangeStart;\n loaderContext.rangeEnd = byteRangeEnd;\n }\n return loaderContext;\n}\n\nexport class LoadError extends Error {\n public readonly data: FragLoadFailResult;\n constructor(data: FragLoadFailResult, ...params) {\n super(...params);\n this.data = data;\n }\n}\n\nexport interface FragLoadFailResult {\n type: string;\n details: string;\n fatal: boolean;\n frag: Fragment;\n part?: Part;\n response?: {\n // error status code\n code: number;\n // error description\n text: string;\n };\n networkDetails: any;\n}\n\nexport type FragmentLoadProgressCallback = (\n result: FragLoadedData | PartsLoadedData\n) => void;\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport { logger } from '../utils/logger';\nimport { LevelKey } from './level-key';\nimport { LoadStats } from './load-stats';\nimport { AttrList } from '../utils/attr-list';\nimport type {\n KeyLoaderContext,\n FragmentLoaderContext,\n Loader,\n PlaylistLevelType,\n} from '../types/loader';\n\nexport enum ElementaryStreamTypes {\n AUDIO = 'audio',\n VIDEO = 'video',\n AUDIOVIDEO = 'audiovideo',\n}\n\nexport interface ElementaryStreamInfo {\n startPTS: number;\n endPTS: number;\n startDTS: number;\n endDTS: number;\n partial?: boolean;\n}\n\nexport type ElementaryStreams = Record<\n ElementaryStreamTypes,\n ElementaryStreamInfo | null\n>;\n\nexport class BaseSegment {\n private _byteRange: number[] | null = null;\n private _url: string | null = null;\n\n // baseurl is the URL to the playlist\n public readonly baseurl: string;\n // relurl is the portion of the URL that comes from inside the playlist.\n public relurl?: string;\n // Holds the types of data this fragment supports\n public elementaryStreams: ElementaryStreams = {\n [ElementaryStreamTypes.AUDIO]: null,\n [ElementaryStreamTypes.VIDEO]: null,\n [ElementaryStreamTypes.AUDIOVIDEO]: null,\n };\n\n constructor(baseurl: string) {\n this.baseurl = baseurl;\n }\n\n // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n setByteRange(value: string, previous?: BaseSegment) {\n const params = value.split('@', 2);\n const byteRange: number[] = [];\n if (params.length === 1) {\n byteRange[0] = previous ? previous.byteRangeEndOffset : 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n\n get byteRange(): number[] {\n if (!this._byteRange) {\n return [];\n }\n\n return this._byteRange;\n }\n\n get byteRangeStartOffset(): number {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset(): number {\n return this.byteRange[1];\n }\n\n get url(): string {\n if (!this._url && this.baseurl && this.relurl) {\n this._url = buildAbsoluteURL(this.baseurl, this.relurl, {\n alwaysNormalize: true,\n });\n }\n return this._url || '';\n }\n\n set url(value: string) {\n this._url = value;\n }\n}\n\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 // levelkey is the EXT-X-KEY that applies 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 levelkey?: 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 latest Presentation Time Stamp (PTS) appended to the buffer.\n public appendedPTS?: number;\n // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public startDTS!: number;\n // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public endDTS!: number;\n // The start time of the fragment, as listed in the manifest. Updated after transmux complete.\n public start: number = 0;\n // Set by `updateFragPTSDTS` in level-helper\n public deltaPTS?: number;\n // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public maxStartPTS?: number;\n // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public minEndPTS?: number;\n // Load/parse timing information\n public stats: LoadStats = new LoadStats();\n public urlId: number = 0;\n public data?: Uint8Array;\n // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered\n public bitrateTest: boolean = false;\n // #EXTINF segment title\n public title: string | null = null;\n // The Media Initialization Section for this segment\n public initSegment: Fragment | null = null;\n\n constructor(type: PlaylistLevelType, baseurl: string) {\n super(baseurl);\n this.type = type;\n }\n\n get decryptdata(): LevelKey | null {\n if (!this.levelkey && !this._decryptdata) {\n return null;\n }\n\n if (!this._decryptdata && this.levelkey) {\n let sn = this.sn;\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 (\n this.levelkey &&\n this.levelkey.method === 'AES-128' &&\n !this.levelkey.iv\n ) {\n logger.warn(\n `missing IV for initialization segment with method=\"${this.levelkey.method}\" - compliance issue`\n );\n }\n\n /*\n Be converted to a Number.\n 'initSegment' will become NaN.\n NaN, which when converted through ToInt32() -> +0.\n ---\n Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n */\n sn = 0;\n }\n this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);\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?.keyFormat && this.decryptdata.uri) {\n return true;\n }\n\n return false;\n }\n\n abortRequests(): void {\n this.loader?.abort();\n this.keyLoader?.abort();\n }\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @param {number} segmentNumber - segment number to generate IV with\n * @returns {Uint8Array}\n */\n createInitializationVector(segmentNumber: number): Uint8Array {\n const uint8View = new Uint8Array(16);\n\n for (let i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> (8 * (15 - i))) & 0xff;\n }\n\n return uint8View;\n }\n\n /**\n * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data\n * @param levelkey - a playlist's encryption info\n * @param segmentNumber - the fragment's segment number\n * @returns {LevelKey} - an object to be applied as a fragment's decryptdata\n */\n setDecryptDataFromLevelKey(\n levelkey: LevelKey,\n segmentNumber: number\n ): LevelKey {\n let decryptdata = levelkey;\n\n if (levelkey?.method === 'AES-128' && levelkey.uri && !levelkey.iv) {\n decryptdata = LevelKey.fromURI(levelkey.uri);\n decryptdata.method = levelkey.method;\n decryptdata.iv = this.createInitializationVector(segmentNumber);\n decryptdata.keyFormat = 'identity';\n }\n\n return decryptdata;\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\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","/*\n * Decrypt key Loader\n */\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport {\n LoaderStats,\n LoaderResponse,\n LoaderConfiguration,\n LoaderCallbacks,\n Loader,\n KeyLoaderContext,\n} from '../types/loader';\nimport { LoadError } from './fragment-loader';\nimport type { HlsConfig } from '../hls';\nimport type { Fragment } from '../loader/fragment';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { KeyLoadedData } from '../types/events';\n\nexport default class KeyLoader implements ComponentAPI {\n private readonly config: HlsConfig;\n public loader: Loader<KeyLoaderContext> | null = null;\n public decryptkey: Uint8Array | null = null;\n public decrypturl: string | null = null;\n\n constructor(config: HlsConfig) {\n this.config = config;\n }\n\n abort(): void {\n this.loader?.abort();\n }\n\n destroy(): void {\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n }\n\n load(frag: Fragment): Promise<KeyLoadedData | void> | never {\n const type = frag.type;\n const loader = this.loader;\n if (!frag.decryptdata) {\n throw new Error('Missing decryption data on fragment in onKeyLoading');\n }\n\n // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved\n const uri = frag.decryptdata.uri;\n if (uri !== this.decrypturl || this.decryptkey === null) {\n const config = this.config;\n if (loader) {\n logger.warn(`abort previous key loader for type:${type}`);\n loader.abort();\n }\n if (!uri) {\n throw new Error('key uri is falsy');\n }\n const Loader = config.loader;\n const keyLoader =\n (frag.keyLoader =\n this.loader =\n new Loader(config) as Loader<KeyLoaderContext>);\n this.decrypturl = uri;\n this.decryptkey = null;\n\n return new Promise((resolve, reject) => {\n const loaderContext: KeyLoaderContext = {\n url: uri,\n frag: frag,\n part: null,\n responseType: 'arraybuffer',\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 loaderConfig: LoaderConfiguration = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: config.fragLoadingRetryDelay,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout,\n highWaterMark: 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 = context.frag;\n if (!frag.decryptdata) {\n logger.error('after key load, decryptdata unset');\n return reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.KEY_LOAD_ERROR,\n fatal: false,\n frag,\n networkDetails,\n })\n );\n }\n this.decryptkey = 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 this.loader = null;\n resolve({ frag });\n },\n\n onError: (\n error: { code: number; text: string },\n context: KeyLoaderContext,\n networkDetails: any\n ) => {\n this.resetLoader(context.frag, keyLoader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.KEY_LOAD_ERROR,\n fatal: false,\n frag,\n networkDetails,\n })\n );\n },\n\n onTimeout: (\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any\n ) => {\n this.resetLoader(context.frag, keyLoader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.KEY_LOAD_TIMEOUT,\n fatal: false,\n frag,\n networkDetails,\n })\n );\n },\n\n onAbort: (\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any\n ) => {\n this.resetLoader(context.frag, keyLoader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n networkDetails,\n })\n );\n },\n };\n\n keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n });\n } else if (this.decryptkey) {\n // Return the key if it's already been loaded\n frag.decryptdata.key = this.decryptkey;\n return Promise.resolve({ frag });\n }\n return Promise.resolve();\n }\n\n private resetLoader(frag: Fragment, loader: Loader<KeyLoaderContext>) {\n if (this.loader === loader) {\n this.loader = null;\n }\n loader.destroy();\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';\n\nconst DEFAULT_TARGET_DURATION = 10;\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 needSidxRanges: boolean = false;\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\n constructor(baseUrl) {\n this.fragments = [];\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 || !!partIndexDiff || !!partSnDiff;\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","import { buildAbsoluteURL } from 'url-toolkit';\n\nexport class LevelKey {\n private _uri: string | null = null;\n public method: string | null = null;\n public keyFormat: string | null = null;\n public keyFormatVersions: string | null = null;\n public keyID: string | null = null;\n public key: Uint8Array | null = null;\n public iv: Uint8Array | null = null;\n\n static fromURL(baseUrl: string, relativeUrl: string): LevelKey {\n return new LevelKey(baseUrl, relativeUrl);\n }\n\n static fromURI(uri: string): LevelKey {\n return new LevelKey(uri);\n }\n\n private constructor(absoluteOrBaseURI: string, relativeURL?: string) {\n if (relativeURL) {\n this._uri = buildAbsoluteURL(absoluteOrBaseURI, relativeURL, {\n alwaysNormalize: true,\n });\n } else {\n this._uri = absoluteOrBaseURI;\n }\n }\n\n get uri() {\n return this._uri;\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 * as URLToolkit from 'url-toolkit';\n\nimport { DateRange } from './date-range';\nimport { Fragment, Part } from './fragment';\nimport { LevelDetails } from './level-details';\nimport { LevelKey } from './level-key';\n\nimport { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport type { CodecType } from '../utils/codecs';\nimport { isCodecType } from '../utils/codecs';\nimport type {\n MediaPlaylist,\n AudioGroup,\n MediaPlaylistType,\n} from '../types/media-playlist';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { LevelAttributes, LevelParsed } from '../types/level';\n\ntype M3U8ParserFragments = Array<Fragment | null>;\n\n// https://regex101.com is your friend\nconst MASTER_PLAYLIST_REGEX =\n /#EXT-X-STREAM-INF:([^\\r\\n]*)(?:[\\r\\n](?:#[^\\r\\n]*)?)*([^\\r\\n]+)|#EXT-X-SESSION-DATA:([^\\r\\n]*)[\\r\\n]+/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp(\n [\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /(?!#) *(\\S[\\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /#.*/.source, // All other non-segment oriented tags will match with all groups empty\n ].join('|'),\n 'g'\n);\n\nconst LEVEL_PLAYLIST_REGEX_SLOW = new RegExp(\n [\n /#(EXTM3U)/.source,\n /#EXT-X-(DATERANGE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/\n .source,\n /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)/\n .source,\n /#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,\n /(#)([^:]*):(.*)/.source,\n /(#)(.*)(?:.*)\\r?\\n?/.source,\n ].join('|')\n);\n\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nfunction isMP4Url(url: string): boolean {\n return MP4_REGEX_SUFFIX.test(URLToolkit.parseURL(url)?.path ?? '');\n}\n\nexport default class M3U8Parser {\n static findGroup(\n groups: Array<AudioGroup>,\n mediaGroupId: string\n ): AudioGroup | undefined {\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n return group;\n }\n }\n }\n\n static convertAVC1ToAVCOTI(codec) {\n // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported\n const avcdata = codec.split('.');\n if (avcdata.length > 2) {\n let result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);\n return result;\n }\n return codec;\n }\n\n static resolve(url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static parseMasterPlaylist(string: string, baseurl: string) {\n const levels: Array<LevelParsed> = [];\n const levelsWithKnownCodecs: Array<LevelParsed> = [];\n const sessionData: Record<string, AttrList> = {};\n let hasSessionData = false;\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]);\n const level: LevelParsed = {\n attrs,\n bitrate:\n attrs.decimalInteger('AVERAGE-BANDWIDTH') ||\n attrs.decimalInteger('BANDWIDTH'),\n name: attrs.NAME,\n url: M3U8Parser.resolve(result[2], baseurl),\n };\n\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n\n setCodecs(\n (attrs.CODECS || '').split(/[ ,]+/).filter((c) => c),\n level\n );\n\n if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {\n level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n if (!level.unknownCodecs?.length) {\n levelsWithKnownCodecs.push(level);\n }\n\n levels.push(level);\n } else if (result[3]) {\n // '#EXT-X-SESSION-DATA' is found, parse session data in group 3\n const sessionAttrs = new AttrList(result[3]);\n if (sessionAttrs['DATA-ID']) {\n hasSessionData = true;\n sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;\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 < levels.length;\n\n return {\n levels: stripUnknownCodecLevels ? levelsWithKnownCodecs : levels,\n sessionData: hasSessionData ? sessionData : null,\n };\n }\n\n static parseMasterPlaylistMedia(\n string: string,\n baseurl: string,\n type: MediaPlaylistType,\n groups: Array<AudioGroup> = []\n ): Array<MediaPlaylist> {\n let result: RegExpExecArray | null;\n const medias: Array<MediaPlaylist> = [];\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 LevelAttributes;\n if (attrs.TYPE === type) {\n const media: MediaPlaylist = {\n attrs,\n bitrate: 0,\n id: id++,\n groupId: attrs['GROUP-ID'],\n instreamId: attrs['INSTREAM-ID'],\n name: attrs.NAME || attrs.LANGUAGE || '',\n type,\n default: attrs.bool('DEFAULT'),\n autoselect: attrs.bool('AUTOSELECT'),\n forced: attrs.bool('FORCED'),\n lang: attrs.LANGUAGE,\n url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : '',\n };\n\n if (groups.length) {\n // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n const groupCodec =\n M3U8Parser.findGroup(groups, media.groupId as string) || groups[0];\n assignCodec(media, groupCodec, 'audioCodec');\n assignCodec(media, groupCodec, 'textCodec');\n }\n\n medias.push(media);\n }\n }\n return medias;\n }\n\n static parseLevelPlaylist(\n string: string,\n baseurl: string,\n id: number,\n type: PlaylistLevelType,\n levelUrlId: number\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 levelkey: LevelKey | undefined;\n let firstPdtIndex = -1;\n let createNextFrag = false;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n level.m3u8 = string;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n if (createNextFrag) {\n createNextFrag = false;\n frag = new Fragment(type, baseurl);\n // setup the next fragment for part loading\n frag.start = totalduration;\n frag.sn = currentSN;\n frag.cc = discontinuityCounter;\n frag.level = id;\n if (currentInitSegment) {\n frag.initSegment = currentInitSegment;\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n currentInitSegment.rawProgramDateTime = null;\n }\n }\n\n const duration = result[1];\n if (duration) {\n // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n } else if (result[3]) {\n // url\n if (Number.isFinite(frag.duration)) {\n frag.start = totalduration;\n if (levelkey) {\n frag.levelkey = levelkey;\n }\n frag.sn = currentSN;\n frag.level = id;\n frag.cc = discontinuityCounter;\n frag.urlId = levelUrlId;\n fragments.push(frag);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.relurl = (' ' + result[3]).slice(1);\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 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 = parseFloat(value1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case '#':\n if (value1 || value2) {\n frag.tagList.push(value2 ? [value1, value2] : [value1]);\n }\n break;\n case 'DISCONTINUITY':\n discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'GAP':\n frag.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 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 'DISCONTINUITY-SEQUENCE':\n discontinuityCounter = parseInt(value1);\n break;\n case 'KEY': {\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const keyAttrs = new AttrList(value1);\n const decryptmethod = keyAttrs.enumeratedString('METHOD');\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n const decryptkeyformatversions =\n keyAttrs.enumeratedString('KEYFORMATVERSIONS');\n const decryptkeyid = keyAttrs.enumeratedString('KEYID');\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat =\n keyAttrs.enumeratedString('KEYFORMAT') ?? 'identity';\n\n const unsupportedKnownKeyformatsInManifest = [\n 'com.apple.streamingkeydelivery',\n 'com.microsoft.playready',\n 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2)\n 'com.widevine', // earlier widevine (v1)\n ];\n\n if (\n unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) >\n -1\n ) {\n logger.warn(\n `Keyformat ${decryptkeyformat} is not supported from the manifest`\n );\n continue;\n } else if (decryptkeyformat !== 'identity') {\n // We are supposed to skip keys we don't understand.\n // As we currently only officially support identity keys\n // from the manifest we shouldn't save any other key.\n continue;\n }\n\n // TODO: multiple keys can be defined on a fragment, and we need to support this\n // for clients that support both playready and widevine\n if (decryptmethod) {\n // TODO: need to determine if the level key is actually a relative URL\n // if it isn't, then we should instead construct the LevelKey using fromURI.\n levelkey = LevelKey.fromURL(baseurl, decrypturi);\n if (\n decrypturi &&\n ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(\n decryptmethod\n ) >= 0\n ) {\n levelkey.method = decryptmethod;\n levelkey.keyFormat = decryptkeyformat;\n\n if (decryptkeyid) {\n levelkey.keyID = decryptkeyid;\n }\n\n if (decryptkeyformatversions) {\n levelkey.keyFormatVersions = decryptkeyformatversions;\n }\n\n // Initialization Vector (IV)\n levelkey.iv = decryptiv;\n }\n }\n break;\n }\n case 'START': {\n const startAttrs = new AttrList(value1);\n const startTimeOffset =\n startAttrs.decimalFloatingPoint('TIME-OFFSET');\n // TIME-OFFSET can be 0\n if (Number.isFinite(startTimeOffset)) {\n level.startTimeOffset = startTimeOffset;\n }\n break;\n }\n case 'MAP': {\n const mapAttrs = new AttrList(value1);\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, levelkey);\n currentInitSegment = init;\n frag.initSegment = currentInitSegment;\n if (\n currentInitSegment.rawProgramDateTime &&\n !frag.rawProgramDateTime\n ) {\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n }\n } else {\n // Initial segment tag is before segment duration tag\n setInitSegment(frag, mapAttrs, id, levelkey);\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 part = new Part(\n new AttrList(value1),\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 level.preloadHint = preloadHintAttrs;\n break;\n }\n case 'RENDITION-REPORT': {\n const renditionReportAttrs = new AttrList(value1);\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 }\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 (firstFragment) {\n level.startCC = firstFragment.cc;\n if (!firstFragment.initSegment) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (\n level.fragments.every(\n (frag) => frag.relurl && isMP4Url(frag.relurl)\n )\n ) {\n logger.warn(\n 'MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX'\n );\n frag = new Fragment(type, baseurl);\n frag.relurl = lastFragment.relurl;\n frag.level = id;\n frag.sn = 'initSegment';\n firstFragment.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\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 setCodecs(codecs: Array<string>, level: LevelParsed) {\n ['video', 'audio', 'text'].forEach((type: CodecType) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n const preferred = filtered.filter((codec) => {\n return (\n codec.lastIndexOf('avc1', 0) === 0 ||\n codec.lastIndexOf('mp4a', 0) === 0\n );\n });\n level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];\n\n // remove from list\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n\n level.unknownCodecs = codecs;\n}\n\nfunction assignCodec(media, groupItem, codecProperty) {\n const codecValue = groupItem[codecProperty];\n if (codecValue) {\n media[codecProperty] = codecValue;\n }\n}\n\nfunction backfillProgramDateTimes(\n fragments: M3U8ParserFragments,\n firstPdtIndex: number\n) {\n let fragPrev = fragments[firstPdtIndex] as Fragment;\n for (let i = firstPdtIndex; i--; ) {\n const frag = fragments[i];\n // Exit on delta-playlist skipped segments\n if (!frag) {\n return;\n }\n frag.programDateTime =\n (fragPrev.programDateTime as number) - frag.duration * 1000;\n fragPrev = frag;\n }\n}\n\nfunction assignProgramDateTime(frag, prevFrag) {\n if (frag.rawProgramDateTime) {\n frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n } else if (prevFrag?.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n\n if (!Number.isFinite(frag.programDateTime)) {\n frag.programDateTime = null;\n frag.rawProgramDateTime = null;\n }\n}\n\nfunction setInitSegment(\n frag: Fragment,\n mapAttrs: AttrList,\n id: number,\n levelkey: 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 (levelkey) {\n frag.levelkey = levelkey;\n }\n frag.initSegment = 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 * @module\n *\n */\n\nimport { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { logger } from '../utils/logger';\nimport { parseSegmentIndex, findBox } from '../utils/mp4-tools';\nimport M3U8Parser from './m3u8-parser';\nimport type { LevelParsed } from '../types/level';\nimport type {\n Loader,\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 type Hls from '../hls';\nimport { AttrList } from '../utils/attr-list';\nimport type {\n ErrorData,\n LevelLoadingData,\n ManifestLoadingData,\n TrackLoadingData,\n} from '../types/events';\nimport { NetworkComponentAPI } from '../types/component-api';\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\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\n const loader = new InternalLoader(config) as Loader<PlaylistLoaderContext>;\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n private getInternalLoader(\n context: PlaylistLoaderContext\n ): Loader<LoaderContext> {\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.unregisterListeners();\n this.destroyInternalLoaders();\n }\n\n private onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData\n ) {\n const { url } = data;\n this.load({\n id: null,\n groupId: null,\n level: 0,\n responseType: 'text',\n type: PlaylistContextType.MANIFEST,\n url,\n deliveryDirectives: null,\n });\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { id, level, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId: null,\n level,\n responseType: 'text',\n type: PlaylistContextType.LEVEL,\n url,\n deliveryDirectives,\n });\n }\n\n private onAudioTrackLoading(\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.AUDIO_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private onSubtitleTrackLoading(\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.SUBTITLE_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private load(context: PlaylistLoaderContext): void {\n const config = this.hls.config;\n\n // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === context.url) {\n // same URL can't overlap\n logger.trace('[playlist-loader]: playlist request ongoing');\n return;\n }\n logger.log(\n `[playlist-loader]: aborting previous loader for type: ${context.type}`\n );\n loader.abort();\n }\n\n let maxRetry;\n let timeout;\n let retryDelay;\n let maxRetryDelay;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case PlaylistContextType.LEVEL:\n case PlaylistContextType.AUDIO_TRACK:\n case PlaylistContextType.SUBTITLE_TRACK:\n // Manage retries in Level/Track Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n // Override level/track timeout for LL-HLS requests\n // (the default of 10000ms is counter productive to blocking playlist reload requests)\n if (context.deliveryDirectives?.part) {\n let levelDetails: LevelDetails | undefined;\n if (\n context.type === PlaylistContextType.LEVEL &&\n context.level !== null\n ) {\n levelDetails = this.hls.levels[context.level].details;\n } else if (\n context.type === PlaylistContextType.AUDIO_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.audioTracks[context.id].details;\n } else if (\n context.type === PlaylistContextType.SUBTITLE_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.subtitleTracks[context.id].details;\n }\n if (levelDetails) {\n const partTarget = levelDetails.partTarget;\n const targetDuration = levelDetails.targetduration;\n if (partTarget && targetDuration) {\n timeout = Math.min(\n Math.max(partTarget * 3, targetDuration * 0.8) * 1000,\n timeout\n );\n }\n }\n }\n\n const loaderConfig: LoaderConfiguration = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay,\n highWaterMark: 0,\n };\n\n const loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\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 loadsuccess(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any = null\n ): void {\n if (context.isSidxRequest) {\n this.handleSidxRequest(response, context);\n this.handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\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 'no EXTM3U delimiter',\n networkDetails\n );\n return;\n }\n\n stats.parsing.start = performance.now();\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (\n string.indexOf('#EXTINF:') > 0 ||\n string.indexOf('#EXT-X-TARGETDURATION:') > 0\n ) {\n this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this.handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n private loaderror(\n response: LoaderResponse,\n context: PlaylistLoaderContext,\n networkDetails: any = null\n ): void {\n this.handleNetworkError(context, networkDetails, false, response);\n }\n\n private loadtimeout(\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any = null\n ): void {\n this.handleNetworkError(context, networkDetails, true);\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 { levels, sessionData } = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this.handleManifestParsingError(\n response,\n context,\n 'no level found in manifest',\n networkDetails\n );\n return;\n }\n\n // multi level playlist, parse level info\n const audioGroups = levels.map((level: LevelParsed) => ({\n id: level.attrs.AUDIO,\n audioCodec: level.audioCodec,\n }));\n\n const subtitleGroups = levels.map((level: LevelParsed) => ({\n id: level.attrs.SUBTITLES,\n textCodec: level.textCodec,\n }));\n\n const audioTracks = M3U8Parser.parseMasterPlaylistMedia(\n string,\n url,\n 'AUDIO',\n audioGroups\n );\n const subtitles = M3U8Parser.parseMasterPlaylistMedia(\n string,\n url,\n 'SUBTITLES',\n subtitleGroups\n );\n const captions = M3U8Parser.parseMasterPlaylistMedia(\n string,\n url,\n 'CLOSED-CAPTIONS'\n );\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 default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: new AttrList({}),\n bitrate: 0,\n url: '',\n });\n }\n }\n\n hls.trigger(Events.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n url,\n stats,\n networkDetails,\n sessionData,\n });\n }\n\n private handleTrackOrLevelPlaylist(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any\n ): void {\n const hls = this.hls;\n const { id, level, type } = context;\n\n const url = getResponseUrl(response, context);\n const levelUrlId = Number.isFinite(id as number) ? id : 0;\n const levelId = Number.isFinite(level as number) ? level : levelUrlId;\n const levelType = mapContextToLevelType(context);\n const levelDetails: LevelDetails = M3U8Parser.parseLevelPlaylist(\n response.data as string,\n url,\n levelId!,\n levelType,\n levelUrlId!\n );\n\n if (!levelDetails.fragments.length) {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url: url,\n reason: 'no fragments found in level',\n level: typeof context.level === 'number' ? context.level : undefined,\n });\n return;\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 });\n }\n\n // save parsing time\n stats.parsing.end = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.fragments[0].initSegment?.url as string;\n this.load({\n url: sidxUrl,\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n groupId: null,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer',\n deliveryDirectives: null,\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this.handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n private handleSidxRequest(\n response: LoaderResponse,\n context: PlaylistLoaderContext\n ): void {\n const data = new Uint8Array(response.data as ArrayBuffer);\n const sidxBox = findBox(data, ['sidx'])[0];\n // if provided fragment does not contain sidx, early return\n if (!sidxBox) {\n return;\n }\n const sidxInfo = parseSegmentIndex(sidxBox);\n if (!sidxInfo) {\n return;\n }\n const sidxReferences = sidxInfo.references;\n const levelDetails = context.levelDetails as LevelDetails;\n sidxReferences.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n const frag = levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.setByteRange(\n String(1 + segRefInfo.end - segRefInfo.start) +\n '@' +\n String(segRefInfo.start)\n );\n }\n if (frag.initSegment) {\n const moovBox = findBox(data, ['moov'])[0];\n const moovEndOffset = moovBox ? moovBox.length : null;\n frag.initSegment.setByteRange(String(moovEndOffset) + '@0');\n }\n });\n }\n\n private handleManifestParsingError(\n response: LoaderResponse,\n context: PlaylistLoaderContext,\n reason: string,\n networkDetails: any\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 reason,\n response,\n context,\n networkDetails,\n });\n }\n\n private handleNetworkError(\n context: PlaylistLoaderContext,\n networkDetails: any,\n timeout = false,\n response?: LoaderResponse\n ): void {\n logger.warn(\n `[playlist-loader]: A network ${\n timeout ? 'timeout' : 'error'\n } occurred while loading ${context.type} level: ${context.level} id: ${\n context.id\n } group-id: \"${context.groupId}\"`\n );\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 networkDetails,\n };\n\n if (response) {\n errorData.response = response;\n }\n\n this.hls.trigger(Events.ERROR, errorData);\n }\n\n private handlePlaylistLoaded(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any\n ): void {\n const {\n type,\n level,\n id,\n groupId,\n loader,\n levelDetails,\n deliveryDirectives,\n } = context;\n\n if (!levelDetails?.targetduration) {\n this.handleManifestParsingError(\n response,\n context,\n 'invalid target duration',\n networkDetails\n );\n return;\n }\n if (!loader) {\n return;\n }\n\n if (levelDetails.live) {\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 this.hls.trigger(Events.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n case PlaylistContextType.AUDIO_TRACK:\n this.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 this.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","export const isFiniteNumber =\n Number.isFinite ||\n function (value) {\n return typeof value === 'number' && isFinite(value);\n };\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame(\n codec?: string,\n channelCount?: number\n ): Uint8Array | undefined {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([\n 0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80,\n ]);\n } else if (channelCount === 3) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x8e,\n ]);\n } else if (channelCount === 4) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38,\n ]);\n } else if (channelCount === 5) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38,\n ]);\n } else if (channelCount === 6) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2,\n 0x00, 0x20, 0x08, 0xe0,\n ]);\n }\n\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n }\n break;\n }\n return undefined;\n }\n}\n\nexport default AAC;\n","/**\n * Generate MP4 Box\n */\n\ntype HdlrTypes = {\n video: Uint8Array;\n audio: Uint8Array;\n};\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n public static types: Record<string, number[]>;\n private static HDLR_TYPES: HdlrTypes;\n private static STTS: Uint8Array;\n private static STSC: Uint8Array;\n private static STCO: Uint8Array;\n private static STSZ: Uint8Array;\n private static VMHD: Uint8Array;\n private static SMHD: Uint8Array;\n private static STSD: Uint8Array;\n private static FTYP: Uint8Array;\n private static DINF: Uint8Array;\n\n static init() {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: [],\n };\n\n let i: string;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3),\n ];\n }\n }\n\n const videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x76,\n 0x69,\n 0x64,\n 0x65, // handler_type: 'vide'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x56,\n 0x69,\n 0x64,\n 0x65,\n 0x6f,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'VideoHandler'\n ]);\n\n const audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x73,\n 0x6f,\n 0x75,\n 0x6e, // handler_type: 'soun'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x53,\n 0x6f,\n 0x75,\n 0x6e,\n 0x64,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n video: videoHdlr,\n audio: audioHdlr,\n };\n\n const dref = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01, // entry_count\n 0x00,\n 0x00,\n 0x00,\n 0x0c, // entry_size\n 0x75,\n 0x72,\n 0x6c,\n 0x20, // 'url' type\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x01, // entry_flags\n ]);\n\n const stco = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x01, // flags\n 0x00,\n 0x00, // graphicsmode\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00, // balance\n 0x00,\n 0x00, // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n ]); // entry_count\n\n const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n const minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(\n MP4.types.ftyp,\n majorBrand,\n minorVersion,\n majorBrand,\n avc1Brand\n );\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box(type, ...payload: Uint8Array[]) {\n let size = 8;\n let i = payload.length;\n const len = i;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n\n const result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.mdhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x55,\n 0xc4, // 'und' language (undetermined)\n 0x00,\n 0x00,\n ])\n );\n }\n\n static mdia(track) {\n return MP4.box(\n MP4.types.mdia,\n MP4.mdhd(track.timescale, track.duration),\n MP4.hdlr(track.type),\n MP4.minf(track)\n );\n }\n\n static mfhd(sequenceNumber) {\n return MP4.box(\n MP4.types.mfhd,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00,\n 0x00, // flags\n sequenceNumber >> 24,\n (sequenceNumber >> 16) & 0xff,\n (sequenceNumber >> 8) & 0xff,\n sequenceNumber & 0xff, // sequence_number\n ])\n );\n }\n\n static minf(track) {\n if (track.type === 'audio') {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.smhd, MP4.SMHD),\n MP4.DINF,\n MP4.stbl(track)\n );\n } else {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.vmhd, MP4.VMHD),\n MP4.DINF,\n MP4.stbl(track)\n );\n }\n }\n\n static moof(sn, baseMediaDecodeTime, track) {\n return MP4.box(\n MP4.types.moof,\n MP4.mfhd(sn),\n MP4.traf(track, baseMediaDecodeTime)\n );\n }\n\n /**\n * @param tracks... (optional) {array} the tracks associated with this movie\n */\n static moov(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(\n null,\n [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)]\n .concat(boxes)\n .concat(MP4.mvex(tracks))\n );\n }\n\n static mvex(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);\n }\n\n static mvhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n const bytes = new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x01,\n 0x00,\n 0x00, // 1.0 rate\n 0x01,\n 0x00, // 1.0 volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0xff,\n 0xff,\n 0xff,\n 0xff, // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp(track) {\n const samples = track.samples || [];\n const bytes = new Uint8Array(4 + samples.length);\n let i;\n let flags;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] =\n (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n flags.hasRedundancy;\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl(track) {\n return MP4.box(\n MP4.types.stbl,\n MP4.stsd(track),\n MP4.box(MP4.types.stts, MP4.STTS),\n MP4.box(MP4.types.stsc, MP4.STSC),\n MP4.box(MP4.types.stsz, MP4.STSZ),\n MP4.box(MP4.types.stco, MP4.STCO)\n );\n }\n\n static avc1(track) {\n let sps: number[] = [];\n let pps: number[] = [];\n let i;\n let data;\n let len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xff);\n sps.push(len & 0xff);\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xff);\n pps.push(len & 0xff);\n\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n const avcc = MP4.box(\n MP4.types.avcC,\n new Uint8Array(\n [\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xe0 | track.sps.length, // 3bit reserved (111) + numOfSequenceParameterSets\n ]\n .concat(sps)\n .concat([\n track.pps.length, // numOfPictureParameterSets\n ])\n .concat(pps)\n )\n ); // \"PPS\"\n const width = track.width;\n const height = track.height;\n const hSpacing = track.pixelRatio[0];\n const vSpacing = track.pixelRatio[1];\n\n return MP4.box(\n MP4.types.avc1,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00, // pre_defined\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n (width >> 8) & 0xff,\n width & 0xff, // width\n (height >> 8) & 0xff,\n height & 0xff, // height\n 0x00,\n 0x48,\n 0x00,\n 0x00, // horizresolution\n 0x00,\n 0x48,\n 0x00,\n 0x00, // vertresolution\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // frame_count\n 0x12,\n 0x64,\n 0x61,\n 0x69,\n 0x6c, // dailymotion/hls.js\n 0x79,\n 0x6d,\n 0x6f,\n 0x74,\n 0x69,\n 0x6f,\n 0x6e,\n 0x2f,\n 0x68,\n 0x6c,\n 0x73,\n 0x2e,\n 0x6a,\n 0x73,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // compressorname\n 0x00,\n 0x18, // depth = 24\n 0x11,\n 0x11,\n ]), // pre_defined = -1\n avcc,\n MP4.box(\n MP4.types.btrt,\n new Uint8Array([\n 0x00,\n 0x1c,\n 0x9c,\n 0x80, // bufferSizeDB\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0, // maxBitrate\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0,\n ])\n ), // avgBitrate\n MP4.box(\n MP4.types.pasp,\n new Uint8Array([\n hSpacing >> 24, // hSpacing\n (hSpacing >> 16) & 0xff,\n (hSpacing >> 8) & 0xff,\n hSpacing & 0xff,\n vSpacing >> 24, // vSpacing\n (vSpacing >> 16) & 0xff,\n (vSpacing >> 8) & 0xff,\n vSpacing & 0xff,\n ])\n )\n );\n }\n\n static esds(track) {\n const configlen = track.config.length;\n return new Uint8Array(\n [\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17 + configlen, // length\n 0x00,\n 0x01, // es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f + configlen, // length\n 0x40, // codec : mpeg4_audio\n 0x15, // stream_type\n 0x00,\n 0x00,\n 0x00, // buffer_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // maxBitrate\n 0x00,\n 0x00,\n 0x00,\n 0x00, // avgBitrate\n\n 0x05, // descriptor_type\n ]\n .concat([configlen])\n .concat(track.config)\n .concat([0x06, 0x01, 0x02])\n ); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static mp4a(track) {\n const samplerate = track.samplerate;\n return MP4.box(\n MP4.types.mp4a,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n track.channelCount, // channelcount\n 0x00,\n 0x10, // sampleSize:16bits\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved2\n (samplerate >> 8) & 0xff,\n samplerate & 0xff, //\n 0x00,\n 0x00,\n ]),\n MP4.box(MP4.types.esds, MP4.esds(track))\n );\n }\n\n static mp3(track) {\n const samplerate = track.samplerate;\n return MP4.box(\n MP4.types['.mp3'],\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n track.channelCount, // channelcount\n 0x00,\n 0x10, // sampleSize:16bits\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved2\n (samplerate >> 8) & 0xff,\n samplerate & 0xff, //\n 0x00,\n 0x00,\n ])\n );\n }\n\n static stsd(track) {\n if (track.type === 'audio') {\n if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd(track) {\n const id = track.id;\n const duration = track.duration * track.timescale;\n const width = track.width;\n const height = track.height;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.tkhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x07, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (id >> 24) & 0xff,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00, // layer\n 0x00,\n 0x00, // alternate_group\n 0x00,\n 0x00, // non-audio track volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n (width >> 8) & 0xff,\n width & 0xff,\n 0x00,\n 0x00, // width\n (height >> 8) & 0xff,\n height & 0xff,\n 0x00,\n 0x00, // height\n ])\n );\n }\n\n static traf(track, baseMediaDecodeTime) {\n const sampleDependencyTable = MP4.sdtp(track);\n const id = track.id;\n const upperWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime / (UINT32_MAX + 1)\n );\n const lowerWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime % (UINT32_MAX + 1)\n );\n return MP4.box(\n MP4.types.traf,\n MP4.box(\n MP4.types.tfhd,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n ])\n ),\n MP4.box(\n MP4.types.tfdt,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n upperWordBaseMediaDecodeTime >> 24,\n (upperWordBaseMediaDecodeTime >> 16) & 0xff,\n (upperWordBaseMediaDecodeTime >> 8) & 0xff,\n upperWordBaseMediaDecodeTime & 0xff,\n lowerWordBaseMediaDecodeTime >> 24,\n (lowerWordBaseMediaDecodeTime >> 16) & 0xff,\n (lowerWordBaseMediaDecodeTime >> 8) & 0xff,\n lowerWordBaseMediaDecodeTime & 0xff,\n ])\n ),\n MP4.trun(\n track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8\n ), // mdat header\n sampleDependencyTable\n );\n }\n\n /**\n * Generate a track box.\n * @param track {object} a track definition\n * @return {Uint8Array} the track box\n */\n static trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex(track) {\n const id = track.id;\n return MP4.box(\n MP4.types.trex,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x01, // default_sample_description_index\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_duration\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_size\n 0x00,\n 0x01,\n 0x00,\n 0x01, // default_sample_flags\n ])\n );\n }\n\n static trun(track, offset) {\n const samples = track.samples || [];\n const len = samples.length;\n const arraylen = 12 + 16 * len;\n const array = new Uint8Array(arraylen);\n let i;\n let sample;\n let duration;\n let size;\n let flags;\n let cts;\n offset += 8 + arraylen;\n array.set(\n [\n track.type === 'video' ? 0x01 : 0x00, // version 1 for video with signed-int sample_composition_time_offset\n 0x00,\n 0x0f,\n 0x01, // flags\n (len >>> 24) & 0xff,\n (len >>> 16) & 0xff,\n (len >>> 8) & 0xff,\n len & 0xff, // sample_count\n (offset >>> 24) & 0xff,\n (offset >>> 16) & 0xff,\n (offset >>> 8) & 0xff,\n offset & 0xff, // data_offset\n ],\n 0\n );\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set(\n [\n (duration >>> 24) & 0xff,\n (duration >>> 16) & 0xff,\n (duration >>> 8) & 0xff,\n duration & 0xff, // sample_duration\n (size >>> 24) & 0xff,\n (size >>> 16) & 0xff,\n (size >>> 8) & 0xff,\n size & 0xff, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & (0xf0 << 8),\n flags.degradPrio & 0x0f, // sample_flags\n (cts >>> 24) & 0xff,\n (cts >>> 16) & 0xff,\n (cts >>> 8) & 0xff,\n cts & 0xff, // sample_composition_time_offset\n ],\n 12 + 16 * i\n );\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n const movie = MP4.moov(tracks);\n const result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\n return result;\n }\n}\n\nexport default MP4;\n","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 { toMsFromMpegTsClock } from '../utils/timescale-conversion';\nimport type {\n AudioSample,\n AvcSample,\n DemuxedAudioTrack,\n DemuxedAvcTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n} from '../types/demuxer';\nimport type { TrackSet } from '../types/track';\nimport type { SourceBufferName } from '../types/buffer';\nimport type { Fragment } from '../loader/fragment';\nimport type { HlsConfig } from '../config';\n\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds\nconst AAC_SAMPLES_PER_FRAME = 1024;\nconst MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;\n\nlet chromeVersion: number | null = null;\nlet safariWebkitVersion: number | null = null;\n\nexport default class MP4Remuxer implements Remuxer {\n private observer: HlsEventEmitter;\n private config: HlsConfig;\n private typeSupported: any;\n private ISGenerated: boolean = false;\n private _initPTS!: number;\n private _initDTS!: number;\n private nextAvcDts: number | null = null;\n private nextAudioPts: number | null = null;\n private videoSampleDuration: number | null = null;\n private isAudioContiguous: boolean = false;\n private isVideoContiguous: boolean = false;\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported,\n vendor = ''\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n if (safariWebkitVersion === null) {\n const result = navigator.userAgent.match(/Safari\\/(\\d+)/i);\n safariWebkitVersion = result ? parseInt(result[1]) : 0;\n }\n }\n\n destroy() {}\n\n resetTimeStamp(defaultTimeStamp) {\n logger.log('[mp4-remuxer]: initPTS & initDTS reset');\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetNextTimestamp() {\n logger.log('[mp4-remuxer]: reset next timestamp');\n this.isVideoContiguous = false;\n this.isAudioContiguous = false;\n }\n\n resetInitSegment() {\n logger.log('[mp4-remuxer]: ISGenerated flag reset');\n this.ISGenerated = false;\n }\n\n getVideoStartPts(videoSamples) {\n let rolloverDetected = false;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n const delta = sample.pts - minPTS;\n if (delta < -4294967296) {\n // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n return normalizePts(minPTS, sample.pts);\n } else if (delta > 0) {\n return minPTS;\n } else {\n return sample.pts;\n }\n }, videoSamples[0].pts);\n if (rolloverDetected) {\n logger.debug('PTS rollover detected');\n }\n return startPTS;\n }\n\n remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedAvcTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n flush: boolean,\n playlistType: PlaylistLevelType\n ): RemuxerResult {\n let video: RemuxedTrack | undefined;\n let audio: RemuxedTrack | undefined;\n let initSegment: InitSegmentData | undefined;\n let text: RemuxedUserdata | undefined;\n let id3: RemuxedMetadata | undefined;\n let independent: boolean | undefined;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n\n // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.\n // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the \"pid\"\n // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.\n // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),\n // then we can remux one track without waiting for the other.\n const hasAudio = audioTrack.pid > -1;\n const hasVideo = videoTrack.pid > -1;\n const length = videoTrack.samples.length;\n const enoughAudioSamples = audioTrack.samples.length > 0;\n const enoughVideoSamples = (flush && length > 0) || length > 1;\n const canRemuxAvc =\n ((!hasAudio || enoughAudioSamples) &&\n (!hasVideo || enoughVideoSamples)) ||\n this.ISGenerated ||\n flush;\n\n if (canRemuxAvc) {\n if (!this.ISGenerated) {\n initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);\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(audioTrack, videoTrack, timeOffset);\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(audioTrack, videoTrack, timeOffset);\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) {\n if (id3Track.samples.length) {\n id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n this._initPTS,\n this._initDTS\n );\n }\n\n if (textTrack.samples.length) {\n text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n this._initPTS\n );\n }\n }\n\n return {\n audio,\n video,\n initSegment,\n independent,\n text,\n id3,\n };\n }\n\n generateIS(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedAvcTrack,\n timeOffset\n ): InitSegmentData | undefined {\n const audioSamples = audioTrack.samples;\n const videoSamples = videoTrack.samples;\n const typeSupported = this.typeSupported;\n const tracks: TrackSet = {};\n const computePTSDTS = !Number.isFinite(this._initPTS);\n let container = 'audio/mp4';\n let initPTS: number | undefined;\n let initDTS: number | undefined;\n let timescale: number | undefined;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n switch (audioTrack.segmentCodec) {\n case 'mp3':\n if (typeSupported.mpeg) {\n // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) {\n // Firefox\n audioTrack.codec = 'mp3';\n }\n break;\n }\n tracks.audio = {\n id: 'audio',\n container: container,\n codec: audioTrack.codec,\n initSegment:\n audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg\n ? new Uint8Array(0)\n : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount,\n },\n };\n if (computePTSDTS) {\n timescale = audioTrack.inputTimeScale;\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS =\n audioSamples[0].pts - Math.round(timescale * timeOffset);\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 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 }\n }\n\n if (Object.keys(tracks).length) {\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = initPTS as number;\n this._initDTS = initDTS as number;\n }\n\n return {\n tracks,\n initPTS,\n timescale,\n };\n }\n }\n\n remuxVideo(\n track: DemuxedAvcTrack,\n timeOffset: number,\n contiguous: boolean,\n audioTrackLength: number\n ): RemuxedTrack | undefined {\n const timeScale: number = track.inputTimeScale;\n const inputSamples: Array<AvcSample> = track.samples;\n const outputSamples: Array<Mp4Sample> = [];\n const nbSamples: number = inputSamples.length;\n const initPTS: number = this._initPTS;\n let nextAvcDts = this.nextAvcDts;\n let offset = 8;\n let mp4SampleDuration = this.videoSampleDuration;\n let firstDTS;\n let lastDTS;\n let minPTS: number = Number.POSITIVE_INFINITY;\n let maxPTS: number = Number.NEGATIVE_INFINITY;\n let sortSamples = false;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n if (!contiguous || nextAvcDts === null) {\n const pts = timeOffset * timeScale;\n const cts =\n inputSamples[0].pts -\n normalizePts(inputSamples[0].dts, inputSamples[0].pts);\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);\n sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || deltapts;\n });\n }\n\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[inputSamples.length - 1].dts;\n\n // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n const inputDuration = lastDTS - firstDTS;\n const averageSampleDuration = inputDuration\n ? Math.round(inputDuration / (nbSamples - 1))\n : mp4SampleDuration || track.inputTimeScale / 30;\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n delta,\n true\n )} ms (${delta}dts) hole between fragments detected, filling it`\n );\n } else {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n -delta,\n true\n )} ms (${delta}dts) overlapping between fragments detected`\n );\n }\n if (!foundOverlap || nextAvcDts > inputSamples[0].pts) {\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n logger.log(\n `Video: First PTS/DTS adjusted: ${toMsFromMpegTsClock(\n firstPTS,\n true\n )}/${toMsFromMpegTsClock(\n firstDTS,\n true\n )}, delta: ${toMsFromMpegTsClock(delta, true)} ms`\n );\n }\n }\n }\n\n firstDTS = Math.max(0, firstDTS);\n\n let nbNalu = 0;\n let naluLen = 0;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts, firstDTS);\n\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n const mdatSize = naluLen + 4 * nbNalu + 8;\n let mdat;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n bytes: mdatSize,\n reason: `fail allocating video mdat ${mdatSize}`,\n });\n return;\n }\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n let stretchedLastFrame = false;\n let minDtsDelta = Number.POSITIVE_INFINITY;\n let minPtsDelta = Number.POSITIVE_INFINITY;\n let maxDtsDelta = Number.NEGATIVE_INFINITY;\n let maxPtsDelta = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < nbSamples; i++) {\n const avcSample = inputSamples[i];\n const avcSampleUnits = avcSample.units;\n let mp4SampleLength = 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n const unit = avcSampleUnits[j];\n const unitData = unit.data;\n const unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n let ptsDelta;\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;\n ptsDelta = inputSamples[i + 1].pts - avcSample.pts;\n } else {\n const config = this.config;\n const lastFrameDuration =\n i > 0\n ? avcSample.dts - inputSamples[i - 1].dts\n : averageSampleDuration;\n ptsDelta =\n i > 0\n ? avcSample.pts - inputSamples[i - 1].pts\n : averageSampleDuration;\n if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n const gapTolerance = Math.floor(config.maxBufferHole * timeScale);\n const deltaToFrameEnd =\n (audioTrackLength\n ? minPTS + audioTrackLength * timeScale\n : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n } else {\n stretchedLastFrame = true;\n }\n logger.log(\n `[mp4-remuxer]: It is approximately ${\n deltaToFrameEnd / 90\n } ms to the next segment; using duration ${\n mp4SampleDuration / 90\n } ms for the last video frame.`\n );\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n const compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);\n maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);\n minPtsDelta = Math.min(minPtsDelta, ptsDelta);\n maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);\n\n outputSamples.push(\n new Mp4Sample(\n avcSample.key,\n mp4SampleDuration,\n mp4SampleLength,\n compositionTimeOffset\n )\n );\n }\n\n if (outputSamples.length) {\n if (chromeVersion) {\n if (chromeVersion < 70) {\n // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n const flags = outputSamples[0].flags;\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n } else if (safariWebkitVersion) {\n // Fix for \"CNN special report, with CC\" in test-streams (Safari browser only)\n // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.\n if (\n maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta &&\n averageSampleDuration / maxDtsDelta < 0.025 &&\n outputSamples[0].cts === 0\n ) {\n logger.warn(\n 'Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.'\n );\n let dts = firstDTS;\n for (let i = 0, len = outputSamples.length; i < len; i++) {\n const nextDts = dts + outputSamples[i].duration;\n const pts = dts + outputSamples[i].cts;\n if (i < len - 1) {\n const nextPts = nextDts + outputSamples[i + 1].cts;\n outputSamples[i].duration = nextPts - pts;\n } else {\n outputSamples[i].duration = i\n ? outputSamples[i - 1].duration\n : averageSampleDuration;\n }\n outputSamples[i].cts = 0;\n dts = nextDts;\n }\n }\n }\n }\n\n console.assert(\n mp4SampleDuration !== null,\n 'mp4SampleDuration must be computed'\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\n track.samples = [];\n track.dropped = 0;\n\n console.assert(mdat.length, 'MDAT length must not be zero');\n\n return data;\n }\n\n remuxAudio(\n track: DemuxedAudioTrack,\n timeOffset: number,\n contiguous: boolean,\n accurateTimeOffset: boolean,\n videoTimeOffset?: number\n ): RemuxedTrack | undefined {\n const inputTimeScale: number = track.inputTimeScale;\n const mp4timeScale: number = track.samplerate\n ? track.samplerate\n : inputTimeScale;\n const scaleFactor: number = inputTimeScale / mp4timeScale;\n const mp4SampleDuration: number =\n track.segmentCodec === 'aac'\n ? AAC_SAMPLES_PER_FRAME\n : MPEG_AUDIO_SAMPLE_PER_FRAME;\n const inputSampleDuration: number = mp4SampleDuration * scaleFactor;\n const initPTS: number = this._initPTS;\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 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 - initPTS, 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 - initPTS, 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 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\n console.assert(mdat.length, 'MDAT length must not be zero');\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 startDTS: number =\n (nextAudioPts !== null\n ? nextAudioPts\n : videoData.startDTS * inputTimeScale) + this._initDTS;\n const endDTS: number = videoData.endDTS * inputTimeScale + this._initDTS;\n // one sample's duration value\n const frameDuration: number = scaleFactor * AAC_SAMPLES_PER_FRAME;\n // samples count of this segment's duration\n const nbSamples: number = Math.ceil((endDTS - startDTS) / frameDuration);\n // silent frame\n const silentFrame: Uint8Array | undefined = AAC.getSilentFrame(\n track.manifestCodec || track.codec,\n track.channelCount\n );\n\n logger.warn('[mp4-remuxer]: remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace(\n '[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec'\n );\n return;\n }\n\n const samples: Array<any> = [];\n for (let i = 0; i < nbSamples; i++) {\n const stamp = startDTS + i * frameDuration;\n samples.push({ unit: silentFrame, pts: stamp, dts: stamp });\n }\n track.samples = samples;\n\n return this.remuxAudio(track, timeOffset, contiguous, false);\n }\n}\n\nexport function normalizePts(value: number, reference: number | null): number {\n let offset;\n if (reference === null) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n}\n\nfunction findKeyframeIndex(samples: Array<AvcSample>): number {\n for (let i = 0; i < samples.length; i++) {\n if (samples[i].key) {\n return i;\n }\n }\n return -1;\n}\n\nexport function flushTextTrackMetadataCueSamples(\n track: DemuxedMetadataTrack,\n timeOffset: number,\n initPTS: number,\n initDTS: number\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(sample.pts - initPTS, timeOffset * inputTimeScale) /\n inputTimeScale;\n sample.dts =\n normalizePts(sample.dts - initDTS, 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: number\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(sample.pts - initPTS, timeOffset * inputTimeScale) /\n inputTimeScale;\n }\n track.samples.sort((a, b) => a.pts - b.pts);\n const samples = track.samples;\n track.samples = [];\n return {\n samples,\n };\n}\n\nclass Mp4Sample {\n public size: number;\n public duration: number;\n public cts: number;\n public flags: Mp4SampleFlags;\n\n constructor(\n isKeyframe: boolean,\n duration: number,\n size: number,\n cts: number\n ) {\n this.duration = duration;\n this.size = size;\n this.cts = cts;\n this.flags = new Mp4SampleFlags(isKeyframe);\n }\n}\n\nclass Mp4SampleFlags {\n public isLeading: 0 = 0;\n public isDependedOn: 0 = 0;\n public hasRedundancy: 0 = 0;\n public degradPrio: 0 = 0;\n public dependsOn: 1 | 2 = 1;\n public isNonSync: 0 | 1 = 1;\n\n constructor(isKeyframe) {\n this.dependsOn = isKeyframe ? 2 : 1;\n this.isNonSync = isKeyframe ? 0 : 1;\n }\n}\n","import {\n flushTextTrackMetadataCueSamples,\n flushTextTrackUserdataCueSamples,\n} from './mp4-remuxer';\nimport type { InitData, InitDataTrack } from '../utils/mp4-tools';\nimport {\n getDuration,\n getStartDTS,\n offsetStartDTS,\n parseInitSegment,\n} from '../utils/mp4-tools';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport { logger } from '../utils/logger';\nimport type { TrackSet } from '../types/track';\nimport type {\n InitSegmentData,\n RemuxedTrack,\n Remuxer,\n RemuxerResult,\n} from '../types/remuxer';\nimport type {\n DemuxedAudioTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n PassthroughTrack,\n} from '../types/demuxer';\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?: number;\n private initTracks?: TrackSet;\n private lastEndTime: number | null = null;\n\n public destroy() {}\n\n public resetTimeStamp(defaultInitPTS) {\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 ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.generateInitSegment(initSegment);\n this.emitInitSegment = true;\n }\n\n private generateInitSegment(initSegment: Uint8Array | undefined): void {\n let { audioCodec, videoCodec } = this;\n if (!initSegment || !initSegment.byteLength) {\n this.initTracks = undefined;\n this.initData = undefined;\n return;\n }\n const initData = (this.initData = parseInitSegment(initSegment));\n\n // Get codec from initSegment or fallback to default\n if (!audioCodec) {\n audioCodec = getParsedTrackCodec(\n initData.audio,\n ElementaryStreamTypes.AUDIO\n );\n }\n\n if (!videoCodec) {\n videoCodec = getParsedTrackCodec(\n initData.video,\n ElementaryStreamTypes.VIDEO\n );\n }\n\n const tracks: TrackSet = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = {\n container: 'video/mp4',\n codec: audioCodec + ',' + videoCodec,\n initSegment,\n id: 'main',\n };\n } else if (initData.audio) {\n tracks.audio = {\n container: 'audio/mp4',\n codec: audioCodec,\n initSegment,\n id: 'audio',\n };\n } else if (initData.video) {\n tracks.video = {\n container: 'video/mp4',\n codec: videoCodec,\n initSegment,\n id: 'main',\n };\n } else {\n logger.warn(\n '[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.'\n );\n }\n this.initTracks = tracks;\n }\n\n public remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: PassthroughTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number\n ): 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 || !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 || !initData.length) {\n this.generateInitSegment(data);\n initData = this.initData;\n }\n if (!initData || !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 startDTS = getStartDTS(initData, data);\n if (!Number.isFinite(initPTS!)) {\n this.initPTS = initSegment.initPTS = initPTS = startDTS - timeOffset;\n }\n\n const duration = getDuration(data, initData);\n const startTime = audioTrack\n ? startDTS - (initPTS as number)\n : (lastEndTime as number);\n const endTime = startTime + duration;\n offsetStartDTS(initData, data, initPTS as number);\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 const initPtsNum = this.initPTS ?? 0;\n result.id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n initPtsNum,\n initPtsNum\n );\n\n if (textTrack.samples.length) {\n result.text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n initPtsNum\n );\n }\n\n return result;\n }\n}\n\nfunction getParsedTrackCodec(\n track: InitDataTrack | undefined,\n type: ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO\n): string {\n const parsedCodec = track?.codec;\n if (parsedCodec && parsedCodec.length > 4) {\n return parsedCodec;\n }\n // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)\n // Provide defaults based on codec type\n // This allows for some playback of some fmp4 playlists without CODECS defined in manifest\n if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {\n return 'hvc1.1.c.L120.90';\n }\n if (parsedCodec === 'av01') {\n return 'av01.0.04M.08';\n }\n if (parsedCodec === 'avc1' || type === ElementaryStreamTypes.VIDEO) {\n return 'avc1.42e01e';\n }\n return 'mp4a.40.5';\n}\nexport default PassThroughRemuxer;\n","/**\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 /**\n * @returns {boolean}\n */\n public hasInterval(): boolean {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n public hasNextTick(): boolean {\n return !!this._tickTimer;\n }\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} 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._tickInterval = self.setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} 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 {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n public clearNextTick(): boolean {\n if (this._tickTimer) {\n self.clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n public tick(): void {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.tickImmediate();\n }\n this._tickCallCount = 0;\n }\n }\n\n public tickImmediate(): void {\n this.clearNextTick();\n this._tickTimer = self.setTimeout(this._boundTick, 0);\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n protected doTick(): void {}\n}\n","/**\n * CMCD spec version\n */\nexport const CMCDVersion = 1;\n\n/**\n * CMCD Object Type\n */\nexport enum CMCDObjectType {\n MANIFEST = 'm',\n AUDIO = 'a',\n VIDEO = 'v',\n MUXED = 'av',\n INIT = 'i',\n CAPTION = 'c',\n TIMED_TEXT = 'tt',\n KEY = 'k',\n OTHER = 'o',\n}\n\n/**\n * CMCD Streaming Format\n */\nexport enum CMCDStreamingFormat {\n DASH = 'd',\n HLS = 'h',\n SMOOTH = 's',\n OTHER = 'o',\n}\n\n/**\n * CMCD Streaming Type\n */\nexport enum CMCDStreamType {\n VOD = 'v',\n LIVE = 'l',\n}\n\n/**\n * CMCD Headers\n */\nexport interface CMCDHeaders {\n 'CMCD-Object': string;\n 'CMCD-Request': string;\n 'CMCD-Session': string;\n 'CMCD-Status': string;\n}\n\n/**\n * CMCD\n */\nexport interface CMCD {\n /////////////////\n // CMCD Object //\n /////////////////\n\n /**\n * Encoded bitrate\n *\n * The encoded bitrate of the audio or video object being requested. This may not be known precisely by the player; however,\n * it MAY be estimated based upon playlist/manifest declarations. If the playlist declares both peak and average bitrate values,\n * the peak value should be transmitted.\n *\n * Integer kbps\n */\n br?: number;\n\n /**\n * Object duration\n *\n * The playback duration in milliseconds of the object being requested. If a partial segment is being requested, then this value\n * MUST indicate the playback duration of that part and not that of its parent segment. This value can be an approximation of the\n * estimated duration if the explicit value is not known.\n *\n * Integer milliseconds\n */\n d?: number;\n\n /**\n * Object type\n *\n * The media type of the current object being requested:\n * - `m` = text file, such as a manifest or playlist\n * - `a` = audio only\n * - `v` = video only\n * - `av` = muxed audio and video\n * - `i` = init segment\n * - `c` = caption or subtitle\n * - `tt` = ISOBMFF timed text track\n * - `k` = cryptographic key, license or certificate.\n * - `o` = other\n *\n * If the object type being requested is unknown, then this key MUST NOT be used.\n */\n ot?: CMCDObjectType;\n\n /**\n * Top bitrate\n *\n * The highest bitrate rendition in the manifest or playlist that the client is allowed to play, given current codec, licensing and\n * sizing constraints.\n *\n * Integer Kbps\n */\n tb?: number;\n\n //////////////////\n // CMCD Request //\n //////////////////\n /**\n * Buffer length\n *\n * The buffer length associated with the media object being requested. This value MUST be rounded to the nearest 100 ms. This key SHOULD only be\n * sent with an object type of ‘a’, ‘v’ or ‘av’.\n *\n * Integer milliseconds\n */\n bl?: number;\n\n /**\n * Deadline\n *\n * Deadline from the request time until the first sample of this Segment/Object needs to be available in order to not create a buffer underrun or\n * any other playback problems. This value MUST be rounded to the nearest 100ms. For a playback rate of 1, this may be equivalent to the player’s\n * remaining buffer length.\n *\n * Integer milliseconds\n */\n dl?: number;\n\n /**\n * Measured mtp CMCD throughput\n *\n * The throughput between client and server, as measured by the client and MUST be rounded to the nearest 100 kbps. This value, however derived,\n * SHOULD be the value that the client is using to make its next Adaptive Bitrate switching decision. If the client is connected to multiple\n * servers concurrently, it must take care to report only the throughput measured against the receiving server. If the client has multiple concurrent\n * connections to the server, then the intent is that this value communicates the aggregate throughput the client sees across all those connections.\n *\n * Integer kbps\n */\n mtp?: number;\n\n /**\n * Next object request\n *\n * Relative path of the next object to be requested. This can be used to trigger pre-fetching by the CDN. This MUST be a path relative to the current\n * request. This string MUST be URLEncoded. The client SHOULD NOT depend upon any pre-fetch action being taken - it is merely a request for such a\n * pre-fetch to take place.\n *\n * String\n */\n nor?: string;\n\n /**\n * Next range request\n *\n * If the next request will be a partial object request, then this string denotes the byte range to be requested. If the ‘nor’ field is not set, then the\n * object is assumed to match the object currently being requested. The client SHOULD NOT depend upon any pre-fetch action being taken – it is merely a\n * request for such a pre-fetch to take place. Formatting is similar to the HTTP Range header, except that the unit MUST be ‘byte’, the ‘Range:’ prefix is\n * NOT required and specifying multiple ranges is NOT allowed. Valid combinations are:\n *\n * - `\"\\<range-start\\>-\"`\n * - `\"\\<range-start\\>-\\<range-end\\>\"`\n * - `\"-\\<suffix-length\\>\"`\n *\n * String\n */\n nrr?: string;\n\n /**\n * Startup\n *\n * Key is included without a value if the object is needed urgently due to startup, seeking or recovery after a buffer-empty event. The media SHOULD not be\n * rendering when this request is made. This key MUST not be sent if it is FALSE.\n *\n * Boolean\n */\n su?: boolean;\n\n //////////////////\n // CMCD Session //\n //////////////////\n\n /**\n * Content ID\n *\n * A unique string identifying the current content. Maximum length is 64 characters. This value is consistent across multiple different\n * sessions and devices and is defined and updated at the discretion of the service provider.\n *\n * String\n */\n cid?: string;\n\n /**\n * Playback rate\n *\n * `1` if real-time, `2` if double speed, `0` if not playing. SHOULD only be sent if not equal to `1`.\n *\n * Decimal\n */\n pr?: number;\n\n /**\n * Streaming format\n *\n * The streaming format that defines the current request.\n *\n * - `d` = MPEG DASH\n * - `h` = HTTP Live Streaming (HLS)\n * - `s` = Smooth Streaming\n * - `o` = other\n *\n * If the streaming format being requested is unknown, then this key MUST NOT be used.\n */\n sf?: CMCDStreamingFormat;\n\n /**\n * Session ID\n *\n * A GUID identifying the current playback session. A playback session typically ties together segments belonging to a single media asset.\n * Maximum length is 64 characters. It is RECOMMENDED to conform to the UUID specification.\n *\n * String\n */\n sid?: string;\n\n /**\n * Stream type\n * - `v` = all segments are available – e.g., VOD\n * - `l` = segments become available over time – e.g., LIVE\n */\n st?: CMCDStreamType;\n\n /**\n * CMCD version\n *\n * The version of this specification used for interpreting the defined key names and values. If this key is omitted, the client and server MUST\n * interpret the values as being defined by version 1. Client SHOULD omit this field if the version is 1.\n *\n * Integer\n */\n v?: number;\n\n /////////////////\n // CMCD Status //\n /////////////////\n\n /**\n * Buffer starvation\n *\n * Key is included without a value if the buffer was starved at some point between the prior request and this object request,\n * resulting in the player being in a rebuffering state and the video or audio playback being stalled. This key MUST NOT be\n * sent if the buffer was not starved since the prior request.\n *\n * If the object type `ot` key is sent along with this key, then the `bs` key refers to the buffer associated with the particular\n * object type. If no object type is communicated, then the buffer state applies to the current session.\n *\n * Boolean\n */\n bs?: boolean;\n\n /**\n * Requested maximum throughput\n *\n * The requested maximum throughput that the client considers sufficient for delivery of the asset. Values MUST be rounded to the\n * nearest 100kbps. For example, a client would indicate that the current segment, encoded at 2Mbps, is to be delivered at no more\n * than 10Mbps, by using rtp=10000.\n *\n * Note: This can benefit clients by preventing buffer saturation through over-delivery and can also deliver a community benefit\n * through fair-share delivery. The concept is that each client receives the throughput necessary for great performance, but no more.\n * The CDN may not support the rtp feature.\n *\n * Integer kbps\n */\n rtp?: number;\n}\n","export 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?: number | null): void;\n resetContiguity(): void;\n}\n\nexport interface DemuxerResult {\n audioTrack: DemuxedAudioTrack;\n videoTrack: DemuxedVideoTrack;\n id3Track: DemuxedMetadataTrack;\n textTrack: DemuxedUserdataTrack;\n}\n\nexport interface DemuxedTrack {\n type: string;\n id: number;\n pid: number;\n inputTimeScale: number;\n sequenceNumber: number;\n samples:\n | AudioSample[]\n | AvcSample[]\n | MetadataSample[]\n | UserdataSample[]\n | Uint8Array;\n timescale?: number;\n container?: string;\n dropped: number;\n duration?: number;\n pesData?: ElementaryStreamData | null;\n codec?: string;\n}\n\nexport interface PassthroughTrack extends DemuxedTrack {\n sampleDuration: number;\n samples: Uint8Array;\n timescale: number;\n duration: number;\n codec: string;\n}\nexport interface DemuxedAudioTrack extends DemuxedTrack {\n config?: number[];\n samplerate?: number;\n segmentCodec?: string;\n channelCount?: number;\n manifestCodec?: string;\n samples: AudioSample[];\n}\n\nexport interface DemuxedVideoTrack extends DemuxedTrack {\n width?: number;\n height?: number;\n pixelRatio?: [number, number];\n audFound?: boolean;\n pps?: number[];\n sps?: number[];\n naluState?: number;\n samples: AvcSample[] | Uint8Array;\n}\n\nexport interface DemuxedAvcTrack extends DemuxedVideoTrack {\n samples: AvcSample[];\n}\n\nexport interface DemuxedMetadataTrack extends DemuxedTrack {\n samples: MetadataSample[];\n}\n\nexport interface DemuxedUserdataTrack extends DemuxedTrack {\n samples: UserdataSample[];\n}\n\nexport enum MetadataSchema {\n audioId3 = 'org.id3',\n dateRange = 'com.apple.quicktime.HLS',\n emsg = 'https://aomedia.org/emsg/ID3',\n}\nexport interface MetadataSample {\n pts: number;\n dts: number;\n duration: number;\n len?: number;\n data: Uint8Array;\n type: MetadataSchema;\n}\n\nexport interface UserdataSample {\n pts: number;\n bytes?: Uint8Array;\n type?: number;\n payloadType?: number;\n uuid?: string;\n userData?: string;\n userDataBytes?: Uint8Array;\n}\n\nexport interface AvcSample {\n dts: number;\n pts: number;\n key: boolean;\n frame: boolean;\n units: AvcSampleUnit[];\n debug: string;\n length: number;\n}\n\nexport interface AvcSampleUnit {\n data: Uint8Array;\n type: number;\n}\n\nexport type AudioSample = {\n unit: Uint8Array;\n pts: number;\n};\n\nexport type AudioFrame = {\n sample: AudioSample;\n length: number;\n missing: number;\n};\n\nexport interface ElementaryStreamData {\n data: Uint8Array[];\n size: number;\n}\n\nexport interface KeyData {\n method: string;\n key: Uint8Array;\n iv: Uint8Array;\n}\n","import { LevelDetails } from '../loader/level-details';\nimport { AttrList } from '../utils/attr-list';\n\nexport interface LevelParsed {\n attrs: LevelAttributes;\n audioCodec?: string;\n bitrate: number;\n details?: LevelDetails;\n height?: number;\n id?: number;\n level?: number;\n name: string;\n textCodec?: string;\n unknownCodecs?: string[];\n url: string;\n videoCodec?: string;\n width?: number;\n}\n\nexport interface LevelAttributes extends AttrList {\n AUDIO?: string;\n AUTOSELECT?: string;\n 'AVERAGE-BANDWIDTH'?: string;\n BANDWIDTH?: string;\n BYTERANGE?: string;\n 'CLOSED-CAPTIONS'?: string;\n CHARACTERISTICS?: string;\n CODECS?: string;\n DEFAULT?: string;\n FORCED?: string;\n 'FRAME-RATE'?: string;\n LANGUAGE?: string;\n NAME?: string;\n 'PROGRAM-ID'?: string;\n RESOLUTION?: string;\n SUBTITLES?: string;\n TYPE?: string;\n URI?: string;\n}\n\nexport enum HlsSkip {\n No = '',\n Yes = 'YES',\n v2 = 'v2',\n}\n\nexport function getSkipValue(details: LevelDetails, msn?: number): HlsSkip {\n const { canSkipUntil, canSkipDateRanges, endSN } = details;\n const snChangeGoal = msn !== undefined ? msn - endSN : 0;\n if (canSkipUntil && snChangeGoal < canSkipUntil) {\n if (canSkipDateRanges) {\n return HlsSkip.v2;\n }\n return HlsSkip.Yes;\n }\n return HlsSkip.No;\n}\n\nexport class HlsUrlParameters {\n msn?: number;\n part?: number;\n skip?: HlsSkip;\n\n constructor(msn?: number, part?: number, skip?: HlsSkip) {\n this.msn = msn;\n this.part = part;\n this.skip = skip;\n }\n\n addDirectives(uri: string): string | never {\n const url: URL = new self.URL(uri);\n if (this.msn !== undefined) {\n url.searchParams.set('_HLS_msn', this.msn.toString());\n }\n if (this.part !== undefined) {\n url.searchParams.set('_HLS_part', this.part.toString());\n }\n if (this.skip) {\n url.searchParams.set('_HLS_skip', this.skip);\n }\n return url.toString();\n }\n}\n\nexport class Level {\n public readonly attrs: LevelAttributes;\n public readonly audioCodec: string | undefined;\n public readonly bitrate: number;\n public readonly codecSet: string;\n public readonly height: number;\n public readonly id: number;\n public readonly name: string | undefined;\n public readonly videoCodec: string | undefined;\n public readonly width: number;\n public readonly unknownCodecs: string[] | undefined;\n public audioGroupIds?: string[];\n public details?: LevelDetails;\n public fragmentError: number = 0;\n public loadError: number = 0;\n public loaded?: { bytes: number; duration: number };\n public realBitrate: number = 0;\n public textGroupIds?: string[];\n public url: string[];\n private _urlId: number = 0;\n\n constructor(data: LevelParsed) {\n this.url = [data.url];\n this.attrs = data.attrs;\n this.bitrate = data.bitrate;\n if (data.details) {\n this.details = data.details;\n }\n this.id = data.id || 0;\n this.name = data.name;\n this.width = data.width || 0;\n this.height = data.height || 0;\n this.audioCodec = data.audioCodec;\n this.videoCodec = data.videoCodec;\n this.unknownCodecs = data.unknownCodecs;\n this.codecSet = [data.videoCodec, data.audioCodec]\n .filter((c) => c)\n .join(',')\n .replace(/\\.[^.,]+/g, '');\n }\n\n get maxBitrate(): number {\n return Math.max(this.realBitrate, this.bitrate);\n }\n\n get uri(): string {\n return this.url[this._urlId] || '';\n }\n\n get urlId(): number {\n return this._urlId;\n }\n\n set urlId(value: number) {\n const newValue = value % this.url.length;\n if (this._urlId !== newValue) {\n this.details = undefined;\n this._urlId = newValue;\n }\n }\n}\n","import type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\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 FragmentLoaderContext {}\n\nexport interface LoaderConfiguration {\n // Max number of load retries\n maxRetry: number;\n // Timeout after which `onTimeOut` callback will be triggered\n // (if loading is still not finished after that delay)\n timeout: number;\n // Delay between an I/O error and following connection retry (ms).\n // This to avoid spamming the server\n retryDelay: number;\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;\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) => void;\n\nexport type LoaderOnTimeout<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\nexport type LoaderOnAbort<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\nexport interface LoaderCallbacks<T extends LoaderContext> {\n onSuccess: LoaderOnSuccess<T>;\n onError: LoaderOnError<T>;\n onTimeout: LoaderOnTimeout<T>;\n onAbort?: LoaderOnAbort<T>;\n onProgress?: LoaderOnProgress<T>;\n}\n\nexport interface Loader<T extends LoaderContext> {\n destroy(): void;\n abort(): void;\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<T>\n ): void;\n /**\n * `getCacheAge()` is called by hls.js to get the duration that a given object\n * has been sitting in a cache proxy when playing live. If implemented,\n * this should return a value in seconds.\n *\n * For HTTP based loaders, this should return the contents of the \"age\" header.\n *\n * @returns time object being lodaded\n */\n getCacheAge?: () => number | null;\n context: T;\n stats: LoaderStats;\n}\n\nexport enum PlaylistContextType {\n MANIFEST = 'manifest',\n LEVEL = 'level',\n AUDIO_TRACK = 'audioTrack',\n SUBTITLE_TRACK = 'subtitleTrack',\n}\n\nexport enum PlaylistLevelType {\n MAIN = 'main',\n AUDIO = 'audio',\n SUBTITLE = 'subtitle',\n}\n\nexport interface PlaylistLoaderContext extends LoaderContext {\n loader?: Loader<PlaylistLoaderContext>;\n\n type: PlaylistContextType;\n // the level index to load\n level: number | null;\n // level or track id from LevelLoadingData / TrackLoadingData\n id: number | null;\n // track group id\n groupId: string | null;\n // defines if the loader is handling a sidx request for the playlist\n isSidxRequest?: boolean;\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","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","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nexport class AttrList {\n [key: string]: any;\n\n constructor(attrs: string | Record<string, any>) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (const attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n decimalInteger(attrName: string): number {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n hexadecimalInteger(attrName: string) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber(attrName: string): number {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n decimalFloatingPoint(attrName: string): number {\n return parseFloat(this[attrName]);\n }\n\n optionalFloat(attrName: string, defaultValue: number): number {\n const value = this[attrName];\n return value ? parseFloat(value) : defaultValue;\n }\n\n enumeratedString(attrName: string): string | undefined {\n return this[attrName];\n }\n\n bool(attrName: string): boolean {\n return this[attrName] === 'YES';\n }\n\n decimalResolution(attrName: string):\n | {\n width: number;\n height: number;\n }\n | undefined {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10),\n };\n }\n\n static parseAttrList(input: string): Record<string, any> {\n let match;\n const attrs = {};\n const quote = '\"';\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let value = match[2];\n\n if (\n value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === value.length - 1\n ) {\n value = value.slice(1, -1);\n }\n\n attrs[match[1]] = value;\n }\n return attrs;\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 {Array<T>} list The array to search.\n * @param {BinarySearchComparison<T>} 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 * @return {T | null} The object if it is found or null otherwise.\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","/**\n * @module BufferHelper\n *\n * Providing 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 * @param {Bufferable} media\n * @param {number} position\n * @returns {boolean}\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 OutputFilter from './output-filter';\nimport { logger } from '../utils/logger';\n\n/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nconst specialCea608CharsCodes = {\n 0x2a: 0xe1, // lowercase a, acute accent\n 0x5c: 0xe9, // lowercase e, acute accent\n 0x5e: 0xed, // lowercase i, acute accent\n 0x5f: 0xf3, // lowercase o, acute accent\n 0x60: 0xfa, // lowercase u, acute accent\n 0x7b: 0xe7, // lowercase c with cedilla\n 0x7c: 0xf7, // division symbol\n 0x7d: 0xd1, // uppercase N tilde\n 0x7e: 0xf1, // lowercase n tilde\n 0x7f: 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80: 0xae, // Registered symbol (R)\n 0x81: 0xb0, // degree sign\n 0x82: 0xbd, // 1/2 symbol\n 0x83: 0xbf, // Inverted (open) question mark\n 0x84: 0x2122, // Trademark symbol (TM)\n 0x85: 0xa2, // Cents symbol\n 0x86: 0xa3, // Pounds sterling\n 0x87: 0x266a, // Music 8'th note\n 0x88: 0xe0, // lowercase a, grave accent\n 0x89: 0x20, // transparent space (regular)\n 0x8a: 0xe8, // lowercase e, grave accent\n 0x8b: 0xe2, // lowercase a, circumflex accent\n 0x8c: 0xea, // lowercase e, circumflex accent\n 0x8d: 0xee, // lowercase i, circumflex accent\n 0x8e: 0xf4, // lowercase o, circumflex accent\n 0x8f: 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90: 0xc1, // capital letter A with acute\n 0x91: 0xc9, // capital letter E with acute\n 0x92: 0xd3, // capital letter O with acute\n 0x93: 0xda, // capital letter U with acute\n 0x94: 0xdc, // capital letter U with diaresis\n 0x95: 0xfc, // lowercase letter U with diaeresis\n 0x96: 0x2018, // opening single quote\n 0x97: 0xa1, // inverted exclamation mark\n 0x98: 0x2a, // asterisk\n 0x99: 0x2019, // closing single quote\n 0x9a: 0x2501, // box drawings heavy horizontal\n 0x9b: 0xa9, // copyright sign\n 0x9c: 0x2120, // Service mark\n 0x9d: 0x2022, // (round) bullet\n 0x9e: 0x201c, // Left double quotation mark\n 0x9f: 0x201d, // Right double quotation mark\n 0xa0: 0xc0, // uppercase A, grave accent\n 0xa1: 0xc2, // uppercase A, circumflex\n 0xa2: 0xc7, // uppercase C with cedilla\n 0xa3: 0xc8, // uppercase E, grave accent\n 0xa4: 0xca, // uppercase E, circumflex\n 0xa5: 0xcb, // capital letter E with diaresis\n 0xa6: 0xeb, // lowercase letter e with diaresis\n 0xa7: 0xce, // uppercase I, circumflex\n 0xa8: 0xcf, // uppercase I, with diaresis\n 0xa9: 0xef, // lowercase i, with diaresis\n 0xaa: 0xd4, // uppercase O, circumflex\n 0xab: 0xd9, // uppercase U, grave accent\n 0xac: 0xf9, // lowercase u, grave accent\n 0xad: 0xdb, // uppercase U, circumflex\n 0xae: 0xab, // left-pointing double angle quotation mark\n 0xaf: 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0: 0xc3, // Uppercase A, tilde\n 0xb1: 0xe3, // Lowercase a, tilde\n 0xb2: 0xcd, // Uppercase I, acute accent\n 0xb3: 0xcc, // Uppercase I, grave accent\n 0xb4: 0xec, // Lowercase i, grave accent\n 0xb5: 0xd2, // Uppercase O, grave accent\n 0xb6: 0xf2, // Lowercase o, grave accent\n 0xb7: 0xd5, // Uppercase O, tilde\n 0xb8: 0xf5, // Lowercase o, tilde\n 0xb9: 0x7b, // Open curly brace\n 0xba: 0x7d, // Closing curly brace\n 0xbb: 0x5c, // Backslash\n 0xbc: 0x5e, // Caret\n 0xbd: 0x5f, // Underscore\n 0xbe: 0x7c, // Pipe (vertical line)\n 0xbf: 0x223c, // Tilde operator\n 0xc0: 0xc4, // Uppercase A, umlaut\n 0xc1: 0xe4, // Lowercase A, umlaut\n 0xc2: 0xd6, // Uppercase O, umlaut\n 0xc3: 0xf6, // Lowercase o, umlaut\n 0xc4: 0xdf, // Esszett (sharp S)\n 0xc5: 0xa5, // Yen symbol\n 0xc6: 0xa4, // Generic currency sign\n 0xc7: 0x2503, // Box drawings heavy vertical\n 0xc8: 0xc5, // Uppercase A, ring\n 0xc9: 0xe5, // Lowercase A, ring\n 0xca: 0xd8, // Uppercase O, stroke\n 0xcb: 0xf8, // Lowercase o, strok\n 0xcc: 0x250f, // Box drawings heavy down and right\n 0xcd: 0x2513, // Box drawings heavy down and left\n 0xce: 0x2517, // Box drawings heavy up and right\n 0xcf: 0x251b, // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nconst getCharForByte = function (byte: number) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nconst NR_ROWS = 15;\nconst NR_COLS = 100;\n// Tables to look up row from PAC data\nconst rowsLowCh1 = {\n 0x11: 1,\n 0x12: 3,\n 0x15: 5,\n 0x16: 7,\n 0x17: 9,\n 0x10: 11,\n 0x13: 12,\n 0x14: 14,\n};\nconst rowsHighCh1 = {\n 0x11: 2,\n 0x12: 4,\n 0x15: 6,\n 0x16: 8,\n 0x17: 10,\n 0x13: 13,\n 0x14: 15,\n};\nconst rowsLowCh2 = {\n 0x19: 1,\n 0x1a: 3,\n 0x1d: 5,\n 0x1e: 7,\n 0x1f: 9,\n 0x18: 11,\n 0x1b: 12,\n 0x1c: 14,\n};\nconst rowsHighCh2 = {\n 0x19: 2,\n 0x1a: 4,\n 0x1d: 6,\n 0x1e: 8,\n 0x1f: 10,\n 0x1b: 13,\n 0x1c: 15,\n};\n\nconst backgroundColors = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n 'black',\n 'transparent',\n];\n\nenum VerboseLevel {\n ERROR = 0,\n TEXT = 1,\n WARNING = 2,\n INFO = 2,\n DEBUG = 3,\n DATA = 3,\n}\n\nclass CaptionsLogger {\n public time: number | null = null;\n public verboseLevel: VerboseLevel = VerboseLevel.ERROR;\n\n log(severity: VerboseLevel, msg: string | (() => string)): void {\n if (this.verboseLevel >= severity) {\n const m: string = typeof msg === 'function' ? msg() : msg;\n logger.log(`${this.time} [${severity}] ${m}`);\n }\n }\n}\n\nconst numArrayToHexArray = function (numArray: number[]): string[] {\n const hexArray: string[] = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\ntype PenStyles = {\n foreground: string | null;\n underline: boolean;\n italics: boolean;\n background: string;\n flash: boolean;\n};\n\nclass PenState {\n public foreground: string;\n public underline: boolean;\n public italics: boolean;\n public background: string;\n public flash: boolean;\n\n constructor(\n foreground?: string,\n underline?: boolean,\n italics?: boolean,\n background?: string,\n flash?: boolean\n ) {\n this.foreground = foreground || 'white';\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || 'black';\n this.flash = flash || false;\n }\n\n reset() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles(styles: Partial<PenStyles>) {\n const attribs = [\n 'foreground',\n 'underline',\n 'italics',\n 'background',\n 'flash',\n ];\n for (let i = 0; i < attribs.length; i++) {\n const style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault() {\n return (\n this.foreground === 'white' &&\n !this.underline &&\n !this.italics &&\n this.background === 'black' &&\n !this.flash\n );\n }\n\n equals(other: PenState) {\n return (\n this.foreground === other.foreground &&\n this.underline === other.underline &&\n this.italics === other.italics &&\n this.background === other.background &&\n this.flash === other.flash\n );\n }\n\n copy(newPenState: PenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n\n toString(): string {\n return (\n 'color=' +\n this.foreground +\n ', underline=' +\n this.underline +\n ', italics=' +\n this.italics +\n ', background=' +\n this.background +\n ', flash=' +\n this.flash\n );\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar {\n uchar: string;\n penState: PenState;\n\n constructor(\n uchar?: string,\n foreground?: string,\n underline?: boolean,\n italics?: boolean,\n background?: string,\n flash?: boolean\n ) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(\n foreground,\n underline,\n italics,\n background,\n flash\n );\n }\n\n reset() {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar(uchar: string, newPenState: PenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState(newPenState: PenState) {\n this.penState.copy(newPenState);\n }\n\n equals(other: StyledUnicodeChar) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy(newChar: StyledUnicodeChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty(): boolean {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nexport class Row {\n public chars: StyledUnicodeChar[];\n public pos: number;\n public currPenState: PenState;\n public cueStartTime?: number;\n logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n this.chars = [];\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.logger = logger;\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals(other: Row) {\n let equal = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other: Row) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty(): boolean {\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor(absPos: number) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n\n if (this.pos < 0) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Negative cursor position ' + this.pos\n );\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Too large cursor position ' + this.pos\n );\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor(relPos: number) {\n const newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let i = this.pos + 1; i < newPos + 1; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace() {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar(byte: number) {\n if (byte >= 0x90) {\n // Extended char\n this.backSpace();\n }\n const char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n this.logger.log(\n VerboseLevel.ERROR,\n () =>\n 'Cannot insert ' +\n byte.toString(16) +\n ' (' +\n char +\n ') at position ' +\n this.pos +\n '. Skipping it!'\n );\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n\n clearFromPos(startPos: number) {\n let i: number;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n }\n\n clear() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow() {\n this.clearFromPos(this.pos);\n }\n\n getTextString() {\n const chars: string[] = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n const char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles(styles: Partial<PenStyles>) {\n this.currPenState.setStyles(styles);\n const currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n */\nexport class CaptionScreen {\n rows: Row[];\n currRow: number;\n nrRollUpRows: number | null;\n lastOutputScreen: CaptionScreen | null;\n logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row(logger));\n } // Note that we use zero-based numbering (0-14)\n\n this.logger = logger;\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.lastOutputScreen = null;\n this.reset();\n }\n\n reset() {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals(other: CaptionScreen): boolean {\n let equal = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other: CaptionScreen) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty(): boolean {\n let empty = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n backSpace() {\n const row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow() {\n const row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar(char: number) {\n const row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen(styles: Partial<PenStyles>) {\n const row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor(relPos: number) {\n const row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor(absPos: number) {\n this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);\n const row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC(pacData: PACData) {\n this.logger.log(\n VerboseLevel.INFO,\n () => 'pacData = ' + JSON.stringify(pacData)\n );\n let newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows - 1;\n }\n\n // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n // clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n const time = this.logger.time;\n if (prevLineTime && time !== null && prevLineTime < time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow - this.nrRollUpRows + i + 1].copy(\n lastOutputScreen.rows[topRowIndex + i]\n );\n }\n }\n }\n }\n\n this.currRow = newRow;\n const row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n const indent = pacData.indent;\n const prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n const styles: PenStyles = {\n foreground: pacData.color,\n underline: pacData.underline,\n italics: pacData.italics,\n background: 'black',\n flash: false,\n };\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData(bkgData: Partial<PenStyles>) {\n this.logger.log(\n VerboseLevel.INFO,\n () => 'bkgData = ' + JSON.stringify(bkgData)\n );\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n }\n\n setRollUpRows(nrRows: number | null) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp() {\n if (this.nrRollUpRows === null) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'roll_up but nrRollUpRows not set yet'\n );\n return; // Not properly setup\n }\n this.logger.log(VerboseLevel.TEXT, () => this.getDisplayText());\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n const topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n this.logger.log(VerboseLevel.INFO, 'Rolling up');\n // this.logger.log(VerboseLevel.TEXT, this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText(asOneRow?: boolean) {\n asOneRow = asOneRow || false;\n const displayText: string[] = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n const rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i + 1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + \": '\" + rowText + \"'\");\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n\n getTextAndFormat() {\n return this.rows;\n }\n}\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\ntype CaptionModes =\n | 'MODE_ROLL-UP'\n | 'MODE_POP-ON'\n | 'MODE_PAINT-ON'\n | 'MODE_TEXT'\n | null;\n\nclass Cea608Channel {\n chNr: number;\n outputFilter: OutputFilter;\n mode: CaptionModes;\n verbose: number;\n displayedMemory: CaptionScreen;\n nonDisplayedMemory: CaptionScreen;\n lastOutputScreen: CaptionScreen;\n currRollUpRow: Row;\n writeScreen: CaptionScreen;\n cueStartTime: number | null;\n logger: CaptionsLogger;\n\n constructor(\n channelNumber: number,\n outputFilter: OutputFilter,\n logger: CaptionsLogger\n ) {\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen(logger);\n this.nonDisplayedMemory = new CaptionScreen(logger);\n this.lastOutputScreen = new CaptionScreen(logger);\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n this.logger = logger;\n }\n\n reset() {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.outputFilter.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n }\n\n getHandler(): OutputFilter {\n return this.outputFilter;\n }\n\n setHandler(newHandler: OutputFilter) {\n this.outputFilter = newHandler;\n }\n\n setPAC(pacData: PACData) {\n this.writeScreen.setPAC(pacData);\n }\n\n setBkgData(bkgData: Partial<PenStyles>) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode(newMode: CaptionModes) {\n if (newMode === this.mode) {\n return;\n }\n\n this.mode = newMode;\n this.logger.log(VerboseLevel.INFO, () => 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n\n insertChars(chars: number[]) {\n for (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n const screen =\n this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n this.logger.log(\n VerboseLevel.INFO,\n () => screen + ': ' + this.writeScreen.getDisplayText(true)\n );\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n this.logger.log(\n VerboseLevel.TEXT,\n () => 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)\n );\n this.outputDataUpdate();\n }\n }\n\n ccRCL() {\n // Resume Caption Loading (switch mode to Pop On)\n this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS() {\n // BackSpace\n this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF() {\n // Reserved (formerly Alarm Off)\n }\n\n ccAON() {\n // Reserved (formerly Alarm On)\n }\n\n ccDER() {\n // Delete to End of Row\n this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU(nrRows: number | null) {\n // Roll-Up Captions-2,3,or 4 Rows\n this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n\n ccFON() {\n // Flash On\n this.logger.log(VerboseLevel.INFO, 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n }\n\n ccRDC() {\n // Resume Direct Captioning (switch mode to PaintOn)\n this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR() {\n // Text Restart in text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD() {\n // Resume Text Display in Text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM() {\n // Erase Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR() {\n // Carriage Return\n this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM() {\n // Erase Non-Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC() {\n // End of Caption (Flip Memories)\n this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n const tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n this.logger.log(\n VerboseLevel.TEXT,\n () => 'DISP: ' + this.displayedMemory.getDisplayText()\n );\n }\n this.outputDataUpdate(true);\n }\n\n ccTO(nrCols: number) {\n // Tab Offset 1,2, or 3 columns\n this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW(secondByte: number) {\n // Parse MIDROW command\n const styles: Partial<PenStyles> = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n const colorIndex = Math.floor(secondByte / 2) - 0x10;\n const colors = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n ];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate(dispatch: boolean = false) {\n const time = this.logger.time;\n if (time === null) {\n return;\n }\n\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {\n // Start of a new cue\n this.cueStartTime = time;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n this.outputFilter.newCue(\n this.cueStartTime!,\n time,\n this.lastOutputScreen\n );\n if (dispatch && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime(t: number) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime!, t, this.displayedMemory);\n }\n\n this.cueStartTime = t;\n }\n }\n }\n}\n\ninterface PACData {\n row: number;\n indent: number | null;\n color: string | null;\n underline: boolean;\n italics: boolean;\n}\n\ntype SupportedField = 1 | 3;\n\ntype Channels = 0 | 1 | 2; // Will be 1 or 2 when parsing captions\n\ntype CmdHistory = {\n a: number | null;\n b: number | null;\n};\n\nclass Cea608Parser {\n channels: Array<Cea608Channel | null>;\n currentChannel: Channels = 0;\n cmdHistory: CmdHistory;\n logger: CaptionsLogger;\n\n constructor(field: SupportedField, out1: OutputFilter, out2: OutputFilter) {\n const logger = new CaptionsLogger();\n this.channels = [\n null,\n new Cea608Channel(field, out1, logger),\n new Cea608Channel(field + 1, out2, logger),\n ];\n this.cmdHistory = createCmdHistory();\n this.logger = logger;\n }\n\n getHandler(channel: number) {\n return (this.channels[channel] as Cea608Channel).getHandler();\n }\n\n setHandler(channel: number, newHandler: OutputFilter) {\n (this.channels[channel] as Cea608Channel).setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData(time: number | null, byteList: number[]) {\n let cmdFound: boolean;\n let a: number;\n let b: number;\n let charsFound: number[] | boolean | null = false;\n\n this.logger.time = time;\n\n for (let i = 0; i < byteList.length; i += 2) {\n a = byteList[i] & 0x7f;\n b = byteList[i + 1] & 0x7f;\n if (a === 0 && b === 0) {\n continue;\n } else {\n this.logger.log(\n VerboseLevel.DATA,\n '[' +\n numArrayToHexArray([byteList[i], byteList[i + 1]]) +\n '] -> (' +\n numArrayToHexArray([a, b]) +\n ')'\n );\n }\n\n cmdFound = this.parseCmd(a, b);\n\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n const currChNr = this.currentChannel;\n if (currChNr && currChNr > 0) {\n const channel = this.channels[currChNr] as Cea608Channel;\n channel.insertChars(charsFound);\n } else {\n this.logger.log(\n VerboseLevel.WARNING,\n 'No channel found yet. TEXT-MODE?'\n );\n }\n }\n }\n if (!cmdFound && !charsFound) {\n this.logger.log(\n VerboseLevel.WARNING,\n \"Couldn't parse cleaned data \" +\n numArrayToHexArray([a, b]) +\n ' orig: ' +\n numArrayToHexArray([byteList[i], byteList[i + 1]])\n );\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns {Boolean} Tells if a command was found\n */\n parseCmd(a: number, b: number) {\n const { cmdHistory } = this;\n const cond1 =\n (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) &&\n b >= 0x20 &&\n b <= 0x2f;\n const cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped'\n );\n return true;\n }\n\n const chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;\n const channel = this.channels[chNr] as Cea608Channel;\n\n if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2a) {\n channel.ccTR();\n } else if (b === 0x2b) {\n channel.ccRTD();\n } else if (b === 0x2c) {\n channel.ccEDM();\n } else if (b === 0x2d) {\n channel.ccCR();\n } else if (b === 0x2e) {\n channel.ccENM();\n } else if (b === 0x2f) {\n channel.ccEOC();\n }\n } else {\n // a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n * @returns {Boolean}\n */\n parseMidrow(a: number, b: number) {\n let chNr: number = 0;\n\n if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currentChannel) {\n this.logger.log(\n VerboseLevel.ERROR,\n 'Mismatch channel in midrow parsing'\n );\n return false;\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.ccMIDROW(b);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'MIDROW (' + numArrayToHexArray([a, b]) + ')'\n );\n return true;\n }\n return false;\n }\n\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC(a: number, b: number): boolean {\n let row: number;\n const cmdHistory = this.cmdHistory;\n\n const case1 =\n ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1f)) &&\n b >= 0x40 &&\n b <= 0x7f;\n const case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;\n if (!(case1 || case2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n return true; // Repeated commands are dropped (once)\n }\n\n const chNr: Channels = a <= 0x17 ? 1 : 2;\n\n if (b >= 0x40 && b <= 0x5f) {\n row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];\n } else {\n // 0x60 <= b <= 0x7F\n row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.setPAC(this.interpretPAC(row, b));\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns {Object} pacData with style parameters.\n */\n interpretPAC(row: number, byte: number): PACData {\n let pacIndex;\n const pacData: PACData = {\n color: null,\n italics: false,\n indent: null,\n underline: false,\n row: row,\n };\n\n if (byte > 0x5f) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n 'white',\n ][Math.floor(pacIndex / 2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars(a: number, b: number): number[] | null {\n let channelNr: Channels;\n let charCodes: number[] | null = null;\n let charCode1: number | null = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let oneCode;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n\n this.logger.log(\n VerboseLevel.INFO,\n \"Special char '\" + getCharForByte(oneCode) + \"' in channel \" + channelNr\n );\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = b === 0 ? [a] : [a, b];\n }\n if (charCodes) {\n const hexCodes = numArrayToHexArray(charCodes);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Char codes = ' + hexCodes.join(',')\n );\n setLastCmd(a, b, this.cmdHistory);\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns {Boolean} Tells if background attributes are found\n */\n parseBackgroundAttributes(a: number, b: number): boolean {\n const case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;\n const case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;\n if (!(case1 || case2)) {\n return false;\n }\n let index: number;\n const bkgData: Partial<PenStyles> = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b - 0x20) / 2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n const chNr: Channels = a <= 0x17 ? 1 : 2;\n const channel: Cea608Channel = this.channels[chNr] as Cea608Channel;\n channel.setBkgData(bkgData);\n setLastCmd(a, b, this.cmdHistory);\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset() {\n for (let i = 0; i < Object.keys(this.channels).length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.reset();\n }\n }\n this.cmdHistory = createCmdHistory();\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime(t: number) {\n for (let i = 0; i < this.channels.length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.cueSplitAtTime(t);\n }\n }\n }\n}\n\nfunction setLastCmd(\n a: number | null,\n b: number | null,\n cmdHistory: CmdHistory\n) {\n cmdHistory.a = a;\n cmdHistory.b = b;\n}\n\nfunction hasCmdRepeated(a: number, b: number, cmdHistory: CmdHistory) {\n return cmdHistory.a === a && cmdHistory.b === b;\n}\n\nfunction createCmdHistory(): CmdHistory {\n return {\n a: null,\n b: null,\n };\n}\n\nexport default Cea608Parser;\n","// from http://mp4ra.org/codecs.html\nconst sampleEntryCodesISO = {\n audio: {\n a3ds: true,\n 'ac-3': true,\n 'ac-4': true,\n alac: true,\n alaw: true,\n dra1: true,\n 'dts+': true,\n 'dts-': true,\n dtsc: true,\n dtse: true,\n dtsh: true,\n 'ec-3': true,\n enca: true,\n g719: true,\n g726: true,\n m4ae: true,\n mha1: true,\n mha2: true,\n mhm1: true,\n mhm2: true,\n mlpa: true,\n mp4a: true,\n 'raw ': true,\n Opus: true,\n opus: true, // browsers expect this to be lowercase despite MP4RA says 'Opus'\n samr: true,\n sawb: true,\n sawp: true,\n sevc: true,\n sqcp: true,\n ssmv: true,\n twos: true,\n ulaw: true,\n },\n video: {\n avc1: true,\n avc2: true,\n avc3: true,\n avc4: true,\n avcp: true,\n av01: true,\n drac: true,\n dva1: true,\n dvav: true,\n dvh1: true,\n dvhe: true,\n encv: true,\n hev1: true,\n hvc1: true,\n mjp2: true,\n mp4v: true,\n mvc1: true,\n mvc2: true,\n mvc3: true,\n mvc4: true,\n resv: true,\n rv60: true,\n s263: true,\n svc1: true,\n svc2: true,\n 'vc-1': true,\n vp08: true,\n vp09: true,\n },\n text: {\n stpp: true,\n wvtt: true,\n },\n};\n\nexport type CodecType = 'audio' | 'video';\n\nexport function isCodecType(codec: string, type: CodecType): boolean {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nexport function isCodecSupportedInMp4(codec: string, type: CodecType): boolean {\n return MediaSource.isTypeSupported(\n `${type || 'video'}/mp4;codecs=\"${codec}\"`\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 || !track.cues || !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 { logger } from './logger';\nimport { adjustSliding } from '../controller/level-helper';\n\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { Level } from '../types/level';\nimport type { RequiredProperties } from '../types/general';\n\nexport function findFirstFragWithCC(fragments: Fragment[], cc: number) {\n let firstFrag: Fragment | null = null;\n\n for (let i = 0, len = fragments.length; i < len; i++) {\n const currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nexport function shouldAlignOnDiscontinuities(\n lastFrag: Fragment | null,\n lastLevel: Level,\n details: LevelDetails\n): lastLevel is RequiredProperties<Level, 'details'> {\n if (lastLevel.details) {\n if (\n details.endCC > details.startCC ||\n (lastFrag && lastFrag.cc < details.startCC)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag(\n prevDetails: LevelDetails,\n curDetails: LevelDetails,\n referenceIndex: number = 0\n) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nfunction adjustFragmentStart(frag: Fragment, sliding: number) {\n if (frag) {\n const start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n}\n\nexport function adjustSlidingStart(sliding: number, details: LevelDetails) {\n // Update segments\n const fragments = details.fragments;\n for (let i = 0, len = fragments.length; i < len; i++) {\n adjustFragmentStart(fragments[i], sliding);\n }\n // Update LL-HLS parts at the end of the playlist\n if (details.fragmentHint) {\n adjustFragmentStart(details.fragmentHint, sliding);\n }\n details.alignedSliding = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastFrag\n * @param lastLevel\n * @param details\n */\nexport function alignStream(\n lastFrag: Fragment | null,\n lastLevel: Level | null,\n details: LevelDetails\n) {\n if (!lastLevel) {\n return;\n }\n alignDiscontinuities(lastFrag, details, lastLevel);\n if (!details.alignedSliding && lastLevel.details) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignPDT(details, lastLevel.details);\n }\n if (\n !details.alignedSliding &&\n lastLevel.details &&\n !details.skippedSegments\n ) {\n // Try to align on sn so that we pick a better start fragment.\n // Do not perform this on playlists with delta updates as this is only to align levels on switch\n // and adjustSliding only adjusts fragments after skippedSegments.\n adjustSliding(lastLevel.details, details);\n }\n}\n\n/**\n * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n * discontinuity sequence.\n * @param lastFrag - The last Fragment which shares the same discontinuity sequence\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nfunction alignDiscontinuities(\n lastFrag: Fragment | null,\n details: LevelDetails,\n lastLevel: Level\n) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(\n lastLevel.details,\n details\n );\n if (referenceFrag && Number.isFinite(referenceFrag.start)) {\n logger.log(\n `Adjusting PTS using last level due to CC increase within current level ${details.url}`\n );\n adjustSlidingStart(referenceFrag.start, details);\n }\n }\n}\n\n/**\n * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.\n * @param details - The details of the new level\n * @param lastDetails - The details of the last loaded level\n */\nexport function alignPDT(details: LevelDetails, lastDetails: LevelDetails) {\n // This check protects the unsafe \"!\" usage below for null program date time access.\n if (\n !lastDetails.fragments.length ||\n !details.hasProgramDateTime ||\n !lastDetails.hasProgramDateTime\n ) {\n return;\n }\n // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n // then we can deduce that playlist B sliding is 1000+8 = 1008s\n const lastPDT = lastDetails.fragments[0].programDateTime!; // hasProgramDateTime check above makes this safe.\n const newPDT = details.fragments[0].programDateTime!;\n // date diff is in ms. frag.start is in seconds\n const sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;\n if (sliding && Number.isFinite(sliding)) {\n logger.log(\n `Adjusting PTS using programDateTime delta ${\n newPDT - lastPDT\n }ms, sliding:${sliding.toFixed(3)} ${details.url} `\n );\n adjustSlidingStart(sliding, details);\n }\n}\n\n/**\n * Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts\n * the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,\n * this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,\n * and uses the \"wallclock\"/PDT timeline as a cross-reference to `details`, adjusting the presentation\n * times/timelines of `details` accordingly.\n * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,\n * the primary purpose of this function is to ensure the \"local timelines\" of audio/subtitle tracks\n * are aligned to the main/video timeline, using PDT as the cross-reference/\"anchor\" that should\n * be consistent across playlists, per the HLS spec.\n * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).\n * @param refDetails - The details of the reference rendition with start and PDT times for alignment.\n */\nexport function alignMediaPlaylistByPDT(\n details: LevelDetails,\n refDetails: LevelDetails\n) {\n if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {\n return;\n }\n\n const fragments = details.fragments;\n const refFragments = refDetails.fragments;\n if (!fragments.length || !refFragments.length) {\n return;\n }\n\n // Calculate a delta to apply to all fragments according to the delta in PDT times and start times\n // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.\n // If a fragment of the same discontinuity was not found use the middle fragment of both.\n const middleFrag = Math.round(refFragments.length / 2) - 1;\n const refFrag = refFragments[middleFrag];\n const frag =\n findFirstFragWithCC(fragments, refFrag.cc) ||\n fragments[Math.round(fragments.length / 2) - 1];\n\n const refPDT = refFrag.programDateTime;\n const targetPDT = frag.programDateTime;\n if (refPDT === null || targetPDT === null) {\n return;\n }\n\n const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);\n adjustSlidingStart(delta, details);\n}\n","/*\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\n constructor(slow: number, fast: number, defaultEstimate: number) {\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 }\n\n update(slow: number, fast: number) {\n const { slow_, fast_ } = this;\n if (this.slow_.halfLife !== slow) {\n this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());\n }\n if (this.fast_.halfLife !== fast) {\n this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.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 canEstimate(): boolean {\n const fast = this.fast_;\n return fast && 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 destroy() {}\n}\nexport default EwmaBandWidthEstimator;\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","import {\n LoaderCallbacks,\n LoaderContext,\n Loader,\n LoaderStats,\n LoaderConfiguration,\n LoaderOnProgress,\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\nclass FetchLoader implements Loader<LoaderContext> {\n private fetchSetup: Function;\n private requestTimeout?: number;\n private request!: Request;\n private response!: Response;\n private controller: AbortController;\n public context!: LoaderContext;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public stats: LoaderStats;\n private loader: Response | null = null;\n\n constructor(config /* HlsConfig */) {\n this.fetchSetup = config.fetchSetup || getRequest;\n this.controller = new self.AbortController();\n this.stats = new LoadStats();\n }\n\n destroy(): void {\n this.loader = this.callbacks = null;\n this.abortInternal();\n }\n\n abortInternal(): void {\n const response = this.response;\n if (!response || !response.ok) {\n this.stats.aborted = true;\n this.controller.abort();\n }\n }\n\n abort(): void {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(this.stats, this.context, this.response);\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>\n ): void {\n const stats = this.stats;\n if (stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n stats.loading.start = self.performance.now();\n\n const initParams = getRequestParameters(context, this.controller.signal);\n const onProgress: LoaderOnProgress<LoaderContext> | undefined =\n callbacks.onProgress;\n const isArrayBuffer = context.responseType === 'arraybuffer';\n const LENGTH = isArrayBuffer ? 'byteLength' : 'length';\n\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 this.requestTimeout = self.setTimeout(() => {\n this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n }, config.timeout);\n\n self\n .fetch(this.request)\n .then((response: Response): Promise<string | ArrayBuffer> => {\n this.response = this.loader = response;\n\n 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 = Math.max(\n self.performance.now(),\n stats.loading.start\n );\n stats.total = parseInt(response.headers.get('Content-Length') || '0');\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 return response.text();\n })\n .then((responseData: string | ArrayBuffer) => {\n const { response } = this;\n self.clearTimeout(this.requestTimeout);\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first\n );\n const total = responseData[LENGTH];\n if (total) {\n stats.loaded = stats.total = total;\n }\n\n const loaderResponse = {\n url: response.url,\n data: responseData,\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 );\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 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 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 { findBox } from './mp4-tools';\nimport { parseTimeStamp } from './vttparser';\nimport VTTCue from './vttcue';\nimport { utf8ArrayToStr } from '../demux/id3';\nimport { toTimescaleFromScale } 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: number,\n timescale: number,\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, 1, 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","export interface ILogFunction {\n (message?: any, ...optionalParams: any[]): void;\n}\n\nexport interface ILogger {\n trace: ILogFunction;\n debug: ILogFunction;\n log: ILogFunction;\n warn: ILogFunction;\n info: ILogFunction;\n error: ILogFunction;\n}\n\nconst noop: ILogFunction = function () {};\n\nconst fakeLogger: ILogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop,\n};\n\nlet exportedLogger: ILogger = fakeLogger;\n\n// let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction consolePrintFn(type: string): ILogFunction {\n const func: ILogFunction = self.console[type];\n if (func) {\n return func.bind(self.console, `[${type}] >`);\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(\n debugConfig: boolean | ILogger,\n ...functions: string[]\n): void {\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type]\n ? debugConfig[type].bind(debugConfig)\n : consolePrintFn(type);\n });\n}\n\nexport function enableLogs(debugConfig: boolean | ILogger, id: string): void {\n // check that console is available\n if (\n (self.console && debugConfig === true) ||\n typeof debugConfig === 'object'\n ) {\n exportLoggerFunctions(\n debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error'\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log(`Debug logs enabled for \"${id}\"`);\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n } else {\n exportedLogger = fakeLogger;\n }\n}\n\nexport const logger: ILogger = exportedLogger;\n","/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nexport enum KeySystems {\n WIDEVINE = 'com.widevine.alpha',\n PLAYREADY = 'com.microsoft.playready',\n}\n\nexport type MediaKeyFunc = (\n keySystem: KeySystems,\n supportedConfigurations: MediaKeySystemConfiguration[]\n) => Promise<MediaKeySystemAccess>;\nconst requestMediaKeySystemAccess = (function (): MediaKeyFunc | null {\n if (\n typeof self !== 'undefined' &&\n self.navigator &&\n self.navigator.requestMediaKeySystemAccess\n ) {\n return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);\n } else {\n return null;\n }\n})();\n\nexport { requestMediaKeySystemAccess };\n","/**\n * MediaSource helper\n */\n\nexport function getMediaSource(): typeof MediaSource | undefined {\n return self.MediaSource || ((self as any).WebKitMediaSource as MediaSource);\n}\n","import { sliceUint8 } from './typed-array';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport { PassthroughTrack, UserdataSample } from '../types/demuxer';\nimport { utf8ArrayToStr } from '../demux/id3';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\nconst push = [].push;\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nexport const RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4,\n};\n\nexport function bin2str(data: Uint8Array): string {\n return String.fromCharCode.apply(null, data);\n}\n\nexport function readUint16(buffer: Uint8Array, offset: number): number {\n const val = (buffer[offset] << 8) | buffer[offset + 1];\n return val < 0 ? 65536 + val : val;\n}\n\nexport function readUint32(buffer: Uint8Array, offset: number): number {\n const val = readSint32(buffer, offset);\n return val < 0 ? 4294967296 + val : val;\n}\n\nexport function readSint32(buffer: Uint8Array, offset: number): number {\n return (\n (buffer[offset] << 24) |\n (buffer[offset + 1] << 16) |\n (buffer[offset + 2] << 8) |\n buffer[offset + 3]\n );\n}\n\nexport function writeUint32(buffer: Uint8Array, offset: number, value: number) {\n buffer[offset] = value >> 24;\n buffer[offset + 1] = (value >> 16) & 0xff;\n buffer[offset + 2] = (value >> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n}\n\n// Find the data for a box specified by its path\nexport function findBox(data: Uint8Array, path: string[]): Uint8Array[] {\n const results = [] as Uint8Array[];\n if (!path.length) {\n // short-circuit the search for empty paths\n return results;\n }\n const end = data.byteLength;\n\n for (let i = 0; i < end; ) {\n const size = readUint32(data, i);\n const type = bin2str(data.subarray(i + 4, i + 8));\n const endbox = size > 1 ? i + size : end;\n\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push(data.subarray(i + 8, endbox));\n } else {\n // recursively search for the next box along the path\n const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));\n if (subresults.length) {\n push.apply(results, subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n}\n\ntype SidxInfo = {\n earliestPresentationTime: number;\n timescale: number;\n version: number;\n referencesCount: number;\n references: any[];\n};\n\nexport function parseSegmentIndex(sidx: Uint8Array): SidxInfo | null {\n const references: any[] = [];\n\n const version = sidx[0];\n\n // set initial offset, we skip the reference ID (not needed)\n let index = 8;\n\n const timescale = readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n const earliestPresentationTime = 0;\n const firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.length + firstOffset;\n\n const referencesCount = readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7fffffff;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n // eslint-disable-next-line no-console\n console.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 {Uint8Array} the bytes of the init segment\n * @return {InitData} a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n\nexport interface InitDataTrack {\n timescale: number;\n id: number;\n codec: string;\n}\n\ntype HdlrType = ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO;\n\nexport interface InitData extends Array<any> {\n [index: number]:\n | {\n timescale: number;\n type: HdlrType;\n default?: {\n duration: number;\n flags: number;\n };\n }\n | undefined;\n audio?: InitDataTrack;\n video?: InitDataTrack;\n caption?: InitDataTrack;\n}\n\nexport function parseInitSegment(initSegment: Uint8Array): InitData {\n const result: InitData = [];\n const traks = findBox(initSegment, ['moov', 'trak']);\n for (let i = 0; i < traks.length; i++) {\n const trak = traks[i];\n const tkhd = findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd[0];\n let index = version === 0 ? 12 : 20;\n const trackId = readUint32(tkhd, index);\n const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd[0];\n index = version === 0 ? 12 : 20;\n const timescale = readUint32(mdhd, index);\n const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = bin2str(hdlr.subarray(8, 12));\n const type: HdlrType | undefined = {\n soun: ElementaryStreamTypes.AUDIO as const,\n vide: ElementaryStreamTypes.VIDEO as const,\n }[hdlrType];\n if (type) {\n // Parse codec details\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n let codec;\n if (stsd) {\n codec = bin2str(stsd.subarray(12, 16));\n // TODO: Parse codec details to be able to build MIME type.\n // stsd.start += 8;\n // const codecBox = findBox(stsd, [codec])[0];\n // if (codecBox) {\n // TODO: Codec parsing support for avc1, mp4a, hevc, av01...\n // }\n }\n result[trackId] = { timescale, type };\n result[type] = { timescale, id: trackId, codec };\n }\n }\n }\n }\n }\n\n const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);\n trex.forEach((trex) => {\n const trackId = readUint32(trex, 4);\n const track = result[trackId];\n if (track) {\n track.default = {\n duration: readUint32(trex, 12),\n flags: readUint32(trex, 20),\n };\n }\n });\n\n return result;\n}\n\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 {InitData} a hash of track type to timescale values\n * @param fmp4 {Uint8Array} the bytes of the mp4 fragment\n * @return {number} the earliest base media decode start time for the\n * fragment, in seconds\n */\nexport function getStartDTS(initData: InitData, fmp4: Uint8Array): number {\n // we need info from two children of each track fragment box\n return (\n findBox(fmp4, ['moof', 'traf']).reduce((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 baseTime *= Math.pow(2, 32);\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 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 isFinite(start) &&\n (result === null || start < result)\n ) {\n return start;\n }\n return result;\n }, null) || 0\n );\n}\n\n/*\n For Reference:\n aligned(8) class TrackFragmentHeaderBox\n extends FullBox(‘tfhd’, 0, tf_flags){\n unsigned int(32) track_ID;\n // all the following are optional fields\n unsigned int(64) base_data_offset;\n unsigned int(32) sample_description_index;\n unsigned int(32) default_sample_duration;\n unsigned int(32) default_sample_size;\n unsigned int(32) default_sample_flags\n }\n */\nexport function getDuration(data: Uint8Array, initData: InitData) {\n let rawDuration = 0;\n let videoDuration = 0;\n let audioDuration = 0;\n const trafs = findBox(data, ['moof', 'traf']);\n for (let i = 0; i < trafs.length; i++) {\n const traf = trafs[i];\n // There is only one tfhd & trun per traf\n // This is true for CMAF style content, and we should perhaps check the ftyp\n // and only look for a single trun then, but for ISOBMFF we should check\n // for multiple track runs.\n const tfhd = findBox(traf, ['tfhd'])[0];\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n continue;\n }\n const trackDefault = track.default;\n const tfhdFlags = readUint32(tfhd, 0) | trackDefault?.flags!;\n let sampleDuration: number | undefined = trackDefault?.duration;\n if (tfhdFlags & 0x000008) {\n // 0x000008 indicates the presence of the default_sample_duration field\n if (tfhdFlags & 0x000002) {\n // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration\n // If present, the default_sample_duration exists at byte offset 12\n sampleDuration = readUint32(tfhd, 12);\n } else {\n // Otherwise, the duration is at byte offset 8\n sampleDuration = readUint32(tfhd, 8);\n }\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n const truns = findBox(traf, ['trun']);\n for (let j = 0; j < truns.length; j++) {\n rawDuration = computeRawDurationFromSamples(truns[j]);\n if (!rawDuration && sampleDuration) {\n const sampleCount = readUint32(truns[j], 4);\n rawDuration = sampleDuration * sampleCount;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n videoDuration += rawDuration / timescale;\n } else if (track.type === ElementaryStreamTypes.AUDIO) {\n audioDuration += rawDuration / timescale;\n }\n }\n }\n if (videoDuration === 0 && audioDuration === 0) {\n // If duration samples are not available in the traf use sidx subsegment_duration\n let sidxDuration = 0;\n const sidxs = findBox(data, ['sidx']);\n for (let i = 0; i < sidxs.length; i++) {\n const sidx = parseSegmentIndex(sidxs[i]);\n if (sidx?.references) {\n sidxDuration += sidx.references.reduce(\n (dur, ref) => dur + ref.info.duration || 0,\n 0\n );\n }\n }\n\n return sidxDuration;\n }\n if (videoDuration) {\n return videoDuration;\n }\n return audioDuration;\n}\n\n/*\n For Reference:\n aligned(8) class TrackRunBox\n extends FullBox(‘trun’, version, tr_flags) {\n unsigned int(32) sample_count;\n // the following are optional fields\n signed int(32) data_offset;\n unsigned int(32) first_sample_flags;\n // all fields in the following array are optional\n {\n unsigned int(32) sample_duration;\n unsigned int(32) sample_size;\n unsigned int(32) sample_flags\n if (version == 0)\n { unsigned int(32)\n else\n { signed int(32)\n }[ sample_count ]\n }\n */\nexport function computeRawDurationFromSamples(trun): number {\n const flags = readUint32(trun, 0);\n // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.\n // Each field is an int32, which is 4 bytes\n let offset = 8;\n // data-offset-present flag\n if (flags & 0x000001) {\n offset += 4;\n }\n // first-sample-flags-present flag\n if (flags & 0x000004) {\n offset += 4;\n }\n\n let duration = 0;\n const sampleCount = readUint32(trun, 4);\n for (let i = 0; i < sampleCount; i++) {\n // sample-duration-present flag\n if (flags & 0x000100) {\n const sampleDuration = readUint32(trun, offset);\n duration += sampleDuration;\n offset += 4;\n }\n // sample-size-present flag\n if (flags & 0x000200) {\n offset += 4;\n }\n // sample-flags-present flag\n if (flags & 0x000400) {\n offset += 4;\n }\n // sample-composition-time-offsets-present flag\n if (flags & 0x000800) {\n offset += 4;\n }\n }\n return duration;\n}\n\nexport function offsetStartDTS(\n initData: InitData,\n fmp4: Uint8Array,\n timeOffset: number\n) {\n findBox(fmp4, ['moof', 'traf']).forEach((traf) => {\n findBox(traf, ['tfhd']).forEach((tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n return;\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n // get the base media decode time from the tfdt\n findBox(traf, ['tfdt']).forEach((tfdt) => {\n const version = tfdt[0];\n let baseMediaDecodeTime = readUint32(tfdt, 4);\n\n if (version === 0) {\n baseMediaDecodeTime -= timeOffset * timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n writeUint32(tfdt, 4, baseMediaDecodeTime);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += readUint32(tfdt, 8);\n baseMediaDecodeTime -= timeOffset * timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n writeUint32(tfdt, 4, upper);\n writeUint32(tfdt, 8, lower);\n }\n });\n });\n });\n}\n\n// TODO: Check if the last moof+mdat pair is part of the valid range\nexport function segmentValidRange(data: Uint8Array): SegmentedRange {\n const segmentedRange: SegmentedRange = {\n valid: null,\n remainder: null,\n };\n\n const moofs = findBox(data, ['moof']);\n if (!moofs) {\n return segmentedRange;\n } else if (moofs.length < 2) {\n segmentedRange.remainder = data;\n return segmentedRange;\n }\n const last = moofs[moofs.length - 1];\n // Offset by 8 bytes; findBox offsets the start by as much\n segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);\n segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);\n return segmentedRange;\n}\n\nexport interface SegmentedRange {\n valid: Uint8Array | null;\n remainder: Uint8Array | null;\n}\n\nexport function appendUint8Array(\n data1: Uint8Array,\n data2: Uint8Array\n): Uint8Array {\n const temp = new Uint8Array(data1.length + data2.length);\n temp.set(data1);\n temp.set(data2, data1.length);\n\n return temp;\n}\n\nexport interface IEmsgParsingData {\n schemeIdUri: string;\n value: string;\n timeScale: number;\n presentationTimeDelta?: number;\n presentationTime?: number;\n eventDuration: number;\n id: number;\n payload: Uint8Array;\n}\n\nexport function parseSamples(\n timeOffset: number,\n track: PassthroughTrack\n): UserdataSample[] {\n const seiSamples = [] as UserdataSample[];\n const videoData = track.samples;\n const timescale = track.timescale;\n const trackId = track.id;\n let isHEVCFlavor = false;\n\n const moofs = findBox(videoData, ['moof']);\n moofs.map((moof) => {\n const moofOffset = moof.byteOffset - 8;\n const trafs = findBox(moof, ['traf']);\n trafs.map((traf) => {\n // get the base media decode time from the tfdt\n const baseTime = findBox(traf, ['tfdt']).map((tfdt) => {\n const version = tfdt[0];\n let result = readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n result += readUint32(tfdt, 8);\n }\n return result / timescale;\n })[0];\n\n if (baseTime !== undefined) {\n timeOffset = baseTime;\n }\n\n return findBox(traf, ['tfhd']).map((tfhd) => {\n const id = readUint32(tfhd, 4);\n const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;\n const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;\n const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;\n const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;\n let defaultSampleDuration = 0;\n const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;\n let defaultSampleSize = 0;\n const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;\n let tfhdOffset = 8;\n\n if (id === trackId) {\n if (baseDataOffsetPresent) {\n tfhdOffset += 8;\n }\n if (sampleDescriptionIndexPresent) {\n tfhdOffset += 4;\n }\n if (defaultSampleDurationPresent) {\n defaultSampleDuration = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleSizePresent) {\n defaultSampleSize = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleFlagsPresent) {\n tfhdOffset += 4;\n }\n if (track.type === 'video') {\n isHEVCFlavor = isHEVC(track.codec);\n }\n\n findBox(traf, ['trun']).map((trun) => {\n const version = trun[0];\n const flags = readUint32(trun, 0) & 0xffffff;\n const dataOffsetPresent = (flags & 0x000001) !== 0;\n let dataOffset = 0;\n const firstSampleFlagsPresent = (flags & 0x000004) !== 0;\n const sampleDurationPresent = (flags & 0x000100) !== 0;\n let sampleDuration = 0;\n const sampleSizePresent = (flags & 0x000200) !== 0;\n let sampleSize = 0;\n const sampleFlagsPresent = (flags & 0x000400) !== 0;\n const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;\n let compositionOffset = 0;\n const sampleCount = readUint32(trun, 4);\n let trunOffset = 8; // past version, flags, and sample count\n\n if (dataOffsetPresent) {\n dataOffset = readUint32(trun, trunOffset);\n trunOffset += 4;\n }\n if (firstSampleFlagsPresent) {\n trunOffset += 4;\n }\n\n let sampleOffset = dataOffset + moofOffset;\n\n for (let ix = 0; ix < sampleCount; ix++) {\n if (sampleDurationPresent) {\n sampleDuration = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleDuration = defaultSampleDuration;\n }\n if (sampleSizePresent) {\n sampleSize = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleSize = defaultSampleSize;\n }\n if (sampleFlagsPresent) {\n trunOffset += 4;\n }\n if (sampleCompositionOffsetsPresent) {\n if (version === 0) {\n compositionOffset = readUint32(trun, trunOffset);\n } else {\n compositionOffset = readSint32(trun, trunOffset);\n }\n trunOffset += 4;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n let naluTotalSize = 0;\n while (naluTotalSize < sampleSize) {\n const naluSize = readUint32(videoData, sampleOffset);\n sampleOffset += 4;\n if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {\n const data = videoData.subarray(\n sampleOffset,\n sampleOffset + naluSize\n );\n parseSEIMessageFromNALu(\n data,\n isHEVCFlavor ? 2 : 1,\n timeOffset + compositionOffset / timescale,\n seiSamples\n );\n }\n sampleOffset += naluSize;\n naluTotalSize += naluSize + 4;\n }\n }\n\n timeOffset += sampleDuration / timescale;\n }\n });\n }\n });\n });\n });\n return seiSamples;\n}\n\nfunction isHEVC(codec: string) {\n if (!codec) {\n return false;\n }\n const delimit = codec.indexOf('.');\n const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);\n return (\n baseCodec === 'hvc1' ||\n baseCodec === 'hev1' ||\n // Dolby Vision\n baseCodec === 'dvh1' ||\n baseCodec === 'dvhe'\n );\n}\n\nfunction isSEIMessage(isHEVCFlavor: boolean, naluHeader: number) {\n if (isHEVCFlavor) {\n const naluType = (naluHeader >> 1) & 0x3f;\n return naluType === 39 || naluType === 40;\n } else {\n const naluType = naluHeader & 0x1f;\n return naluType === 6;\n }\n}\n\nexport function parseSEIMessageFromNALu(\n unescapedData: Uint8Array,\n headerSize: number,\n pts: number,\n samples: UserdataSample[]\n) {\n const data = discardEPB(unescapedData);\n let seiPtr = 0;\n // skip nal header\n seiPtr += headerSize;\n let payloadType = 0;\n let payloadSize = 0;\n let endOfCaptions = false;\n let b = 0;\n\n while (seiPtr < data.length) {\n payloadType = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadType += b;\n } while (b === 0xff);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadSize += b;\n } while (b === 0xff);\n\n const leftOver = data.length - seiPtr;\n\n if (!endOfCaptions && payloadType === 4 && seiPtr < data.length) {\n endOfCaptions = true;\n\n const countryCode = data[seiPtr++];\n if (countryCode === 181) {\n const providerCode = readUint16(data, seiPtr);\n seiPtr += 2;\n\n if (providerCode === 49) {\n const userStructure = readUint32(data, seiPtr);\n seiPtr += 4;\n\n if (userStructure === 0x47413934) {\n const userDataType = data[seiPtr++];\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n const firstByte = data[seiPtr++];\n const totalCCs = 0x1f & firstByte;\n const enabled = 0x40 & firstByte;\n const totalBytes = enabled ? 2 + totalCCs * 3 : 0;\n const byteArray = new Uint8Array(totalBytes);\n if (enabled) {\n byteArray[0] = firstByte;\n for (let i = 1; i < totalBytes; i++) {\n byteArray[i] = data[seiPtr++];\n }\n }\n\n samples.push({\n type: userDataType,\n payloadType,\n pts,\n bytes: byteArray,\n });\n }\n }\n }\n }\n } else if (payloadType === 5 && payloadSize < leftOver) {\n endOfCaptions = true;\n\n if (payloadSize > 16) {\n const uuidStrArray: Array<string> = [];\n for (let i = 0; i < 16; i++) {\n const b = data[seiPtr++].toString(16);\n uuidStrArray.push(b.length == 1 ? '0' + b : b);\n\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataBytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n userDataBytes[i] = data[seiPtr++];\n }\n\n samples.push({\n payloadType,\n pts,\n uuid: uuidStrArray.join(''),\n userData: utf8ArrayToStr(userDataBytes),\n userDataBytes,\n });\n }\n } else if (payloadSize < leftOver) {\n seiPtr += payloadSize;\n } else if (payloadSize > leftOver) {\n break;\n }\n }\n}\n\n/**\n * remove Emulation Prevention bytes from a RBSP\n */\nexport function discardEPB(data: Uint8Array): Uint8Array {\n const length = data.byteLength;\n const EPBPositions = [] as Array<number>;\n let i = 1;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n const newLength = length - EPBPositions.length;\n const newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n}\n\nexport function parseEmsg(data: Uint8Array): IEmsgParsingData {\n const version = data[0];\n let schemeIdUri: string = '';\n let value: string = '';\n let timeScale: number = 0;\n let presentationTimeDelta: number = 0;\n let presentationTime: number = 0;\n let eventDuration: number = 0;\n let id: number = 0;\n let offset: number = 0;\n\n if (version === 0) {\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n timeScale = readUint32(data, 12);\n presentationTimeDelta = readUint32(data, 16);\n eventDuration = readUint32(data, 20);\n id = readUint32(data, 24);\n offset = 28;\n } else if (version === 1) {\n offset += 4;\n timeScale = readUint32(data, offset);\n offset += 4;\n const leftPresentationTime = readUint32(data, offset);\n offset += 4;\n const rightPresentationTime = readUint32(data, offset);\n offset += 4;\n presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;\n if (!Number.isSafeInteger(presentationTime)) {\n presentationTime = Number.MAX_SAFE_INTEGER;\n // eslint-disable-next-line no-console\n console.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","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","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 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 }\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","/**\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","const MPEG_TS_CLOCK_FREQ_HZ = 90000;\n\nexport function toTimescaleFromBase(\n value,\n destScale: number,\n srcBase: number = 1,\n round: boolean = false\n): number {\n const result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\n\nexport function toTimescaleFromScale(\n value,\n destScale: number,\n srcScale: number = 1,\n round: boolean = false\n): number {\n return toTimescaleFromBase(value, destScale, 1 / srcScale, round);\n}\n\nexport function toMsFromMpegTsClock(\n value: number,\n round: boolean = false\n): number {\n return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\n\nexport function toMpegTsClockFromTimescale(\n value: number,\n srcScale: number = 1\n): number {\n return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\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","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ndeclare interface VTTCuePolyfill extends VTTCue {\n new (...args): VTTCuePolyfill;\n hasBeenReset: boolean;\n displayState: void;\n}\n\nexport default (function () {\n if (typeof self !== 'undefined' && self.VTTCue) {\n return self.VTTCue;\n }\n\n const AllowedDirections = ['', 'lr', 'rl'] as const;\n type Direction = typeof AllowedDirections[number];\n\n const AllowedAlignments = [\n 'start',\n 'middle',\n 'end',\n 'left',\n 'right',\n ] as const;\n type Alignment = typeof AllowedAlignments[number];\n\n function isAllowedValue<T, A>(allowed: T, value: string): A | false {\n if (typeof value !== 'string') {\n return false;\n }\n // necessary for assuring the generic conforms to the Array interface\n if (!Array.isArray(allowed)) {\n return false;\n }\n // reset the type so that the next narrowing works well\n const lcValue = value.toLowerCase() as any;\n // use the allow list to narrow the type to a specific subset of strings\n if (~allowed.indexOf(lcValue)) {\n return lcValue;\n }\n\n return false;\n }\n\n function findDirectionSetting(value: string) {\n return isAllowedValue<typeof AllowedDirections, Direction>(\n AllowedDirections,\n value\n );\n }\n\n function findAlignSetting(value: string) {\n return isAllowedValue<typeof AllowedAlignments, Alignment>(\n AllowedAlignments,\n value\n );\n }\n\n function extend(obj: Record<string, any>, ...rest: Record<string, any>[]) {\n let i = 1;\n for (; i < arguments.length; i++) {\n const cobj = arguments[i];\n for (const p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue(startTime: number, endTime: number, text: string) {\n const cue = this as VTTCuePolyfill;\n const baseObj = { enumerable: true };\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical: Direction = '';\n let _snapToLines = true;\n let _line: number | 'auto' = 'auto';\n let _lineAlign: Alignment = 'start';\n let _position = 50;\n let _positionAlign: Alignment = 'middle';\n let _size = 50;\n let _align: Alignment = 'middle';\n\n Object.defineProperty(\n cue,\n 'id',\n extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value: string) {\n _id = '' + value;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'pauseOnExit',\n extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value: boolean) {\n _pauseOnExit = !!value;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'startTime',\n extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value: number) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n\n _startTime = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'endTime',\n extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value: number) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n\n _endTime = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'text',\n extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value: string) {\n _text = '' + value;\n this.hasBeenReset = true;\n },\n })\n );\n\n // todo: implement VTTRegion polyfill?\n Object.defineProperty(\n cue,\n 'region',\n extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value: any) {\n _region = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'vertical',\n extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value: string) {\n const setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _vertical = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'snapToLines',\n extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value: boolean) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'line',\n extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value: number | 'auto') {\n if (typeof value !== 'number' && value !== 'auto') {\n throw new SyntaxError(\n 'An invalid number or illegal string was specified.'\n );\n }\n\n _line = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'lineAlign',\n extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _lineAlign = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'position',\n extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value: number) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n\n _position = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'positionAlign',\n extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _positionAlign = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'size',\n extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value: number) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n\n _size = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'align',\n extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _align = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = undefined;\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n const WebVTT = (self as any).WebVTT;\n return WebVTT.convertCueToDOMTree(self, this.text);\n };\n // this is a polyfill hack\n return VTTCue as any as VTTCuePolyfill;\n})();\n","/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js\n */\n\nimport VTTCue from './vttcue';\n\nclass StringDecoder {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n decode(data: string | any, options?: Object): string | never {\n if (!data) {\n return '';\n }\n\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n\n return decodeURIComponent(encodeURIComponent(data));\n }\n}\n\n// Try to parse input as a time stamp.\nexport function parseTimeStamp(input: string) {\n function computeSeconds(h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);\n }\n\n const m = input.match(/^(?:(\\d+):)?(\\d{2}):(\\d{2})(\\.\\d+)?/);\n if (!m) {\n return null;\n }\n\n if (parseFloat(m[2]) > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[2], m[3], 0, m[4]);\n }\n // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3], m[4]);\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nclass Settings {\n private readonly values: { [key: string]: any } = Object.create(null);\n\n // Only accept the first assignment to any key.\n set(k: string, v: any) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n }\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get(k: string, dflt?: any, defaultKey?: string): any {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n\n return this.has(k) ? this.values[k] : dflt;\n }\n // Check whether we have a value for a key.\n has(k: string): boolean {\n return k in this.values;\n }\n // Accept a setting if its one of the given alternatives.\n alt(k: string, v: any, a: any[]) {\n for (let n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n }\n // Accept a setting if its a valid (signed) integer.\n integer(k: string, v: any) {\n if (/^-?\\d+$/.test(v)) {\n // integer\n this.set(k, parseInt(v, 10));\n }\n }\n // Accept a setting if its a valid percentage.\n percent(k: string, v: any): boolean {\n if (/^([\\d]{1,3})(\\.[\\d]*)?%$/.test(v)) {\n const percent = parseFloat(v);\n if (percent >= 0 && percent <= 100) {\n this.set(k, percent);\n return true;\n }\n }\n return false;\n }\n}\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interpret each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions(\n input: string,\n callback: (k: string, v: any) => void,\n keyValueDelim: RegExp,\n groupDelim?: RegExp\n) {\n const groups = groupDelim ? input.split(groupDelim) : [input];\n for (const i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n const kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n const k = kv[0];\n const v = kv[1];\n callback(k, v);\n }\n}\n\nconst defaults = new VTTCue(0, 0, '');\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nconst center = (defaults.align as string) === 'middle' ? 'middle' : 'center';\n\nfunction parseCue(input: string, cue: VTTCue, regionList: Region[]) {\n // Remember the original input if we need to throw an error.\n const oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp(): number | never {\n const ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings(input: string, cue: VTTCue) {\n const settings = new Settings();\n\n parseOptions(\n input,\n function (k, v) {\n let vals;\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (let i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n vals = v.split(',');\n settings.integer(k, vals[0]);\n if (settings.percent(k, vals[0])) {\n settings.set('snapToLines', false);\n }\n\n settings.alt(k, vals[0], ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], [\n 'start',\n center,\n 'end',\n 'line-left',\n 'line-right',\n 'auto',\n ]);\n }\n\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n },\n /:/,\n /\\s/\n );\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n let line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n let position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position =\n cue.align === 'start' || cue.align === 'left'\n ? 0\n : cue.align === 'end' || cue.align === 'right'\n ? 100\n : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace() {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.slice(0, 3) !== '-->') {\n // (3) next characters must match '-->'\n throw new Error(\n \"Malformed time stamp (time stamps must be separated by '-->'): \" + oInput\n );\n }\n input = input.slice(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nexport function fixLineBreaks(input: string): string {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\ntype Region = {\n id: string;\n region: any;\n};\n\nexport class VTTParser {\n private state:\n | 'INITIAL'\n | 'HEADER'\n | 'ID'\n | 'CUE'\n | 'CUETEXT'\n | 'NOTE'\n | 'BADWEBVTT'\n | 'BADCUE' = 'INITIAL';\n private buffer: string = '';\n private decoder: StringDecoder = new StringDecoder();\n private regionList: Region[] = [];\n private cue: VTTCue | null = null;\n public oncue?: (cue: VTTCue) => void;\n public onparsingerror?: (error: Error) => void;\n public onflush?: () => void;\n\n parse(data?: string): VTTParser {\n const _this = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n _this.buffer += _this.decoder.decode(data, { stream: true });\n }\n\n function collectNextLine(): string {\n let buffer: string = _this.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (\n pos < buffer.length &&\n buffer[pos] !== '\\r' &&\n buffer[pos] !== '\\n'\n ) {\n ++pos;\n }\n\n const line: string = buffer.slice(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n\n _this.buffer = buffer.slice(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader(input) {\n parseOptions(\n input,\n function (k, v) {\n // switch (k) {\n // case 'region':\n // 3.3 WebVTT region metadata header syntax\n // console.log('parse region', v);\n // parseRegion(v);\n // break;\n // }\n },\n /:/\n );\n }\n\n // 5.1 WebVTT file parsing.\n try {\n let line: string = '';\n if (_this.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(_this.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n const m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!m || !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 { toMpegTsClockFromTimescale } 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: number,\n timescale: number,\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 initPTS90Hz = toMpegTsClockFromTimescale(initPTS, timescale);\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 - initPTS90Hz) / 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\n if (webVttMpegTsMapOffset) {\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 { logger } from '../utils/logger';\nimport type {\n LoaderCallbacks,\n LoaderContext,\n LoaderStats,\n Loader,\n LoaderConfiguration,\n} from '../types/loader';\nimport { LoadStats } from '../loader/load-stats';\n\nconst AGE_HEADER_LINE_REGEX = /^age:\\s*[\\d.]+\\s*$/m;\n\nclass XhrLoader implements Loader<LoaderContext> {\n private xhrSetup: Function | null;\n private requestTimeout?: number;\n private retryTimeout?: number;\n private retryDelay: number;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public context!: LoaderContext;\n\n private loader: XMLHttpRequest | null = null;\n public stats: LoaderStats;\n\n constructor(config /* HlsConfig */) {\n this.xhrSetup = config ? config.xhrSetup : null;\n this.stats = new LoadStats();\n this.retryDelay = 0;\n }\n\n destroy(): void {\n this.callbacks = null;\n this.abortInternal();\n this.loader = null;\n this.config = null;\n }\n\n abortInternal(): void {\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(): void {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(this.stats, this.context, this.loader);\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>\n ): void {\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.retryDelay = config.retryDelay;\n this.loadInternal();\n }\n\n loadInternal(): void {\n const { config, context } = this;\n if (!config) {\n return;\n }\n const xhr = (this.loader = new self.XMLHttpRequest());\n\n const stats = this.stats;\n stats.loading.first = 0;\n stats.loaded = 0;\n const xhrSetup = this.xhrSetup;\n\n try {\n if (xhrSetup) {\n try {\n xhrSetup(xhr, context.url);\n } catch (e) {\n // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n xhr.open('GET', context.url, true);\n xhrSetup(xhr, context.url);\n }\n }\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n\n const headers = this.context.headers;\n if (headers) {\n for (const header in headers) {\n xhr.setRequestHeader(header, headers[header]);\n }\n }\n } catch (e) {\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: e.message },\n context,\n xhr\n );\n return;\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 this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.timeout\n );\n xhr.send();\n }\n\n readystatechange(): void {\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 // clear xhr timeout and rearm it if readyState less than 4\n self.clearTimeout(this.requestTimeout);\n if (stats.loading.first === 0) {\n stats.loading.first = Math.max(\n self.performance.now(),\n stats.loading.start\n );\n }\n\n if (readyState === 4) {\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 isArrayBuffer = xhr.responseType === 'arraybuffer';\n if (\n status >= 200 &&\n status < 300 &&\n ((isArrayBuffer && xhr.response) || xhr.responseText !== null)\n ) {\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first\n );\n let data;\n let len: number;\n if (isArrayBuffer) {\n data = xhr.response;\n len = data.byteLength;\n } else {\n data = xhr.responseText;\n len = data.length;\n }\n stats.loaded = stats.total = len;\n\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 = {\n url: xhr.responseURL,\n data: data,\n };\n\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (\n stats.retry >= config.maxRetry ||\n (status >= 400 && status < 499)\n ) {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks!.onError(\n { code: status, text: xhr.statusText },\n context,\n xhr\n );\n } else {\n // retry\n logger.warn(\n `${status} while loading ${context.url}, retrying in ${this.retryDelay}...`\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 // set exponential backoff\n this.retryDelay = Math.min(\n 2 * this.retryDelay,\n config.maxRetryDelay\n );\n stats.retry++;\n }\n }\n } else {\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n self.clearTimeout(this.requestTimeout);\n this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.timeout\n );\n }\n }\n }\n\n loadtimeout(): void {\n logger.warn(`timeout while loading ${this.context.url}`);\n const callbacks = this.callbacks;\n if (callbacks) {\n this.abortInternal();\n callbacks.onTimeout(this.stats, this.context, this.loader);\n }\n }\n\n loadprogress(event: ProgressEvent): void {\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\nexport default XhrLoader;\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","// 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","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","","// module factories are used so entry inlining is disabled\n// startup\n// Load entry module and return exports\nvar __webpack_exports__ = __webpack_require__(\"./src/hls.ts\");\n",""],"names":["AbrController","AudioStreamController","AudioTrackController","SubtitleStreamController","SubtitleTrackController","BufferController","TimelineController","CapLevelController","FPSController","EMEController","CMCDController","XhrLoader","FetchLoader","fetchSupported","Cues","requestMediaKeySystemAccess","logger","hlsDefaultConfig","autoStartLoad","startPosition","defaultAudioCodec","undefined","debug","capLevelOnFPSDrop","capLevelToPlayerSize","ignoreDevicePixelRatio","initialLiveManifestSize","maxBufferLength","backBufferLength","Infinity","maxBufferSize","maxBufferHole","highBufferWatchdogPeriod","nudgeOffset","nudgeMaxRetry","maxFragLookUpTolerance","liveSyncDurationCount","liveMaxLatencyDurationCount","liveSyncDuration","liveMaxLatencyDuration","maxLiveSyncPlaybackRate","liveDurationInfinity","liveBackBufferLength","maxMaxBufferLength","enableWorker","enableSoftwareAES","manifestLoadingTimeOut","manifestLoadingMaxRetry","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","startLevel","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","fragLoadingTimeOut","fragLoadingMaxRetry","fragLoadingRetryDelay","fragLoadingMaxRetryTimeout","startFragPrefetch","fpsDroppedMonitoringPeriod","fpsDroppedMonitoringThreshold","appendErrorMaxRetry","loader","fLoader","pLoader","xhrSetup","licenseXhrSetup","licenseResponseCallback","abrController","bufferController","capLevelController","fpsController","stretchShortVideoTrack","maxAudioFramesDrift","forceKeyFrameOnDiscontinuity","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","abrBandWidthFactor","abrBandWidthUpFactor","abrMaxWithRealBitrate","maxStarvationDelay","maxLoadingDelay","minAutoBitrate","emeEnabled","widevineLicenseUrl","drmSystemOptions","requestMediaKeySystemAccessFunc","testBandwidth","progressive","lowLatencyMode","cmcd","enableDateRangeMetadataCues","enableEmsgMetadataCues","enableID3MetadataCues","timelineConfig","subtitleStreamController","__USE_SUBTITLES__","subtitleTrackController","timelineController","audioStreamController","__USE_ALT_AUDIO__","audioTrackController","emeController","__USE_EME_DRM__","cmcdController","__USE_CMCD__","cueHandler","enableWebVTT","enableIMSC1","enableCEA708Captions","captionsTextTrack1Label","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","captionsTextTrack3Label","captionsTextTrack3LanguageCode","captionsTextTrack4Label","captionsTextTrack4LanguageCode","renderTextTracksNatively","mergeConfig","defaultConfig","userConfig","Error","enableStreamingMode","config","currentLoader","log","canStreamProgressively","EwmaBandWidthEstimator","Events","ErrorDetails","PlaylistLevelType","hls","lastLoadedFragLevel","_nextAutoLevel","timer","onCheck","_abandonRulesCheck","bind","fragCurrent","partCurrent","bitrateTestDelay","bwEstimator","registerListeners","on","FRAG_LOADING","onFragLoading","FRAG_LOADED","onFragLoaded","FRAG_BUFFERED","onFragBuffered","LEVEL_LOADED","onLevelLoaded","ERROR","onError","unregisterListeners","off","destroy","clearTimer","event","data","frag","type","MAIN","part","self","setInterval","details","live","update","autoLevelEnabled","media","stats","duration","aborted","loaded","total","level","paused","playbackRate","readyState","bufferInfo","mainForwardBufferInfo","requestDelay","performance","now","loading","start","Math","abs","loadedFirstByte","first","bwEstimate","getEstimate","levels","minAutoLevel","expectedLen","max","round","maxBitrate","loadRate","fragLoadedDelay","bufferStarvationDelay","len","fragLevelNextLoadedDelay","Number","POSITIVE_INFINITY","nextLoadLevel","levelNextBitrate","warn","sn","index","toFixed","sample","keyLoader","abortRequests","trigger","FRAG_LOAD_EMERGENCY_ABORTED","loadedBytes","bytes","loadedDuration","realBitrate","bitrateTest","fragBufferedData","id","processingMs","parsing","end","FRAG_LOAD_ERROR","FRAG_LOAD_TIMEOUT","clearInterval","getNextABRAutoLevel","maxAutoLevel","currentFragDuration","pos","currentTime","avgbw","bestLevel","findBestLevel","trace","min","bwFactor","bwUpFactor","currentBw","maxFetchDuration","currentLevel","currentCodecSet","codecSet","i","levelInfo","levelDetails","avgDuration","partTarget","averagetargetduration","adjustedbw","bitrate","fetchDuration","forcedAutoLevel","canEstimate","nextABRAutoLevel","loadError","nextLevel","BaseStreamController","State","BufferHelper","FragmentState","Level","ElementaryStreamTypes","ChunkCache","TransmuxerInterface","ChunkMetadata","fragmentWithinToleranceTest","alignMediaPlaylistByPDT","TICK_INTERVAL","fragmentTracker","videoBuffer","videoTrackCC","waitingVideoCC","audioSwitch","trackId","waitingData","mainDetails","bufferFlushed","cachedTrackLoadedData","_registerListeners","onHandlerDestroying","_unregisterListeners","MEDIA_ATTACHED","onMediaAttached","MEDIA_DETACHING","onMediaDetaching","MANIFEST_LOADING","onManifestLoading","AUDIO_TRACKS_UPDATED","onAudioTracksUpdated","AUDIO_TRACK_SWITCHING","onAudioTrackSwitching","AUDIO_TRACK_LOADED","onAudioTrackLoaded","BUFFER_RESET","onBufferReset","BUFFER_CREATED","onBufferCreated","BUFFER_FLUSHED","onBufferFlushed","INIT_PTS_FOUND","onInitPtsFound","initPTS","cc","state","WAITING_INIT_PTS","tick","startLoad","STOPPED","lastCurrentTime","stopLoad","fragLoadError","IDLE","loadedmetadata","WAITING_TRACK","nextLoadPosition","doTick","doTickIdle","waitForCdnTuneIn","FRAG_LOADING_WAITING_RETRY","retryDate","seeking","resetStartWhenNotLoaded","cache","complete","payload","flush","networkDetails","_handleFragmentLoadProgress","_handleFragmentLoadComplete","clearWaitingFragment","getLoadPosition","mediaBuffer","waitingFragmentAtPosition","onTickEnd","removeFragment","resetLoadingState","startFragRequested","trackDetails","levelLastLoaded","bufferable","afterBufferFlushed","AUDIO","getFwdBufferInfo","mainBufferInfo","bufferLen","maxBufLen","getMaxBufferLength","_streamEnded","BUFFER_EOS","ENDED","fragments","targetBufferTime","PTSKnown","nextStart","targetduration","getNextFragment","loadFragment","mainBufferLength","maxConfigBuffer","audioTracks","resetTransmuxer","map","mediaPlaylist","altAudio","url","removeAllFragments","newDetails","startSN","endSN","totalduration","track","sliding","deltaUpdateFailed","hasProgramDateTime","alignPlaylists","setStartPosition","console","assert","audioCodec","transmuxer","_handleTransmuxComplete","_handleTransmuxerFlush","initSegmentData","initSegment","accurateTimeOffset","partIndex","partial","chunkMeta","chunkCount","byteLength","push","Uint8Array","fragLoadedData","audioTrack","tracks","audio","buffer","video","buffered","length","fragContextChanged","fragPrevious","AUDIO_TRACK_SWITCHED","fragBufferedComplete","KEY_LOAD_ERROR","KEY_LOAD_TIMEOUT","onFragmentOrKeyLoadError","AUDIO_TRACK_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","fatal","BUFFER_FULL_ERROR","parent","PARSING","PARSED","flushBuffer","bufferedInfo","reduceMaxBufferLength","flushMainBuffer","transmuxResult","remuxResult","context","getCurrentContext","text","id3","completeAudioSwitch","_bufferInitSegment","FRAG_PARSING_INIT_SEGMENT","startPTS","endPTS","startDTS","endDTS","elementaryStreams","setElementaryStreamInfo","bufferFragmentData","samples","emittedID3","FRAG_PARSING_METADATA","emittedText","FRAG_PARSING_USERDATA","levelCodec","codec","container","BUFFER_CODECS","segment","BUFFER_APPENDING","fragState","getState","NOT_LOADED","PARTIAL","_loadInitSegment","ErrorTypes","BasePlaylistController","PlaylistContextType","groupId","tracksInGroup","trackName","selectDefaultTrack","MANIFEST_PARSED","onManifestParsed","LEVEL_LOADING","onLevelLoading","LEVEL_SWITCHING","onLevelSwitching","currentTrack","curDetails","retryCount","playlistLoaded","switchLevel","levelIndex","audioGroupIds","audioGroupId","urlId","filter","some","default","audioTracksUpdated","selectInitialTrack","AUDIO_TRACK","retryLoadingOrFail","setAudioTrack","newId","lastTrack","name","hlsUrlParameters","switchParams","loadPlaylist","currentAudioTrackName","findTrackId","MEDIA_ERROR","shouldLoadTrack","addDirectives","error","AUDIO_TRACK_LOADING","deliveryDirectives","getSkipValue","HlsSkip","HlsUrlParameters","computeReloadInterval","mergeDetails","logPrefix","requestScheduled","canLoad","NETWORK_ERROR","clearTimeout","playlistUri","previous","renditionReports","attr","uri","URI","slice","msn","parseInt","currentGoal","age","No","previousDetails","elapsed","advancedDateTime","Date","reloaded","advanced","lastPartSn","lastPartIndex","canBlockReload","endSn","hasParts","lastPart","nextSnStartIndex","lastAdvanced","cdnAge","ageHeader","tuneInGoal","segments","floor","parts","getDeliveryDirectives","position","distanceToLiveEdgeMs","edge","reloadInterval","updated","estimatedTimeUntilUpdate","setTimeout","previousDeliveryDirectives","skip","errorEvent","retry","indexOf","delay","pow","TaskLoop","appendUint8Array","alignStream","findFragmentByPDT","findFragmentByPTS","findFragWithCC","getFragmentWithSN","getPartWith","updateFragPTSDTS","FragmentLoader","LoadError","KeyLoader","Decrypter","TimeRanges","KEY_LOADING","WAITING_LEVEL","_state","fragmentLoader","decrypter","onvseeking","onvended","abort","clearNextTick","partList","lastPartBuffered","isBuffered","OK","onMediaSeeking","onMediaEnded","addEventListener","ended","removeEventListener","tolerance","fragStartOffset","fragEndOffset","pastFragment","tickImmediate","onHandlerDestroyed","_loadFragForPlayback","progressCallback","_doFragLoad","then","catch","reason","resetFragmentLoading","startOffset","endOffset","flushScope","BUFFER_FLUSHING","decryptData","decryptdata","key","iv","method","startTime","decrypt","decryptedData","endTime","FRAG_DECRYPTED","tstart","tdecrypt","buffering","toString","getBuffered","seekToStartPos","fragLoadedEndData","partsLoaded","fragLoaded","keyLoadingPromise","encrypted","load","keyLoadedData","KEY_LOADED","throwIfFragContextChanged","fragmentHint","getNextPart","parseFloat","doFragPartsLoad","handleFragLoadError","loadedEndOfParts","Promise","resolve","dataOnProgress","all","reject","loadPartIndex","loadPart","partLoadedData","loadedPart","nextPart","fragment","INTERNAL_ABORTED","handleFragLoadAborted","updateLevelTiming","data1","data2","dropped","independent","flushBufferGap","fragDuration","segmentFraction","bufferedFragAtPos","getBufferedFrag","levelBitrate","threshold","minLength","fragLen","getInitialLiveFragment","liveSyncPosition","partEnd","fragmentEnd","getFragmentAtPosition","mapToInitFragWhenRequired","contiguous","independentAttrOmitted","programDateTime","endProgramDateTime","targetSN","fragNext","liveStart","bufferEnd","loadingParts","concat","lookupTolerance","curSNIdx","sameLevel","nextFrag","synchronizeToLiveEdge","withinSlidingWindow","maxLatency","lastLevel","slidingStart","firstLevelLoad","aligned","alignedSliding","alignedSlidingStart","advancePartLimit","partHoldBack","startTimeOffset","filterType","levelRetry","bufferType","playlistType","bufferedTimeRanges","detectEvictedFragments","parsed","Object","keys","reduce","result","info","parsedDuration","drift","LEVEL_PTS_UPDATED","FRAG_PARSED","nextState","previousState","getMediaSource","BufferOperationQueue","MediaSource","VIDEO_CODEC_PROFILE_REPACE","_objectUrl","operationQueue","listeners","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","appendError","pendingTracks","sourceBuffer","_onMediaSourceOpen","updateMediaElementDuration","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","_initSourceBuffer","hasSourceTypes","getSourceBufferTypes","MEDIA_ATTACHING","onMediaAttaching","onBufferAppending","onBufferCodecs","onBufferEos","onBufferFlushing","LEVEL_UPDATED","onLevelUpdated","onFragParsed","FRAG_CHANGED","onFragChanged","audiovideo","codecEvents","ms","src","URL","createObjectURL","endOfStream","err","message","revokeObjectURL","removeAttribute","MEDIA_DETACHED","forEach","sb","removeBufferListeners","removeSourceBuffer","sourceBufferCount","changeType","metadata","currentCodec","replace","nextCodec","mimeType","appendChangeType","operation","execute","shiftAndExecuteNext","onStart","onComplete","e","append","eventData","chunkStats","bufferAppendingStart","fragBuffering","partBuffering","checkTimestampOffset","executeStart","delta","timestampOffset","appendExecutor","executeEnd","timeRanges","BUFFER_APPENDED","BUFFER_APPEND_ERROR","code","DOMException","QUOTA_EXCEEDED_ERR","flushOperation","removeExecutor","buffersAppendedTo","AUDIOVIDEO","VIDEO","onUnblocked","blockBuffers","flushBackBuffer","acc","sourceBufferTypes","targetDuration","levelTargetDuration","maxBackBufferLength","targetBackBufferPosition","BACK_BUFFER_REACHED","LIVE_BACK_BUFFER_REACHED","levelDuration","mediaDuration","msDuration","updateSeekableRange","setLiveSeekableRange","pendingTracksCount","createSourceBuffers","buffers","BUFFER_INCOMPATIBLE_CODECS_ERROR","executeNext","tracksCreated","addSourceBuffer","sbName","addBufferListener","_onSBUpdateStart","_onSBUpdateEnd","_onSBUpdateError","BUFFER_ADD_CODEC_ERROR","current","BUFFER_APPENDING_ERROR","removeStart","removeEnd","updating","remove","appendBuffer","blockingOperations","appendBlocker","fn","listener","l","sourceBufferReference","queues","queue","insertAbort","unshift","promise","shift","autoLevelCapping","firstLevel","restrictedLevels","streamController","clientRect","setStreamController","unregisterListener","stopCapping","FPS_DROP_LEVEL_CAPPING","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","startCapping","detectPlayerSize","mediaHeight","mediaWidth","getMaxLevel","nextLevelSwitch","capLevelIndex","validLevels","getMaxLevelByMediaSize","getDimensions","boundsRect","width","height","getBoundingClientRect","right","left","bottom","top","atGreatestBandwidth","curLevel","maxLevelIndex","contentScaleFactor","pixelRatio","devicePixelRatio","CMCDObjectType","CMCDStreamingFormat","CMCDVersion","sid","cid","useHeaders","initialized","starved","audioBuffer","onWaiting","onPlaying","applyPlaylistData","apply","ot","MANIFEST","su","applyFragmentData","getObjectType","d","MUXED","br","tb","getTopBandwidth","bl","getBufferLength","createPlaylistLoader","createFragmentLoader","sessionId","uuid","contentId","onMediaDetached","createData","v","sf","HLS","pr","mtp","bandwidthEstimate","isVideo","INIT","bs","headers","toHeaders","query","toQuery","appendQueryToUri","TIMED_TEXT","NaN","Ctor","callbacks","Blob","lastIndexOf","serialize","results","isValid","value","isNaN","toRounded","toHundred","toUrlSafe","encodeURIComponent","formatters","dl","nor","rtp","sort","formatter","JSON","stringify","join","headerNames","headerGroups","headerMap","nrr","st","separator","includes","KeySystems","MAX_LICENSE_REQUEST_FAILURES","createWidevineMediaKeySystemConfigurations","audioCodecs","videoCodecs","baseConfig","audioCapabilities","videoCapabilities","contentType","robustness","audioRobustness","videoRobustness","getSupportedMediaKeySystemConfigurations","keySystem","WIDEVINE","_widevineLicenseUrl","_licenseXhrSetup","_licenseResponseCallback","_emeEnabled","_requestMediaKeySystemAccess","_drmSystemOptions","_config","_mediaKeysList","_media","_hasSetMediaKeys","_requestLicenseFailureCount","mediaKeysPromise","_onMediaEncrypted","onMediaEncrypted","getLicenseServerUrl","_attemptKeySystemAccess","mediaKeySystemConfigs","keySystemAccessPromise","mediaKeySystemAccess","_onMediaKeySystemAccessObtained","mediaKeysListItem","mediaKeysSessionInitialized","mediaKeySystemDomain","createMediaKeys","mediaKeys","_onMediaKeysCreated","mediaKeysSession","createSession","_onNewMediaKeySession","keySession","_onKeySessionMessage","_requestLicense","initDataType","KEY_SYSTEM_ERROR","KEY_SYSTEM_NO_KEYS","finallySetKeyAndStartSession","_attemptSetMediaKeys","_generateRequestWithPreferredKeySession","initData","keysListItem","setMediaKeys","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_NO_INIT_DATA","generateRequest","_createLicenseXhr","keyMessage","callback","xhr","XMLHttpRequest","responseType","onreadystatechange","_onLicenseRequestReadyStageChange","call","open","status","response","statusText","KEY_SYSTEM_LICENSE_REQUEST_FAILED","attemptsLeft","_generateLicenseRequestChallenge","challenge","send","mediaKeysList","close","videoCodec","isVideoPlaybackQualityAvailable","lastTime","lastDroppedFrames","lastDecodedFrames","getVideoPlaybackQuality","checkFPSInterval","checkFPS","decodedFrames","droppedFrames","currentPeriod","currentDropped","currentDecoded","droppedFPS","FPS_DROP","totalDroppedFrames","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","BinarySearch","PDTValue","Array","isArray","startPDT","endPDT","seg","pdtWithinToleranceTest","foundFragment","search","candidate","candidateLookupTolerance","deltaPTS","pdtBufferEnd","FragmentTracker","activeFragment","activeParts","create","bufferPadding","onBufferAppended","getAppendedFrag","levelType","activePart","appendedPTS","fragmentEntity","body","elementaryStream","timeRange","esData","range","time","isNotBuffered","isTimeBuffered","detectPartialFragments","fragKey","getFragmentKey","streamInfo","getBufferedTimes","fragBuffered","minEndPTS","maxStartPTS","getPartialFragment","bestFragment","timePadding","bestOverlap","isPartial","APPENDING","rangeEnd","hasFragment","removeFragmentsInRange","clearElementaryStreamInfo","STALL_MINIMUM_DURATION_MS","MAX_START_GAP_JUMP","SKIP_BUFFER_HOLE_STEP_SECONDS","SKIP_BUFFER_RANGE_START","GapController","nudgeRetry","stallReported","stalled","moved","poll","activeFrag","seeked","beginSeek","stalledDuration","hasEnoughBuffer","noBufferGap","startJump","isLive","maxStartGapJump","_trySkipBufferHole","tnow","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","targetTime","_tryNudgeBuffer","BUFFER_STALLED_ERROR","lastEndTime","BUFFER_SEEK_OVER_HOLE","BUFFER_NUDGE_ON_STALL","sendAddTrackEvent","clearCurrentCues","removeCuesInRange","ID3","DateRangeAttribute","MetadataSchema","MIN_CUE_DURATION","getCueClass","WebKitDataCue","VTTCue","TextTrackCue","MAX_CUE_ENDTIME","Cue","MAX_VALUE","dateRangeDateToTimelineSeconds","date","offset","getTime","hexToArrayBuffer","str","from","split","ID3TrackController","id3Track","dateRangeCuesAppended","onFragParsingMetadata","createTrack","getID3Track","textTracks","mode","textTrack","kind","label","addTextTrack","emsg","frames","getID3Frames","pts","timeDiff","j","frame","isTimeStampFrame","updateId3CueEnds","cue","addCue","cues","predicate","audioId3","dateRanges","ids","idsToRemove","removeCue","lastFragment","dateTimeOffset","dateRange","appendedDateRangeCues","durationKnown","startDate","endDate","endOnNext","nextDateRangeWithSameClass","filterMapArray","class","a","b","attributes","ID","CLASS","START_DATE","DURATION","END_DATE","END_ON_NEXT","SCTE35_OUT","SCTE35_IN","LatencyController","stallCount","_latency","timeupdateHandler","timeupdate","latency","computeLatency","targetLatency","distanceFromTarget","liveMinLatencyDuration","inLiveRange","forwardBufferLength","rate","exp","edgeStalled","estimateLiveEdge","liveEdge","holdBack","maxLiveSyncOnStallIncrease","liveSyncOnStallIncrease","syncPosition","maxLevelUpdateAge","bufferedRanges","isCodecSupportedInMp4","addGroupId","assignTrackIdsByGroup","chromeOrFirefox","test","navigator","userAgent","toLowerCase","LevelController","_levels","_firstLevel","_startLevel","currentLevelIndex","manualLevelIndex","onParsedComplete","MANIFEST_LOADED","onManifestLoaded","onAudioTrackSwitched","subtitleTracks","bitrateStart","levelSet","levelFromSet","resolutionFound","videoCodecFound","audioCodecFound","levelParsed","attrs","levelKey","RESOLUTION","CODECS","SUBTITLES","subtitles","audioOnly","edata","t","forceStartLoad","MANIFEST_INCOMPATIBLE_CODECS_ERROR","SUBTITLE_TRACK","textGroupIds","redundantFailover","levelError","levelSwitch","variantLevelIndex","fragmentError","LEVEL_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","REMUX_ALLOC_ERROR","recoverLevel","errorDetails","retrying","redundantLevels","nextAutoLevel","newUrlId","removeLevel","filterLevelAndGroupByIdIndex","LEVELS_UPDATED","newLevel","OTHER_ERROR","LEVEL_SWITCH_ERROR","lastLevelIndex","levelSwitchingData","_urlId","configStartLevel","DateRange","groups","updatePTS","fromIdx","toIdx","fragFrom","fragTo","updateFromToPTS","fragToPTS","parsedMediaDuration","fragStartPts","fragEndPts","fragIdx","oldDetails","currentInitSegment","oldFragments","oldInit","ccOffset","PTSFrag","mapFragmentIntersection","oldFrag","newFrag","relurl","fragmentsToCheck","skippedSegments","startCC","canSkipDateRanges","mergeDateRanges","recentlyRemovedDateranges","newFragments","mapPartIntersection","oldPart","newPart","adjustSliding","driftStartTime","driftStart","driftEndTime","driftEnd","oldDateRanges","deltaDateRanges","oldParts","newParts","intersectionFn","newFrags","oldFrags","addSliding","liveEdgeMaxTargetDurations","lastSegmentDuration","changeTypeSupported","StreamController","audioCodecSwap","gapController","_forceStartLoad","fragPlaying","onvplaying","onvseeked","fragLastKbps","couldBacktrack","backtrackFragment","audioCodecSwitch","onFragLoadEmergencyAborted","onLevelsUpdated","checkBuffer","checkFragmentChanged","getMainFwdBufferInfo","backtrackSn","backtrackFrag","_loadBitrateTestFrag","fragOrPart","followingBufferedFrag","immediateLevelSwitch","abortCurrentFrag","fetchdelay","fragPlayingCurrent","nextLevelId","bufferedFrag","nextBufferedFrag","maxStart","startPts","onMediaPlaying","onMediaSeeked","aac","heaac","newLevelId","endCC","_getAudioCodec","fromAltAudio","mediaTrack","alternate","videoTrack","swapAudioCodec","bufferStart","timescale","firstKeyFrame","firstKeyFramePTS","backtrack","ua","channelCount","fragCurrentLevel","LEVEL_SWITCHED","currentFrag","epocMs","currentTrackId","tracksBuffered","SUBTITLE_TRACKS_UPDATED","onSubtitleTracksUpdated","SUBTITLE_TRACK_SWITCH","onSubtitleTrackSwitch","SUBTITLE_TRACK_LOADED","onSubtitleTrackLoaded","SUBTITLE_FRAG_PROCESSED","onSubtitleFragProcessed","success","fragStart","fragEnd","endOffsetSubtitles","SUBTITLE","mediaBufferTimeRanges","mainSlidingStartFragment","foundFrag","BufferableInstance","timeranges","getRange","queuedDefaultTrack","trackChangeListener","onTextTracksChanged","asyncPollTrackChange","pollTrackChange","useTextTrackPolling","subtitlePollingInterval","_subtitleDisplay","subtitleTrack","timeout","filterSubtitleTracks","textGroupId","initialTrackId","subtitleTracksUpdated","setSubtitleTrack","SUBTITLE_TRACK_LOADING","toggleTrackModes","groupTracks","oldTrack","nextTrack","subtitleDisplay","textTrackList","Cea608Parser","OutputFilter","parseWebVTT","addCueToTrack","parseIMSC1","IMSC1_CODEC","enabled","unparsedVttFrags","captionsTracks","nonNativeCaptionsTracks","cea608Parser1","cea608Parser2","lastSn","prevCC","vttCCs","newVTTCCs","captionsProperties","textTrack1","languageCode","textTrack2","textTrack3","textTrack4","channel1","channel2","channel3","channel4","onFragParsingUserdata","onFragDecrypted","SUBTITLE_TRACKS_CLEARED","onSubtitleTracksCleared","addCues","screen","cueRanges","merged","cueRange","overlap","intersection","newCue","CUES_PARSED","getExistingTrack","createCaptionsTrack","createNativeTrack","createNonNativeTrack","existingTrack","createTextTrack","trackProperties","_id","closedCaptions","NON_NATIVE_TEXT_TRACKS_FOUND","lang","_cleanTracks","reset","hasIMSC1","textCodec","sameTracks","inUseTracks","inUseTrack","canReuseVttTextTrack","textTrackKind","_captionsOrSubtitlesFromCharacteristics","tracksList","CHARACTERISTICS","transcribesSpokenDialog","describesMusicAndSound","captions","captionsTrack","instreamIdMatch","exec","instreamId","closedCaptionsForLevel","decrypted","trackPlaylistMedia","new","_parseIMSC1","_parseVTTs","_appendCues","payloadWebVTT","_fallbackToIMSC1","fragLevel","ccBytes","ccdatas","extractCea608Data","addData","byteArray","actualCCBytes","count","tmpByte","ccbyte1","ccbyte2","ccValid","ccType","manifestTrack","x1","x2","y1","y2","presentationOffset","AESCrypto","subtle","aesIV","sliceUint8","removePadding","array","outputBytes","paddingBytes","DataView","getUint8","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","ksRows","keySize","keySchedule","invKeySchedule","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","x","xi","sx","x4","x8","expandKey","keyBuffer","sameKey","ksRow","invKsRow","sbox","prev","networkToHostOrderSwap","word","inputArrayBuffer","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","swapWord","FastAESKey","CHUNK_SIZE","removePKCS7Padding","logEnabled","softwareDecrypter","fastAesKey","remainderData","currentIV","currentResult","useSoftware","browserCrypto","crypto","webkitSubtle","isSync","softwareDecrypt","decryptResult","webCryptoDecrypt","logOnce","currentChunk","getValidChunk","aesKey","onWebCryptoError","splitPoint","msg","importKey","BaseAudioDemuxer","ADTS","AACDemuxer","observer","resetInitSegment","trackDuration","_audioTrack","pid","sequenceNumber","segmentCodec","manifestCodec","inputTimeScale","probe","id3Data","getID3Data","canParse","appendFrame","initTrackConfig","basePTS","frameIndex","missing","getAudioConfig","adtsObjectType","adtsExtensionSamplingIndex","adtsChannelConfig","adtsSamplingRates","adtsSamplingIndex","FRAG_PARSING_ERROR","samplerate","isHeaderPattern","getHeaderLength","getFullFrameLength","canGetFrameLength","isHeader","headerLength","frameLength","newOffset","getFrameDuration","parseFrameHeader","frameDuration","stamp","header","unit","set","subarray","dummyTrack","_id3Track","cachedData","lastPTS","resetTimeStamp","deaultTimestamp","resetContiguity","demux","timeOffset","lastDataIndex","timestamp","getTimeStamp","initPTSFn","dts","partialData","demuxSampleAes","keyData","chunks","dataLength","chunk","concatUint8Arrays","ExpGolomb","bytesAvailable","bitsAvailable","loadWord","workingBytes","availableBytes","skipBits","skipBytes","readBits","size","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","readUByte","readUShort","readUInt","skipScalingList","lastScale","nextScale","deltaScale","readSPS","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","numRefFramesInPicOrderCntCycle","scalingListCount","profileIdc","chromaFormatIdc","picOrderCntType","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","aspectRatioIdc","ceil","readSliceType","isFooter","front","readSize","readTimeStamp","getFrameData","String","fromCharCode","frameData","decodeFrame","decodePrivFrame","decodeURLFrame","decodeTextFrame","owner","utf8ArrayToStr","privateData","description","timeStampFrame","pts33Bit","exitOnNull","decoder","getTextDecoder","decoded","decode","idx","substring","c","char2","char3","out","testables","TextDecoder","MpegAudio","MP3Demuxer","findBox","segmentValidRange","parseEmsg","parseSamples","parseInitSegment","RemuxerTrackIdConfig","emsgSchemePattern","MP4Demuxer","txtTrack","captionTrack","sampleDuration","videoSamples","segmentedData","remainder","valid","extractID3Track","emsgs","emsgInfo","schemeIdUri","presentationTime","timeScale","presentationTimeDelta","eventDuration","chromeVersion","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","mpegVersion","mpegLayer","bitRateIndex","sampleRateIndex","paddingBit","channelMode","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","match","needChromeFix","headerSize","discardEPB","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","curUnit","encryptedBuffer","byteOffset","decryptedBuffer","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","uint8DecryptedData","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","units","work","Transmuxer","TransmuxConfig","TransmuxState","isPromise","EventEmitter","isTypeSupported","onTransmuxComplete","onFlush","useWorker","worker","onwmsg","forwardMessage","ev","typeSupported","mp4","mpeg","mp3","vendor","Worker","require","onWorkerMessage","onerror","INTERNAL_EXCEPTION","filename","lineno","postMessage","cmd","objectURL","w","terminate","removeAllListeners","defaultInitPTS","transmuxing","lastFrag","discontinuity","trackSwitch","snDiff","partDiff","initSegmentChange","configureTransmuxer","ArrayBuffer","handleTransmuxComplete","handleFlushResult","logType","configure","enableLogs","TransmuxerWorker","forwardWorkerLogs","logFn","func","parse","emitTransmuxComplete","isEmptyResult","transferable","addToTransferable","TSDemuxer","MP4Remuxer","PassThroughRemuxer","muxConfig","remux","demuxer","remuxer","decryptionPromise","transmuxConfig","currentTransmuxState","uintData","defaultInitPts","resetInitialTimestamp","getEncryptionType","getDecrypter","emptyResult","needsProbing","transmux","currentState","transmuxResults","emit","demuxResultOrPromise","demuxResult","flushRemux","resetNextTimestamp","transmuxSampleAes","transmuxUnencrypted","mux","Remuxer","Demuxer","encryptionType","p","Function","parseSEIMessageFromNALu","PACKET_LENGTH","sampleAes","pmtParsed","_duration","_pmtId","_avcTrack","_txtTrack","aacOverFlow","avcSample","syncOffset","scanwindow","pesData","isSampleAes","pes","avcId","avcData","audioId","id3Id","audioData","unknownPID","pmtId","tsPacketErrors","stt","atf","parsePES","parseAVCPES","parseAACPES","parseMPEGPES","parseID3PES","parsePAT","parsedPIDs","parsePMT","avc","extractRemainingSamples","last","parseAVCNALu","spsfound","audFound","pushAccessUnit","createAVCSample","sliceType","sps","expGolombDecoder","codecarray","codecstring","h","pps","getLastNalUnit","lastUnit","naluState","lastState","overflow","unitType","lastUnitStart","lastUnitType","tmp","frameMissingBytes","sampleLength","frameOverflowBytes","id3Sample","sectionLength","tableEnd","programInfoLength","stream","pesLen","pesHdrLen","pesPts","pesDts","newData","splice","pesPrefix","pesFlags","payloadStartOffset","dataLen","avcTrack","nbSamples","lastSample","webpackBootstrapFunc","__webpack_modules__","ENTRY_MODULE","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","m","n","getter","__esModule","definition","o","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","r","Symbol","toStringTag","webpackBootstrapFuncArr","moduleNameReqExp","dependencyRegExp","quoteRegExp","isNumeric","getModuleDependencies","sources","queueName","retval","fnString","wrapperSignature","webpackRequireName","re","RegExp","hasValuesInQueues","hasValues","getRequiredModules","modulesQueue","main","requiredModules","seenModules","moduleToCheck","pop","newModules","newModulesKeys","getWebpackString","entryModule","moduleString","options","modules","blob","window","webkitURL","mozURL","msURL","workerUrl","URLToolkit","PlaylistLoader","isSupported","Hls","coreComponents","networkControllers","_emitter","_autoLevelCapping","latencyController","levelController","DefaultConfig","ConfigAbrController","ConfigBufferController","ConfigCapLevelController","ConfigFpsController","playListLoader","id3TrackController","createController","ControllerClass","components","controllerInstance","once","eventObject","listenerCount","DESTROYING","detachMedia","component","attachMedia","loadSource","loadedSource","loadingSource","buildAbsoluteURL","location","href","alwaysNormalize","controller","recoverMediaError","loadLevel","manualLevel","shouldStartCapping","newCapLevelToPlayerSize","currentProgramDateTime","audioTrackId","subtitleTrackId","__VERSION__","getSourceBuffer","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","AttrList","dateRangeAttr","dateRangeWithSameId","_startDate","_endDate","_badValueForSameId","previousAttr","decimalFloatingPoint","PLANNED_DURATION","bool","MIN_CHUNK_SIZE","partLoadTimeout","onProgress","FragmentILoader","DefaultILoader","loaderContext","createLoaderContext","loaderConfig","maxRetry","retryDelay","maxRetryDelay","highWaterMark","onSuccess","resetLoader","resetIV","onAbort","onTimeout","updateStatsFromPart","fragStats","partStats","partTotal","estTotalParts","estLoadedParts","estRemainingParts","estRemainingBytes","fragLoading","partLoading","rangeStart","byteRangeStartOffset","byteRangeEndOffset","byteRangeStart","byteRangeEnd","fragmentLen","params","LevelKey","LoadStats","BaseSegment","baseurl","_byteRange","_url","setByteRange","byteRange","Fragment","_decryptdata","rawProgramDateTime","tagList","levelkey","title","createInitializationVector","segmentNumber","uint8View","setDecryptDataFromLevelKey","fromURI","keyFormat","Part","partAttrs","fragOffset","gap","enumeratedString","decryptkey","decrypturl","Loader","loaderCallbacks","DEFAULT_TARGET_DURATION","LevelDetails","baseUrl","availabilityDelay","misses","needSidxRanges","m3u8","version","canSkipUntil","preloadHint","partSnDiff","partIndexDiff","runTime","runDuration","fromURL","relativeUrl","absoluteOrBaseURI","relativeURL","_uri","keyFormatVersions","keyID","isCodecType","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","source","LEVEL_PLAYLIST_REGEX_SLOW","MP4_REGEX_SUFFIX","isMP4Url","parseURL","path","M3U8Parser","findGroup","mediaGroupId","group","convertAVC1ToAVCOTI","avcdata","parseMasterPlaylist","string","levelsWithKnownCodecs","sessionData","hasSessionData","lastIndex","decimalInteger","NAME","resolution","decimalResolution","setCodecs","unknownCodecs","sessionAttrs","stripUnknownCodecLevels","parseMasterPlaylistMedia","medias","TYPE","LANGUAGE","autoselect","forced","groupCodec","assignCodec","parseLevelPlaylist","levelUrlId","currentSN","currentPart","discontinuityCounter","prevFrag","firstPdtIndex","createNextFrag","assignProgramDateTime","tag","value1","value2","toUpperCase","skipAttrs","keyAttrs","decryptmethod","decrypturi","decryptiv","hexadecimalInteger","decryptkeyformatversions","decryptkeyid","decryptkeyformat","unsupportedKnownKeyformatsInManifest","startAttrs","mapAttrs","init","setInitSegment","serverControlAttrs","optionalFloat","partInfAttrs","previousFragmentPart","preloadHintAttrs","renditionReportAttrs","fragmentLength","firstFragment","every","backfillProgramDateTimes","codecs","filtered","preferred","groupItem","codecProperty","codecValue","fragPrev","BYTERANGE","parseSegmentIndex","mapContextToLevelType","getResponseUrl","loaders","destroyInternalLoaders","onAudioTrackLoading","onSubtitleTrackLoading","createInternalLoader","PLoader","InternalLoader","getInternalLoader","resetInternalLoader","contextType","LEVEL","loadsuccess","loaderror","loadtimeout","isSidxRequest","handleSidxRequest","handlePlaylistLoaded","handleManifestParsingError","handleTrackOrLevelPlaylist","handleMasterPlaylist","handleNetworkError","audioGroups","subtitleGroups","embeddedAudioFound","levelId","LEVEL_EMPTY_ERROR","singleLevel","sidxUrl","sidxBox","sidxInfo","sidxReferences","references","segmentRef","segRefInfo","moovBox","moovEndOffset","MANIFEST_PARSING_ERROR","UNKNOWN","MANIFEST_LOAD_TIMEOUT","MANIFEST_LOAD_ERROR","SUBTITLE_TRACK_LOAD_TIMEOUT","SUBTITLE_LOAD_ERROR","errorData","getCacheAge","isFiniteNumber","isFinite","MAX_SAFE_INTEGER","AAC","getSilentFrame","UINT32_MAX","MP4","types","avc1","avcC","btrt","dinf","dref","esds","ftyp","hdlr","mdat","mdhd","mdia","mfhd","minf","moof","moov","mp4a","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","tfdt","tfhd","traf","trak","trun","trex","tkhd","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","upperWordDuration","lowerWordDuration","baseMediaDecodeTime","boxes","flags","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","arraylen","cts","isLeading","paddingValue","isNonSync","degradPrio","movie","toMsFromMpegTsClock","MAX_SILENT_FRAME_DURATION","AAC_SAMPLES_PER_FRAME","MPEG_AUDIO_SAMPLE_PER_FRAME","safariWebkitVersion","ISGenerated","_initPTS","_initDTS","nextAvcDts","nextAudioPts","videoSampleDuration","isAudioContiguous","isVideoContiguous","defaultTimeStamp","getVideoStartPts","rolloverDetected","minPTS","normalizePts","audioTimeOffset","videoTimeOffset","hasAudio","hasVideo","enoughAudioSamples","enoughVideoSamples","canRemuxAvc","generateIS","firstKeyFrameIndex","findKeyframeIndex","tsDelta","audiovideoTimestampDelta","remuxAudio","audioTrackLength","remuxVideo","flushTextTrackMetadataCueSamples","flushTextTrackUserdataCueSamples","audioSamples","computePTSDTS","initDTS","inputSamples","outputSamples","mp4SampleDuration","firstDTS","lastDTS","maxPTS","NEGATIVE_INFINITY","sortSamples","deltadts","deltapts","inputDuration","averageSampleDuration","foundHole","foundOverlap","firstPTS","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","MUX_ERROR","setUint32","stretchedLastFrame","minDtsDelta","minPtsDelta","maxDtsDelta","maxPtsDelta","avcSampleUnits","mp4SampleLength","unitData","unitDataLen","ptsDelta","lastFrameDuration","gapTolerance","deltaToFrameEnd","compositionTimeOffset","Mp4Sample","nextDts","nextPts","nb","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","alignedWithVideo","timeOffsetMpegTS","newStamp","fillFrame","audioSample","prevSample","unitLen","remuxEmptyAudio","videoData","silentFrame","reference","isKeyframe","Mp4SampleFlags","getDuration","getStartDTS","offsetStartDTS","emitInitSegment","initTracks","generateInitSegment","getParsedTrackCodec","initPtsNum","parsedCodec","_boundTick","_tickTimer","_tickInterval","_tickCallCount","hasInterval","hasNextTick","millis","CMCDStreamType","snChangeGoal","v2","Yes","searchParams","newValue","getNewPerformanceTiming","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","parseAttrList","attrName","intValue","stringValue","hexadecimalIntegerAsNumber","defaultValue","res","input","quote","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","noopBuffered","maxHoleDuration","vbuffered","diff","buffered2","buf2len","buf2end","bufferStartNext","specialCea608CharsCodes","getCharForByte","byte","charCode","NR_ROWS","NR_COLS","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","VerboseLevel","CaptionsLogger","verboseLevel","severity","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","setStyles","styles","attribs","style","isDefault","equals","other","copy","newPenState","StyledUnicodeChar","uchar","penState","setChar","setPenState","newChar","isEmpty","Row","chars","currPenState","cueStartTime","equal","empty","setCursor","absPos","DEBUG","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","currChar","CaptionScreen","rows","currRow","nrRollUpRows","lastOutputScreen","row","setPen","INFO","setPAC","pacData","newRow","topRowIndex","prevLineTime","indent","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","TEXT","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","trim","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","getHandler","setHandler","newHandler","setMode","newMode","insertChars","outputDataUpdate","ccRCL","ccBS","ccAOF","ccAON","ccDER","ccRU","ccFON","ccRDC","ccTR","ccRTD","ccEDM","ccCR","ccENM","ccEOC","ccTO","nrCols","ccMIDROW","secondByte","colorIndex","colors","dispatch","dispatchCue","cueSplitAtTime","field","out1","out2","channels","currentChannel","cmdHistory","createCmdHistory","channel","byteList","cmdFound","charsFound","DATA","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","currChNr","WARNING","cond1","cond2","hasCmdRepeated","setLastCmd","case1","case2","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","sampleEntryCodesISO","a3ds","alac","alaw","dra1","dtsc","dtse","dtsh","enca","g719","g726","m4ae","mha1","mha2","mhm1","mhm2","mlpa","Opus","opus","samr","sawb","sawp","sevc","sqcp","ssmv","twos","ulaw","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","typeCodes","fixLineBreaks","generateCueId","WHITESPACE_CHAR","captionScreen","indenting","cueText","getCueById","line","align","cueA","cueB","findFirstFragWithCC","firstFrag","shouldAlignOnDiscontinuities","findDiscontinuousReferenceFrag","prevDetails","referenceIndex","prevFrags","curFrags","prevStartFrag","adjustFragmentStart","adjustSlidingStart","alignDiscontinuities","alignPDT","referenceFrag","lastDetails","lastPDT","newPDT","refDetails","refFragments","middleFrag","refFrag","refPDT","targetPDT","EWMA","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","halfLife","getTotalWeight","durationMs","numBytes","numBits","durationS","bandwidthInBps","estimate","weight","alpha_","estimate_","totalWeight_","adjAlpha","zeroFactor","fetch","AbortController","ReadableStream","Request","fetchSetup","requestTimeout","request","getRequest","abortInternal","ok","initParams","getRequestParameters","signal","isArrayBuffer","LENGTH","FetchError","loadProgressively","responseData","loaderResponse","chunkCache","reader","getReader","pump","read","done","credentials","Headers","parseTimeStamp","toTimescaleFromScale","HMSF_REGEX","TIME_UNIT_REGEX","textAlignToLineAlign","center","callBack","errorCallBack","ttmlList","syncTime","ttml","parseTTML","parser","DOMParser","xmlDoc","parseFromString","tt","getElementsByTagName","defaultRateInfo","frameRate","subFrameRate","frameRateMultiplier","tickRate","rateInfo","getAttribute","styleElements","collectionToDictionary","getElementCollection","regionElements","cueElements","cueElement","getTextContent","hasAttribute","parseTtmlTime","timestampParsingError","region","getTtmlStyles","textAlign","lineAlign","fromElement","parentName","childName","querySelectorAll","elementsWithId","dict","element","childNodes","node","nodeName","textContent","ttsNs","regionStyle","styleAttributes","regionStyleName","getAttributeNS","ns","hasAttributeNS","timeAttributeValue","seconds","parseHoursMinutesSecondsFrames","parseTimeUnits","noop","fakeLogger","exportedLogger","consolePrintFn","exportLoggerFunctions","debugConfig","functions","WebKitMediaSource","bin2str","readUint16","val","readUint32","readSint32","writeUint32","endbox","subresults","sidx","earliestPresentationTime","firstOffset","startByte","referencesCount","referenceInfo","referenceSize","referenceType","subsegmentDuration","traks","hdlrType","soun","vide","fmp4","baseTime","scale","rawDuration","videoDuration","audioDuration","trafs","trackDefault","tfhdFlags","truns","computeRawDurationFromSamples","sampleCount","sidxDuration","sidxs","dur","ref","upper","lower","segmentedRange","moofs","temp","seiSamples","isHEVCFlavor","moofOffset","baseDataOffsetPresent","sampleDescriptionIndexPresent","defaultSampleDurationPresent","defaultSampleDuration","defaultSampleSizePresent","defaultSampleSize","defaultSampleFlagsPresent","tfhdOffset","isHEVC","dataOffsetPresent","dataOffset","firstSampleFlagsPresent","sampleDurationPresent","sampleSizePresent","sampleSize","sampleFlagsPresent","sampleCompositionOffsetsPresent","compositionOffset","trunOffset","sampleOffset","ix","naluTotalSize","naluSize","isSEIMessage","delimit","baseCodec","naluHeader","naluType","unescapedData","seiPtr","payloadType","payloadSize","endOfCaptions","leftOver","countryCode","providerCode","userStructure","userDataType","firstByte","totalCCs","totalBytes","uuidStrArray","userDataBytes","userData","EPBPositions","newLength","sourceIndex","leftPresentationTime","rightPresentationTime","isSafeInteger","videoEl","Event","document","createEvent","initEvent","dispatchEvent","textTrackCue","getCuesInRange","getFirstCueIndexAfterTime","mid","cuesFound","firstCueInRange","MPEG_TS_CLOCK_FREQ_HZ","toTimescaleFromBase","destScale","srcBase","srcScale","toMpegTsClockFromTimescale","AllowedDirections","AllowedAlignments","isAllowedValue","allowed","lcValue","findDirectionSetting","findAlignSetting","extend","rest","arguments","cobj","baseObj","hasBeenReset","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","TypeError","setting","SyntaxError","displayState","getCueAsHTML","WebVTT","convertCueToDOMTree","StringDecoder","decodeURIComponent","computeSeconds","s","f","Settings","values","k","dflt","defaultKey","has","alt","integer","percent","parseOptions","keyValueDelim","groupDelim","kv","defaults","parseCue","regionList","oInput","consumeTimeStamp","ts","consumeCueSettings","settings","vals","vertical","snapToLines","skipWhitespace","VTTParser","oncue","onparsingerror","onflush","_this","collectNextLine","alreadyCollectedLine","hasSubstring","LINEBREAKS","startsWith","inputString","searchString","cueString2millis","timeString","secs","mins","hours","hash","calculateOffset","currCC","vttByteArray","vttLines","initPTS90Hz","cueTime","timestampMapMPEGTS","timestampMapLOCAL","parsingError","inHeader","cueOffset","webVttMpegTsMapOffset","AGE_HEADER_LINE_REGEX","retryTimeout","onprogress","loadInternal","setRequestHeader","readystatechange","loadprogress","responseText","responseURL","lengthComputable","getAllResponseHeaders","getResponseHeader"],"sourceRoot":""}
|