From 3797f3af4f8241bc725315ba806e03278790e1b5 Mon Sep 17 00:00:00 2001 From: Isaac <> Date: Fri, 8 Nov 2024 16:26:01 +0100 Subject: [PATCH] Video improvements --- .../GalleryUI/Sources/GalleryController.swift | 4 +- .../Sources/GalleryControllerNode.swift | 16 +- .../SecretMediaPreviewController.swift | 2 +- .../InstantPageGalleryController.swift | 2 +- .../Sources/ChunkMediaPlayer.swift | 114 +++--- .../SecureIdDocumentGalleryController.swift | 2 +- .../Sources/AvatarGalleryController.swift | 2 +- .../Sources/TelegramBaseController.swift | 4 +- .../ChatMessageInteractiveMediaNode.swift | 61 +-- .../Sources/PeerInfoScreen.swift | 2 +- .../Sources/WallpaperGalleryController.swift | 2 +- .../Animations/anim_set_notification.tgs | Bin 0 -> 4179 bytes .../TelegramUI/Sources/AppDelegate.swift | 8 - .../Chat/ChatControllerLoadDisplayNode.swift | 13 + .../Sources/ExperimentalUISettings.swift | 2 +- .../HlsBundle/headless_prologue.js | 38 ++ .../HlsBundle/index.bundle.js | 1 - .../HlsBundle/index/index.bundle.js | 2 + .../index/index.bundle.js.LICENSE.txt | 1 + .../HlsBundle/{ => index}/index.html | 0 .../PlayerSource/build.sh | 7 +- .../PlayerSource/package-lock.json | 12 + .../PlayerSource/package.json | 2 + .../PlayerSource/src/VideoElementStub.js | 11 +- .../PlayerSource/src/index.js | 82 +++- .../PlayerSource/webpack.dev.js | 2 +- .../Sources/HLSVideoContent.swift | 10 +- .../Sources/HLSVideoJSNativeContentNode.swift | 359 +++++++----------- .../Sources/WebViewHLSJSContextImpl.swift | 76 ++++ .../Sources/WebViewNativeJSContextImpl.swift | 248 ++++++++++++ .../Sources/WebSearchGalleryController.swift | 2 +- 31 files changed, 773 insertions(+), 314 deletions(-) create mode 100644 submodules/TelegramUI/Resources/Animations/anim_set_notification.tgs create mode 100644 submodules/TelegramUniversalVideoContent/HlsBundle/headless_prologue.js delete mode 100644 submodules/TelegramUniversalVideoContent/HlsBundle/index.bundle.js create mode 100644 submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js create mode 100644 submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js.LICENSE.txt rename submodules/TelegramUniversalVideoContent/HlsBundle/{ => index}/index.html (100%) create mode 100644 submodules/TelegramUniversalVideoContent/Sources/WebViewHLSJSContextImpl.swift create mode 100644 submodules/TelegramUniversalVideoContent/Sources/WebViewNativeJSContextImpl.swift diff --git a/submodules/GalleryUI/Sources/GalleryController.swift b/submodules/GalleryUI/Sources/GalleryController.swift index e2adc98ad3..e78ce6375a 100644 --- a/submodules/GalleryUI/Sources/GalleryController.swift +++ b/submodules/GalleryUI/Sources/GalleryController.swift @@ -259,7 +259,7 @@ public func galleryItemForEntry( } if isHLS { - content = HLSVideoContent(id: .message(message.id, message.stableId, file.fileId), userLocation: .peer(message.id.peerId), fileReference: .message(message: MessageReference(message), media: file), streamVideo: streamVideos, loopVideo: loopVideos) + content = HLSVideoContent(id: .message(message.stableId, file.fileId), userLocation: .peer(message.id.peerId), fileReference: .message(message: MessageReference(message), media: file), streamVideo: streamVideos, loopVideo: loopVideos) } else { content = NativeVideoContent(id: .message(message.stableId, file.fileId), userLocation: .peer(message.id.peerId), fileReference: .message(message: MessageReference(message), media: file), imageReference: mediaImage.flatMap({ ImageMediaReference.message(message: MessageReference(message), media: $0) }), streamVideo: .conservative, loopVideo: loopVideos, tempFilePath: tempFilePath, captureProtected: captureProtected, storeAfterDownload: generateStoreAfterDownload?(message, file)) } @@ -1364,7 +1364,7 @@ public class GalleryController: ViewController, StandalonePresentableController, }) let disableTapNavigation = !(self.context.sharedContext.currentMediaDisplaySettings.with { $0 }.showNextMediaOnTap) - self.displayNode = GalleryControllerNode(controllerInteraction: controllerInteraction, disableTapNavigation: disableTapNavigation) + self.displayNode = GalleryControllerNode(context: self.context, controllerInteraction: controllerInteraction, disableTapNavigation: disableTapNavigation) self.displayNodeDidLoad() self.galleryNode.statusBar = self.statusBar diff --git a/submodules/GalleryUI/Sources/GalleryControllerNode.swift b/submodules/GalleryUI/Sources/GalleryControllerNode.swift index d269eddc5e..8da53f9fb6 100644 --- a/submodules/GalleryUI/Sources/GalleryControllerNode.swift +++ b/submodules/GalleryUI/Sources/GalleryControllerNode.swift @@ -5,8 +5,11 @@ import Display import Postbox import SwipeToDismissGesture import AccountContext +import UndoUI open class GalleryControllerNode: ASDisplayNode, ASScrollViewDelegate, ASGestureRecognizerDelegate { + private let context: AccountContext + public var statusBar: StatusBar? public var navigationBar: NavigationBar? { didSet { @@ -48,7 +51,8 @@ open class GalleryControllerNode: ASDisplayNode, ASScrollViewDelegate, ASGesture } } - public init(controllerInteraction: GalleryControllerInteraction, pageGap: CGFloat = 20.0, disableTapNavigation: Bool = false) { + public init(context: AccountContext, controllerInteraction: GalleryControllerInteraction, pageGap: CGFloat = 20.0, disableTapNavigation: Bool = false) { + self.context = context self.backgroundNode = ASDisplayNode() self.backgroundNode.backgroundColor = UIColor.black self.scrollView = UIScrollView() @@ -471,6 +475,16 @@ open class GalleryControllerNode: ASDisplayNode, ASScrollViewDelegate, ASGesture let minimalDismissDistance = scrollView.contentSize.height / 12.0 if abs(velocity.y) > 1.0 || abs(distanceFromEquilibrium) > minimalDismissDistance { if distanceFromEquilibrium > 1.0, let centralItemNode = self.pager.centralItemNode(), centralItemNode.maybePerformActionForSwipeDismiss() { + if let chatController = self.baseNavigationController()?.topViewController as? ChatController { + let presentationData = self.context.sharedContext.currentPresentationData.with({ $0 }) + //TODO:localize + chatController.present(UndoOverlayController( + presentationData: presentationData, + content: .hidArchive(title: "Video Minimized", text: "Swipe down on a video to close it.", undo: false), + elevatedLayout: false, action: { _ in true } + ), in: .current) + } + return } diff --git a/submodules/GalleryUI/Sources/SecretMediaPreviewController.swift b/submodules/GalleryUI/Sources/SecretMediaPreviewController.swift index 2d5c388ef5..3a33f9bde7 100644 --- a/submodules/GalleryUI/Sources/SecretMediaPreviewController.swift +++ b/submodules/GalleryUI/Sources/SecretMediaPreviewController.swift @@ -254,7 +254,7 @@ public final class SecretMediaPreviewController: ViewController { }, controller: { [weak self] in return self }) - self.displayNode = SecretMediaPreviewControllerNode(controllerInteraction: controllerInteraction) + self.displayNode = SecretMediaPreviewControllerNode(context: self.context, controllerInteraction: controllerInteraction) self.displayNodeDidLoad() self.controllerNode.statusPressed = { [weak self] _ in diff --git a/submodules/InstantPageUI/Sources/InstantPageGalleryController.swift b/submodules/InstantPageUI/Sources/InstantPageGalleryController.swift index 3735bdd4b8..9a8f39f9bb 100644 --- a/submodules/InstantPageUI/Sources/InstantPageGalleryController.swift +++ b/submodules/InstantPageUI/Sources/InstantPageGalleryController.swift @@ -377,7 +377,7 @@ public class InstantPageGalleryController: ViewController, StandalonePresentable }, controller: { [weak self] in return self }) - self.displayNode = GalleryControllerNode(controllerInteraction: controllerInteraction) + self.displayNode = GalleryControllerNode(context: self.context,controllerInteraction: controllerInteraction) self.displayNodeDidLoad() self.galleryNode.statusBar = self.statusBar diff --git a/submodules/MediaPlayer/Sources/ChunkMediaPlayer.swift b/submodules/MediaPlayer/Sources/ChunkMediaPlayer.swift index 4a5e32c1a6..3b724d0a4c 100644 --- a/submodules/MediaPlayer/Sources/ChunkMediaPlayer.swift +++ b/submodules/MediaPlayer/Sources/ChunkMediaPlayer.swift @@ -230,45 +230,6 @@ private final class ChunkMediaPlayerContext { self.loadedState = ChunkMediaPlayerLoadedState() let queue = self.queue - let audioRendererContext = MediaPlayerAudioRenderer( - audioSession: .manager(self.audioSessionManager), - forAudioVideoMessage: self.isAudioVideoMessage, - playAndRecord: self.playAndRecord, - soundMuted: self.soundMuted, - ambient: self.ambient, - mixWithOthers: self.mixWithOthers, - forceAudioToSpeaker: self.forceAudioToSpeaker, - baseRate: self.baseRate, - audioLevelPipe: self.audioLevelPipe, - updatedRate: { [weak self] in - queue.async { - guard let self else { - return - } - self.tick() - } - }, - audioPaused: { [weak self] in - queue.async { - guard let self else { - return - } - if self.enableSound { - if self.continuePlayingWithoutSoundOnLostAudioSession { - self.continuePlayingWithoutSound(seek: .start) - } else { - self.pause(lostAudioSession: true, faded: false) - } - } else { - self.seek(timestamp: 0.0, action: .play, notify: true) - } - } - } - ) - self.audioRenderer = MediaPlayerAudioRendererContext(renderer: audioRendererContext) - - self.loadedState.controlTimebase = ChunkMediaPlayerControlTimebase(timebase: audioRendererContext.audioTimebase, isAudio: true) - self.videoRenderer.visibilityUpdated = { [weak self] value in assert(queue.isCurrent()) @@ -328,9 +289,6 @@ private final class ChunkMediaPlayerContext { return .noFrames }) - audioRendererContext.start() - self.tick() - let tickTimer = SwiftSignalKit.Timer(timeout: 1.0 / 25.0, repeat: true, completion: { [weak self] in self?.tick() }, queue: self.queue) @@ -344,6 +302,8 @@ private final class ChunkMediaPlayerContext { self.partsState = partsState self.tick() }) + + self.tick() } deinit { @@ -457,6 +417,7 @@ private final class ChunkMediaPlayerContext { } else { timestamp = 0.0 } + let _ = timestamp self.seek(timestamp: timestamp, action: .play, notify: true) } else { if case let .timecode(time) = seek { @@ -598,12 +559,31 @@ private final class ChunkMediaPlayerContext { } timestamp = max(0.0, timestamp) - if let firstPart = self.loadedState.partStates.first, let mediaBuffers = firstPart.mediaBuffers, mediaBuffers.videoBuffer != nil, mediaBuffers.audioBuffer == nil { - // No audio + var disableAudio = false + if !self.enableSound { + disableAudio = true + } + var hasAudio = false + if let firstPart = self.loadedState.partStates.first, let mediaBuffers = firstPart.mediaBuffers, mediaBuffers.videoBuffer != nil { + if mediaBuffers.audioBuffer != nil { + hasAudio = true + } else { + disableAudio = true + } + } + + if disableAudio { + var resetTimebase = false if self.audioRenderer != nil { self.audioRenderer?.renderer.stop() self.audioRenderer = nil - + resetTimebase = true + } + if self.loadedState.controlTimebase == nil { + resetTimebase = true + } + + if resetTimebase { var timebase: CMTimebase? CMTimebaseCreateWithSourceClock(allocator: nil, sourceClock: CMClockGetHostTimeClock(), timebaseOut: &timebase) let controlTimebase = ChunkMediaPlayerControlTimebase(timebase: timebase!, isAudio: false) @@ -611,6 +591,50 @@ private final class ChunkMediaPlayerContext { self.loadedState.controlTimebase = controlTimebase } + } else if hasAudio { + if self.audioRenderer == nil { + let queue = self.queue + let audioRendererContext = MediaPlayerAudioRenderer( + audioSession: .manager(self.audioSessionManager), + forAudioVideoMessage: self.isAudioVideoMessage, + playAndRecord: self.playAndRecord, + soundMuted: self.soundMuted, + ambient: self.ambient, + mixWithOthers: self.mixWithOthers, + forceAudioToSpeaker: self.forceAudioToSpeaker, + baseRate: self.baseRate, + audioLevelPipe: self.audioLevelPipe, + updatedRate: { [weak self] in + queue.async { + guard let self else { + return + } + self.tick() + } + }, + audioPaused: { [weak self] in + queue.async { + guard let self else { + return + } + if self.enableSound { + if self.continuePlayingWithoutSoundOnLostAudioSession { + self.continuePlayingWithoutSound(seek: .start) + } else { + self.pause(lostAudioSession: true, faded: false) + } + } else { + self.seek(timestamp: 0.0, action: .play, notify: true) + } + } + } + ) + self.audioRenderer = MediaPlayerAudioRendererContext(renderer: audioRendererContext) + + self.loadedState.controlTimebase = ChunkMediaPlayerControlTimebase(timebase: audioRendererContext.audioTimebase, isAudio: true) + audioRendererContext.flushBuffers(at: CMTimeMakeWithSeconds(timestamp, preferredTimescale: 44000), completion: {}) + audioRendererContext.start() + } } //print("Timestamp: \(timestamp)") diff --git a/submodules/PassportUI/Sources/SecureIdDocumentGalleryController.swift b/submodules/PassportUI/Sources/SecureIdDocumentGalleryController.swift index 324a8638f5..7a1d041ca9 100644 --- a/submodules/PassportUI/Sources/SecureIdDocumentGalleryController.swift +++ b/submodules/PassportUI/Sources/SecureIdDocumentGalleryController.swift @@ -187,7 +187,7 @@ class SecureIdDocumentGalleryController: ViewController, StandalonePresentableCo }, controller: { [weak self] in return self }) - self.displayNode = GalleryControllerNode(controllerInteraction: controllerInteraction) + self.displayNode = GalleryControllerNode(context: self.context, controllerInteraction: controllerInteraction) self.displayNodeDidLoad() self.galleryNode.statusBar = self.statusBar diff --git a/submodules/PeerAvatarGalleryUI/Sources/AvatarGalleryController.swift b/submodules/PeerAvatarGalleryUI/Sources/AvatarGalleryController.swift index 10b3b1dd33..83225a8c54 100644 --- a/submodules/PeerAvatarGalleryUI/Sources/AvatarGalleryController.swift +++ b/submodules/PeerAvatarGalleryUI/Sources/AvatarGalleryController.swift @@ -633,7 +633,7 @@ public class AvatarGalleryController: ViewController, StandalonePresentableContr }, controller: { [weak self] in return self }) - self.displayNode = GalleryControllerNode(controllerInteraction: controllerInteraction) + self.displayNode = GalleryControllerNode(context: self.context, controllerInteraction: controllerInteraction) self.displayNodeDidLoad() self.galleryNode.pager.updateOnReplacement = true diff --git a/submodules/TelegramBaseController/Sources/TelegramBaseController.swift b/submodules/TelegramBaseController/Sources/TelegramBaseController.swift index 2da6f4581e..3cddbb8300 100644 --- a/submodules/TelegramBaseController/Sources/TelegramBaseController.swift +++ b/submodules/TelegramBaseController/Sources/TelegramBaseController.swift @@ -472,8 +472,8 @@ open class TelegramBaseController: ViewController, KeyShortcutResponder { let controller = UndoOverlayController( presentationData: presentationData, content: .universal( - animation: "anim_profileunmute", - scale: 0.075, + animation: "anim_set_notification", + scale: 0.06, colors: [ "Middle.Group 1.Fill 1": UIColor.white, "Top.Group 1.Fill 1": UIColor.white, diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift index 6518e6bfc4..876b9f08ef 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift @@ -796,6 +796,8 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr return { [weak self] context, presentationData, dateTimeFormat, message, associatedData, attributes, media, mediaIndex, dateAndStatus, automaticDownload, peerType, peerId, sizeCalculation, layoutConstants, contentMode, presentationContext in let _ = peerType + let useInlineHLS = "".isEmpty + var nativeSize: CGSize let isSecretMedia = message.containsSecretMedia @@ -1270,7 +1272,9 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr var passFile = true if NativeVideoContent.isHLSVideo(file: file), let minimizedQualityFile = HLSVideoContent.minimizedHLSQuality(file: .message(message: MessageReference(message), media: file)) { - file = minimizedQualityFile.file.media + if !useInlineHLS { + file = minimizedQualityFile.file.media + } if hlsInlinePlaybackRange == nil { passFile = false } @@ -1395,7 +1399,9 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr var passFile = true if NativeVideoContent.isHLSVideo(file: file), let minimizedQualityFile = HLSVideoContent.minimizedHLSQuality(file: .message(message: MessageReference(message), media: file)) { - file = minimizedQualityFile.file.media + if !useInlineHLS { + file = minimizedQualityFile.file.media + } if hlsInlinePlaybackRange == nil { passFile = false } @@ -1777,27 +1783,38 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr let loopVideo = updatedVideoFile.isAnimated let videoContent: UniversalVideoContent - videoContent = NativeVideoContent( - id: .message(message.stableId, updatedVideoFile.fileId), - userLocation: .peer(message.id.peerId), - fileReference: .message(message: MessageReference(message), media: updatedVideoFile), - limitedFileRange: hlsInlinePlaybackRange, - streamVideo: streamVideo ? .conservative : .none, - loopVideo: loopVideo, - enableSound: false, - fetchAutomatically: false, - onlyFullSizeThumbnail: (onlyFullSizeVideoThumbnail ?? false), - autoFetchFullSizeThumbnail: true, - continuePlayingWithoutSoundOnLostAudioSession: isInlinePlayableVideo, - placeholderColor: emptyColor, - captureProtected: message.isCopyProtected() || isExtendedMedia, - storeAfterDownload: { [weak context] in - guard let context, let peerId else { - return + if useInlineHLS && NativeVideoContent.isHLSVideo(file: updatedVideoFile) { + videoContent = HLSVideoContent( + id: .message(message.stableId, updatedVideoFile.fileId), + userLocation: .peer(message.id.peerId), + fileReference: .message(message: MessageReference(message), media: updatedVideoFile), + loopVideo: loopVideo, + enableSound: false, + fetchAutomatically: false + ) + } else { + videoContent = NativeVideoContent( + id: .message(message.stableId, updatedVideoFile.fileId), + userLocation: .peer(message.id.peerId), + fileReference: .message(message: MessageReference(message), media: updatedVideoFile), + limitedFileRange: hlsInlinePlaybackRange, + streamVideo: streamVideo ? .conservative : .none, + loopVideo: loopVideo, + enableSound: false, + fetchAutomatically: false, + onlyFullSizeThumbnail: (onlyFullSizeVideoThumbnail ?? false), + autoFetchFullSizeThumbnail: true, + continuePlayingWithoutSoundOnLostAudioSession: isInlinePlayableVideo, + placeholderColor: emptyColor, + captureProtected: message.isCopyProtected() || isExtendedMedia, + storeAfterDownload: { [weak context] in + guard let context, let peerId else { + return + } + let _ = storeDownloadedMedia(storeManager: context.downloadedMediaStoreManager, media: .message(message: MessageReference(message), media: updatedVideoFile), peerId: peerId).startStandalone() } - let _ = storeDownloadedMedia(storeManager: context.downloadedMediaStoreManager, media: .message(message: MessageReference(message), media: updatedVideoFile), peerId: peerId).startStandalone() - } - ) + ) + } let videoNode = UniversalVideoNode(accountId: context.account.id, postbox: context.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: decoration, content: videoContent, priority: .embedded) videoNode.isUserInteractionEnabled = false videoNode.ownsContentNodeUpdated = { [weak self] owns in diff --git a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift index 6354ffbb83..78a0fbbf98 100644 --- a/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift +++ b/submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift @@ -8159,7 +8159,7 @@ final class PeerInfoScreenNode: ViewControllerTracingNode, PeerInfoScreenNodePro canCreateStream = true } case let channel as TelegramChannel: - if channel.flags.contains(.isCreator) { + if channel.hasPermission(.manageCalls) { canCreateStream = true credentialsPromise = Promise() credentialsPromise?.set(context.engine.calls.getGroupCallStreamCredentials(peerId: peerId, revokePreviousCredentials: false) |> `catch` { _ -> Signal in return .never() }) diff --git a/submodules/TelegramUI/Components/Settings/WallpaperGalleryScreen/Sources/WallpaperGalleryController.swift b/submodules/TelegramUI/Components/Settings/WallpaperGalleryScreen/Sources/WallpaperGalleryController.swift index 18a158a3d4..ab217d29a0 100644 --- a/submodules/TelegramUI/Components/Settings/WallpaperGalleryScreen/Sources/WallpaperGalleryController.swift +++ b/submodules/TelegramUI/Components/Settings/WallpaperGalleryScreen/Sources/WallpaperGalleryController.swift @@ -446,7 +446,7 @@ public class WallpaperGalleryController: ViewController { }, controller: { [weak self] in return self }) - self.displayNode = WallpaperGalleryControllerNode(controllerInteraction: controllerInteraction, pageGap: 0.0, disableTapNavigation: true) + self.displayNode = WallpaperGalleryControllerNode(context: self.context, controllerInteraction: controllerInteraction, pageGap: 0.0, disableTapNavigation: true) self.displayNodeDidLoad() (self.displayNode as? WallpaperGalleryControllerNode)?.nativeStatusBar = self.statusBar diff --git a/submodules/TelegramUI/Resources/Animations/anim_set_notification.tgs b/submodules/TelegramUI/Resources/Animations/anim_set_notification.tgs new file mode 100644 index 0000000000000000000000000000000000000000..5c98fff33f70dc2f632fd41277c58b2329f0b89a GIT binary patch literal 4179 zcmV-Z5UlSXiwFn~0kISS16V;+E^2dcZUF6E+iu)O68#lno=Kwb7r!M)HZR8RVzU=4 z1U+b-ajdm2#%PjkVEEtnoa!crQr@+Z&yFAo~?Z6ySQpr zH|y=?>e<`X_b7XQx7}W?|8#Y|zCZio>oe8q&M4GDg%v(tmyhqt$Myw3-!-e3o7JX>xggzuw-jo}FJb ztLw|3*Bk!+cKG`07M~g;{=9l-Ye#?n$MffBU;gE*f1{iGjePz3p6j^dk4tIyy0rcu zzSWrLX7L+^Z{AG4IX7N)$~7jaE}KSOl$z$92x45(s|Nr23LN9UR?wxw+tn2d@a4Jc zTnt^oD^+5Yz z^sI+idWiELtk;L;5W}nwUFF|uGw&uI>SR6-QzxSJgS(jZU|pR>`p_PnJ|K(-caZ87 ze6NAt4?A?R02+IHkFA$3^=KebeHN<8rn}tPWSiE9F7UXc|LxsyGVsUM=$MR0@Czfv z@c?xz0AWgF0OLE8^CJcbW@!ko@^}zk&!&x?RTxDp{6f@u@Gx;nQsW^^)d;V<7i-LvdjIP3&AM1(!sY7w4N&rGTXg-l;Hi9Z|7ul-=rQvb9t&x7e%`|T#Q^1n;%S`U zb8Wj|Emy?vLQahajd6*8<2Mzl;TO{VIgv6rso>@NU0dBL*qGM1&Srk66Liazra!W& zNu9yOT8*9Z-m!TQ!;M}n4w7aGls?_ zBv6xl!g{J0Lh@WQj-xfQX5DGaMSF@t7cpc*!Q|M*Y>tQl25LzqVwiwT+EWV96$rUY z+Hw&Fu%rj2z?MVreXM()Oq}Wj5KJm$sjzDcrBGgEY=g)+c1GK=Qh2C~s6g&i&{Zj5 zF3<~fF9cBv;A~8#QkK1IHyQD%h$QePe8C@M1Kw7ZGzYdaM~Z%$f(p`z{sTM?cn;g$FGsk|Ic=89*dc z&qq-V2LRkx3__*(d=X#-*}^;jdbxddrs;y+;;%2h`ts|uf39C_?>1-O5_!+svu`$c zKfFPOR{-0Wm)G}ekrE;I<@HLso}hVCcy}4b^?I~VU43D$y7J>X9k_kh%hUO0bNS}g z)eB6Bbr$EdrEQqGQ9I9Q!AdQ=O;fv6E7(K6TR6PL$WC7`HKJVZFPFaY{l@%#b9sCJ z@@{jp;+{#7?1V_?_Ki3YFJxVV1grI15Z$32{4K0$pdkP$;7L;D5aIlj?X(6*z2F28 zK7$4ME+#$H8~?;PDzu{S1E*7=DFDlL zgme>ullEXq0{%wVX>CMkv|G9X^i>-UnK;-s&9&V zCBhGC5f%p4*(M-Vs3=s_?-vu17%g=ukEKo=wA?*oiz$Io0C+|NKwjQHF*aeMM5duy zs65voC;>HY+Thbcv&XPx=3t}D9{H|IFAaL ztnnk^!+hgN1Bs#vMT@*65}~^TN@O}Ld7>+cCqUq454>6sMi_7m6I2=$iI$&?)&>Gq z(ah+rOhdSjLwyXANqm=Qu{dVCH@TfIVFcCJ9CRrY0YT3MW!&;yE6Zc+r5GN?5)LnS5d z<N9 z-`5;rk}6D`XE(ZvNlKg&$0HVt^^7`?OEmRfr{WG4i?vXKy@t<_(4Q531jYB3m;@`8 z#i~i5394gw%qqS>6qMMg$YZTOkJ>?{X`$V&@1ca-5&WQG-1IhU(Xc&zTJ#{ESkDvd zIjQrty;;p&7Pa$b*2^A=*>_e#*f}^i!ttw9QN56>n=?-HetDko#kT7WCd!J7^Ss}_ z&q=h0Jt+D~KTWUDdzYQ*nh+ZsxIenF{U{wiSmTBxAR4LOeN;9lA-XnK;H|+g^Ykq(1Vp27M4rA7N*My#fGJHzG!6fX&(@pV^iQ?^S&zD1raSrdOv4Kc?$mi-YvF08vM1Nw#D|q2i~5; zvDdqR7afOaXHJbS!M3;up?3vB<#>5sC*}eN`wiN?j(09e?(VGmSin*XO@C-V7NBX6j95l((oVK?B;kw0 zSuXdL__Ff}D4`e%yC@+<3)_z!fY)9|V0a^rOMqrse05tRN+N$6N%-n6RcSkHD+7iJ zCM2DjG63TpG2WLPwO#m6xrs{-H8i{o?@jlD`bHUw*(APR{4KO-_qrYj?|d=(B4d~g z&!7$Ty@pXz=P=gt<7BEjC(8+z1HIZukPy040EDQ z^}(H#cHr=3paY1bwL5j=o(3}yj2SU`@c>C{X&p@iF6v57!D5Scuj@%rOXZOcL;I9w zD8&o+VaUlO21zsx@Cg=yam>GJV=4z?*-z! zPg|aF^*F9R(VpKs?QutGk9!d9xp-uPuAL_6{_FC`_5Io3j%Ru=C+5C4*V{1}5B{A2 zulMF?wzq~M^^6iTARY6u&D>=%{|ae!$<}N`{x$)99V%_%Zw2{h_|@Y|2?+BJRZt9! zgfIxi*g0Cj&D^*?(%TtWxmaDFu{R|S7w>#5V4>Vv0mURKCiX^>;0Ca>5aU7+{{vU% z)Y8f%md=$Wv7+$IG@vT=CiJd=IP5BIvN*Jl}IKQIfWrg5>rYfJAx%4No*IOWNQgo zua#WgQ=#gzy};bD6n=#Ir=%sMO430i>96q$e3!CQ+SDc)lG6<%t3{ejY)N$?6H$1E zYJrWuw@sRHZeC5I#FtPxJgiUzQLj~LUKr}s2kwYnH~_*%7Nu>W+;oVd%n%rvc$+U* zlwq_aw&)w6lCzRgYigh%Ho!NMz`A;?wuGgO0lkniAQyp&LpVMx^@t%BFLkH4=B9$U zOP!7~go}@P=fnG7WYEhA^w%&aAdiqB10?NEIYR$R1wQfPViGZFZ%#Qx z&%ZK+qh$>)KInB1J|57+W3PLtbp!kb`+y6^PxWOFJpq%4tohUo4Jvav%bPOJ;n(mf zrOb4I-G#Vio^UGWf3|uL%RKvY66fe zFXcHmUGVZekM<+wV^*r4iO>`gVTQU?85&9ehF!*4<_3grW)jpv9?4`POBAYYv^+@1 zbPVU}vrv+U3qdpKR3zp^1xlSzO9E44gy2>Y8h{M@MgNZ#;gJlYK?jZGDckboE3893 zYjl|cGlZ4TV;u|&r`KmK?@22&mI+HkIabnVoa>;|bNWpxPYcCNB-u?Yof-7RNhdG( z;M+5p`<9`czKDy-O1@T!eF@(>76PAGmHF@;7Eb!L`)Bx&C-p~#wNv^lPw79uMf%Sv dUU~68hXLQ;Ty9>M*FIjn`#*k^eJ-F<000F6`d{"use strict";function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var e,s,i,r,n,a={exports:{}};e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a.exports=n={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=n.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=s.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(c)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(i,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};var o=a.exports;function l(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,i)}return s}function h(t){for(var e=1;e`):E}(e)}))}const A=S,R=/^(\d+)x(\d+)$/,b=/(.+?)=(".*?"|.*?)(?:,|$)/g;class k{constructor(t){"string"==typeof t&&(t=k.parseAttrList(t)),u(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const s=new Uint8Array(e.length/2);for(let t=0;tNumber.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=R.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const s={};for(b.lastIndex=0;null!==(e=b.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));s[e[1].trim()]=t}return s}}function w(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class D{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){A.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=u(new k({}),s,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);f(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(f(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&f(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class I{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var _="audio",C="video",x="audiovideo";class P{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[_]:null,[C]:null,[x]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=o.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class M extends P{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new I,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!f(this.programDateTime))return null;const t=f(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[_]=null,t[C]=null,t[x]=null}}class F extends P{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new I,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class O{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&f(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function N(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function U(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=N(r)):s=function(t){const e=B(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}function B(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const $="undefined"!=typeof self?self:void 0;var G={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},K="org.w3.clearkey",H="com.apple.streamingkeydelivery",V="com.microsoft.playready",Y="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function W(t){switch(t){case H:return G.FAIRPLAY;case V:return G.PLAYREADY;case Y:return G.WIDEVINE;case K:return G.CLEARKEY}}var j="1077efecc0b24d02ace33c1e52e2fb4b",q="e2719d58a985b3c9781ab030af78d30e",X="9a04f07998404286ab92e65be0885f95",z="edef8ba979d64acea3c827dcd51d21ed";function Q(t){return t===z?G.WIDEVINE:t===X?G.PLAYREADY:t===j||t===q?G.CLEARKEY:void 0}function J(t){switch(t){case G.FAIRPLAY:return H;case G.PLAYREADY:return V;case G.WIDEVINE:return Y;case G.CLEARKEY:return K}}function Z(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[G.FAIRPLAY,G.WIDEVINE,G.PLAYREADY,G.CLEARKEY].filter((t=>!!e[t])):[];return!i[G.WIDEVINE]&&s&&i.push(G.WIDEVINE),i}const tt=null!=$&&null!=(et=$.navigator)&&et.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var et;function st(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const it=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,rt=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,nt=(t,e)=>{const s=e;let i=0;for(;it(t,e);){i+=10;i+=at(t,e+6),rt(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(s,s+i)},at=(t,e)=>{let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s},ot=(t,e)=>it(t,e)&&at(t,e+6)+10<=t.length-e,lt=t=>{const e=ct(t);for(let t=0;tt&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,dt=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=at(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},ct=t=>{let e=0;const s=[];for(;it(t,e);){const i=at(t,e+6);e+=10;const r=e+i;for(;e+8"PRIV"===t.type?ft(t):"W"===t.type[0]?mt(t):gt(t),ft=t=>{if(t.size<2)return;const e=vt(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},gt=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=vt(t.data.subarray(e),!0);e+=s.length+1;const i=vt(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=vt(t.data.subarray(1));return{key:t.type,data:e}},mt=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=vt(t.data.subarray(e),!0);e+=s.length+1;const i=vt(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=vt(t.data);return{key:t.type,data:e}},pt=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}},vt=(t,e=!1)=>{const s=Et();if(s){const i=s.decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let r,n,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=t[l++],o+=String.fromCharCode((31&r)<<6|63&n);break;case 14:n=t[l++],a=t[l++],o+=String.fromCharCode((15&r)<<12|(63&n)<<6|63&a)}}return o};let yt;function Et(){if(!navigator.userAgent.includes("PlayStation 4"))return yt||void 0===self.TextDecoder||(yt=new self.TextDecoder("utf-8")),yt}const Tt=function(t){let e="";for(let s=0;s>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function _t(t,e){const s=[];if(!e.length)return s;const i=t.byteLength;for(let r=0;r1?r+n:i;if(Rt(t.subarray(r+4,r+8))===e[0])if(1===e.length)s.push(t.subarray(r+8,a));else{const i=_t(t.subarray(r+8,a),e.slice(1));i.length&&Lt.apply(s,i)}r=a}return s}function Ct(t){const e=[],s=t[0];let i=8;const r=kt(t,i);i+=4;let n=0,a=0;0===s?(n=kt(t,i),a=kt(t,i+4),i+=8):(n=wt(t,i),a=wt(t,i+8),i+=16),i+=2;let o=t.length+a;const l=bt(t,i);i+=2;for(let s=0;s>>31)return A.warn("SIDX has hierarchical references (not supported)"),null;const l=kt(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function xt(t){const e=[],s=_t(t,["moov","trak"]);for(let t=0;t{const s=kt(t,4),i=e[s];i&&(i.default={duration:kt(t,12),flags:kt(t,20)})})),e}function Pt(t){const e=t.subarray(8),s=e.subarray(86),i=Rt(e.subarray(4,8));let r=i;const n="enca"===i||"encv"===i;if(n){const t=_t(e,[i])[0];_t(t.subarray("enca"===i?28:78),["sinf"]).forEach((t=>{const e=_t(t,["schm"])[0];if(e){const s=Rt(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=_t(t,["frma"])[0];e&&(r=Rt(e))}}}))}switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=_t(s,["avcC"])[0];r+="."+Ft(t[1])+Ft(t[2])+Ft(t[3]);break}case"mp4a":{const t=_t(e,[i])[0],s=_t(t.subarray(28),["esds"])[0];if(s&&s.length>12){let t=4;if(3!==s[t++])break;t=Mt(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=Mt(s,t);const i=s[t++];if(64!==i)break;if(r+="."+Ft(i),t+=12,5!==s[t++])break;t=Mt(s,t);const n=s[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&s[t])>>5)),r+="."+a}break}case"hvc1":case"hev1":{const t=_t(s,["hvcC"])[0],e=t[1],i=["","A","B","C"][e>>6],n=31&e,a=kt(t,2),o=(32&e)>>5?"H":"L",l=t[12],h=t.subarray(6,12);r+="."+i+n,r+="."+a.toString(16).toUpperCase(),r+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}r+=d;break}case"dvh1":case"dvhe":{const t=_t(s,["dvcC"])[0],e=t[2]>>1&127,i=t[2]<<5&32|t[3]>>3&31;r+="."+Ot(e)+"."+Ot(i);break}case"vp09":{const t=_t(s,["vpcC"])[0],e=t[4],i=t[5],n=t[6]>>4&15;r+="."+Ot(e)+"."+Ot(i)+"."+Ot(n);break}case"av01":{const t=_t(s,["av1C"])[0],e=t[1]>>>5,i=31&t[1],n=t[2]>>>7?"H":"M",a=(64&t[2])>>6,o=(32&t[2])>>5,l=2===e&&a?o?12:10:a?10:8,h=(16&t[2])>>4,d=(8&t[2])>>3,c=(4&t[2])>>2,u=3&t[2],f=1,g=1,m=1,p=0;r+="."+e+"."+Ot(i)+n+"."+Ot(l)+"."+h+"."+d+c+u+"."+Ot(f)+"."+Ot(g)+"."+Ot(m)+"."+p;break}}return{codec:r,encrypted:n}}function Mt(t,e){const s=e+5;for(;128&t[e++]&&e{const l=o.byteOffset-8;_t(o,["traf"]).map((o=>{const h=_t(o,["tfdt"]).map((t=>{const e=t[0];let s=kt(t,4);return 1===e&&(s*=Math.pow(2,32),s+=kt(t,8)),s/r}))[0];return void 0!==h&&(t=h),_t(o,["tfhd"]).map((h=>{const d=kt(h,4),c=16777215&kt(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=kt(h,p),p+=4),f&&(g=kt(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),s=e<0?t:t.substring(0,e);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(e.codec)),_t(o,["trun"]).map((n=>{const o=n[0],h=16777215&kt(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const L=kt(n,4);let A=8;d&&(c=kt(n,A),A+=4),f&&(A+=4);let R=c+l;for(let l=0;l>1&63;return 39===t||40===t}return 6===(31&e)}function Kt(t,e,s,i){const r=Ht(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(ot){A.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=bt(r,e);if(e+=2,49===t){const t=kt(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=Tt(new Uint8Array(n,s+12,16)),o=t.getUint32(28);let l=null,h=null;if(0===r){if(e-32>8*(15-s)&255;return e}(t);return new jt(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=U(this.uri);if(e)switch(this.keyFormat){case Y:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case V:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Vt(t,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(s)),r=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=N(t).subarray(0,16);!function(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=Wt[this.uri];if(!t){const e=Object.keys(Wt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),Wt[this.uri]=t}this.keyId=t}return this}}const qt=/\{\$([a-zA-Z0-9-_]+)\}/g;function Xt(t){return qt.test(t)}function zt(t,e,s){if(null!==t.variableList||t.hasVariableRefs)for(let i=s.length;i--;){const r=s[i],n=e[r];n&&(e[r]=Qt(t,n))}}function Qt(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(qt,(e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r}))}return e}function Jt(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Zt(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function te(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const ee={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function se(t,e,s=!0){return!t.split(",").some((t=>!ie(t,e,s)))}function ie(t,e,s=!0){var i;const r=te(s);return null!=(i=null==r?void 0:r.isTypeSupported(re(t,e)))&&i}function re(t,e){return`${e}/mp4;codecs="${t}"`}function ne(t){if(t){const e=t.substring(0,4);return ee.video[e]}return 2}function ae(t){return t.split(",").reduce(((t,e)=>{const s=ee.video[e];return s?(2*s+t)/(t?3:2):(ee.audio[e]+t)/(t?2:1)}),0)}const oe={};const le=/flac|opus/i;function he(t,e=!0){return t.replace(le,(t=>function(t,e=!0){if(oe[t])return oe[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let i=0;i0&&i.length({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(ue.lastIndex=0;null!==(i=ue.exec(t));){const t=new k(i[1]),n=t.TYPE;if(n){const i=a[n],l=r[n]||[];r[n]=l,zt(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?pe.resolve(t.URI,e):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const t=pe.findGroup(i,g.groupId)||i[0];Te(g,t,"audioCodec"),Te(g,t,"textCodec")}l.push(g)}}return r}static parseLevelPlaylist(t,e,s,i,r,n){const a=new O(e),o=a.fragments;let l,h,d,c=null,g=0,m=0,p=0,v=0,y=null,E=new M(i,e),T=-1,S=!1,L=null;for(ge.lastIndex=0,a.m3u8=t,a.hasVariableRefs=Xt(t);null!==(l=ge.exec(t));){S&&(S=!1,E=new M(i,e),E.start=p,E.sn=g,E.cc=v,E.level=s,c&&(E.initSegment=c,E.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,L&&(E.setByteRange(L),L=null)));const t=l[1];if(t){E.duration=parseFloat(t);const e=(" "+l[2]).slice(1);E.title=e||null,E.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(f(E.duration)){E.start=p,d&&Ae(E,d,a),E.sn=g,E.level=s,E.cc=v,o.push(E);const t=(" "+l[3]).slice(1);E.relurl=Qt(a,t),Se(E,y),y=E,p+=E.duration,g++,m=0,S=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);y?E.setByteRange(t,y):E.setByteRange(t)}else if(l[5])E.rawProgramDateTime=(" "+l[5]).slice(1),E.tagList.push(["PROGRAM-DATE-TIME",E.rawProgramDateTime]),-1===T&&(T=o.length);else{if(l=l[0].match(me),!l){A.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new k(r);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const s=m>0?t[t.length-1]:void 0,i=m++,n=new k(r);zt(a,n,["BYTERANGE","URI"]);const o=new F(n,E,e,i,s);t.push(o),E.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new k(r);zt(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new k(r);zt(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:A.warn(`line parsed but not handled: ${l}`)}}}y&&!y.relurl?(o.pop(),p-=y.duration,a.partList&&(a.fragmentHint=y)):a.partList&&(Se(E,y),E.cc=v,a.fragmentHint=E,d&&Ae(E,d,a));const R=o.length,b=o[0],w=o[R-1];if(p+=a.skippedSegments*a.targetduration,p>0&&R&&w){a.averagetargetduration=p/R;const t=w.sn;a.endSN="initSegment"!==t?t:0,a.live||(w.endList=!0),b&&(a.startCC=b.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(p+=a.fragmentHint.duration),a.totalduration=p,a.endCC=v,T>0&&function(t,e){let s=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(o,T),a}}function ve(t,e,s){var i,r;const n=new k(t);zt(s,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&A.error(`Invalid IV: ${n.IV}`);const c=o?pe.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new jt(a,c,d,u,l)}function ye(t){const e=new k(t).decimalFloatingPoint("TIME-OFFSET");return f(e)?e:null}function Ee(t,e){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const i=s.filter((e=>function(t,e){const s=ee[e];return!!s&&!!s[t.slice(0,4)]}(e,t)));i.length&&(e[`${t}Codec`]=i.join(","),s=s.filter((t=>-1===i.indexOf(t))))})),e.unknownCodecs=s}function Te(t,e,s){const i=e[s];i&&(t[s]=i)}function Se(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),f(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Le(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function Ae(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||i.push(t)}var Re="manifest",be="level",ke="audioTrack",we="subtitleTrack",De="main",Ie="audio",_e="subtitle";function Ce(t){const{type:e}=t;switch(e){case ke:return Ie;case we:return _e;default:return De}}function xe(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class Pe{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.LEVEL_LOADING,this.onLevelLoading,this),t.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.LEVEL_LOADING,this.onLevelLoading,this),t.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Re,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:be,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:ke,url:r,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:we,url:r,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=r.context;if(e&&e.url===t.url&&e.level===t.level)return void A.trace("[playlist-loader]: playlist request ongoing");A.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===Re?s.manifestLoadPolicy.default:u({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),f(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===be&&null!==t.level?e=this.hls.levels[t.level].details:t.type===ke&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===we&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);i=u({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),pe.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),i||null,e)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};r.load(t,a,o)}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=xe(t,s),o=pe.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=pe.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((t=>!t.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(A.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new k({}),bitrate:0,url:""}))}r.trigger(p.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:v,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=xe(t,s),d=f(o)?o:f(a)?a:0,c=Ce(s),u=pe.parseLevelPlaylist(t.data,h,d,c,0,this.variableList);if(l===Re){const t={attrs:new k({}),bitrate:0,details:u,name:"",url:h};n.trigger(p.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(p.ERROR,{type:v.NETWORK_ERROR,details:y.MANIFEST_PARSING_ERROR,fatal:e.type===Re,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===be?n+=`: ${t.level} id: ${t.id}`:t.type!==ke&&t.type!==we||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);A.warn(`[playlist-loader]: ${n}`);let o=y.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case Re:o=s?y.MANIFEST_LOAD_TIMEOUT:y.MANIFEST_LOAD_ERROR,l=!0;break;case be:o=s?y.LEVEL_LOAD_TIMEOUT:y.LEVEL_LOAD_ERROR,l=!1;break;case ke:o=s?y.AUDIO_TRACK_LOAD_TIMEOUT:y.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case we:o=s?y.SUBTITLE_TRACK_LOAD_TIMEOUT:y.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const c={type:v.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:r};if(i){const s=(null==e?void 0:e.url)||t.url;c.response=h({url:s,data:void 0},i)}this.hls.trigger(p.ERROR,c)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:c}=i,u=xe(e,i),f=Ce(i),g="number"==typeof i.level&&f===De?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(p.ERROR,{type:v.NETWORK_ERROR,details:y.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:t,reason:t.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m)a.trigger(p.ERROR,{type:v.NETWORK_ERROR,details:y.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Re:case be:a.trigger(p.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:c});break;case ke:a.trigger(p.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c});break;case we:a.trigger(p.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c})}}}function Me(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function Fe(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){A.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){A.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function Oe(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}function Ne(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(et[s].endTime)return-1;let i=0,r=s;for(;i<=r;){const n=Math.floor((r+i)/2);if(et[n].startTime&&i-1)for(let n=r,a=t.length;n=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e{const t=Ke();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Ye(t,e){return t.getTime()/1e3-e}class We{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(p.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(Oe(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;eVe&&(i=Ve);i-s<=0&&(i=s+.25);for(let t=0;tt.type===Be&&o:"video"===i?t=>t.type===Ge&&a:t=>t.type===Be&&o||t.type===Ge&&a,Ne(r,e,s,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:i}=this,{dateRanges:r}=e,n=Object.keys(r);if(i){const t=Object.keys(s).filter((t=>!n.includes(t)));for(let e=t.length;e--;){const r=t[e];Object.keys(s[r].cues).forEach((t=>{i.removeCue(s[r].cues[t])})),delete s[r]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!f(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Ke();for(let t=0;t{if(e!==i.id){const s=r[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDatethis.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:s,targetduration:i}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,s=this.levelDetails;if(null===t||null===e||null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(p.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(p.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var s;e.details===y.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&A.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,s))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const qe=["NONE","TYPE-0","TYPE-1",null];const Xe=["SDR","PQ","HLG"];var ze="",Qe="YES",Je="v2";function Ze(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i!!t)).map((t=>t.substring(0,4))).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return ss(this._audioGroups,t)}hasSubtitleGroup(t){return ss(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function ss(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function is(t,e){const s=e.startPTS;if(f(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&(i.duration=r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function rs(t,e,s,i,r,n){i-s<=0&&(A.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let a=s,o=i;const l=e.startPTS,h=e.endPTS;if(f(l)){const t=Math.abs(l-s);f(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(s,l),s=Math.min(s,l),r=Math.min(r,e.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,e.endDTS)}const d=s-e.start;0!==e.start&&(e.start=s),e.duration=i-e.start,e.startPTS=s,e.maxStartPTS=a,e.startDTS=r,e.endPTS=i,e.minEndPTS=o,e.endDTS=n;const c=e.sn;if(!t||ct.endSN)return 0;let u;const g=c-t.startSN,m=t.fragments;for(m[g]=e,u=g;u>0;u--)is(m[u],m[u-1]);for(u=g;u=0;t--){const e=i[t].initSegment;if(e){s=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let r,n=0;if(function(t,e,s){const i=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=r;t<=n;t++){const r=l[a+t];let n=o[t];i&&!n&&t{t.relurl&&(n=t.cc-i.cc),f(t.startPTS)&&f(t.endPTS)&&(i.start=i.startPTS=t.startPTS,i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.duration=t.endPTS-t.startPTS,i.duration&&(r=i),e.PTSKnown=e.alignedSliding=!0),i.elementaryStreams=t.elementaryStreams,i.loader=t.loader,i.stats=t.stats,t.initSegment&&(i.initSegment=t.initSegment,s=t.initSegment)})),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)}))}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((t=>!t)),e.deltaUpdateFailed){A.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const i=u({},t);s&&s.forEach((t=>{delete i[t]}));return Object.keys(e).forEach((t=>{const s=new D(e[t].attr,i[t]);s.isValid?i[t]=s:A.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)})),i}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){A.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),r?rs(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):as(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function as(t,e){const s=e.startSN+e.skippedSegments-t.startSN,i=t.fragments;s<0||s>=i.length||os(e,i[s].start)}function os(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach((t=>{t.level=e}))}))}function cs(t){switch(t.details){case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_TIMEOUT:case y.LEVEL_LOAD_TIMEOUT:case y.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function us(t,e){const s=cs(e);return t.default[(s?"timeout":"error")+"Retry"]}function fs(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function gs(t){return h(h({},t),{errorRetry:null,timeoutRetry:null})}function ms(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}const ps=function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function vs(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[t.sn-e[0].sn+1]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===ys(s,i,n)||function(t,e,s){if(e&&0===e.start&&e.level0){const i=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=ps(e,ys.bind(null,s,i));return!a||a===t&&n?n:a}function ys(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function Es(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}var Ts=0,Ss=2,Ls=3,As=5,Rs=0,bs=1,ks=2;class ws{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=A.log.bind(A,`${e}:`),this.warn=A.warn.bind(A,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let r=-1;for(let s=0;s=0&&t>e.partTarget&&(a+=1)}const o=s&&Ze(s);return new ts(n,a>=0?a:void 0,o)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;if(i.advancedDateTime=Date.now()-a,i.live||null!=s&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&ns(s,i),!this.canLoad||!i.live)return;let a,o,l;if(i.canBlockReload&&i.endSN&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,n=i.endSN,h=i.lastPartIndex,d=r===n;-1!==h?(o=d?n+1:r,l=d?t?0:h:h+1):o=n+1;const c=i.age,u=c+i.ageHeader;let f=Math.min(u-i.partTarget,1.5*i.targetduration);if(f>0){if(s&&f>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${f} with playlist age: ${i.age}`),f=0;else{const t=Math.floor(f/i.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}i.tuneInGoal=f}if(a=this.getDeliveryDirectives(i,e.deliveryDirectives,o,l),t||!d)return void this.loadPlaylist(a)}else(i.canBlockReload||i.canSkipUntil)&&(a=this.getDeliveryDirectives(i,e.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=function(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments,r=4;if(i.length&&s*r>e){const t=1e3*i[i.length-1].duration;tthis.requestScheduled+c&&(this.requestScheduled=r.loading.start),void 0!==o&&i.canBlockReload?this.requestScheduled=r.loading.first+c-(1e3*i.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+cthis.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(t,e,s,i){let r=Ze(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=ze),new ts(s,i,r)}checkRetry(t){const e=t.details,s=cs(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===As||!i.resolved&&r===Ss);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=fs(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}}class Ds{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Is{constructor(t,e,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ds(t),this.fast_=new Ds(e),this.defaultTTFB_=i,this.ttfb_=new Ds(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new Ds(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new Ds(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new Ds(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const _s={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Cs={};function xs(t,e,s,i,r,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce(((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach((e=>{t[e]=(t[e]||0)+i.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!d&&f(h)&&Object.keys(d).some((t=>parseInt(t)>h))}function Ps(t,e,s){const i=t.videoCodec,r=t.audioCodec;if(!i||!r||!s)return Promise.resolve(_s);const n={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=i.split(",").map((t=>({type:"media-source",video:h(h({},n),{},{contentType:re(t,"video")})})));return r&&t.audioGroups&&t.audioGroups.forEach((t=>{var s;t&&(null==(s=e.groups[t])||s.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",s=parseFloat(t);f(s)&&s>2&&o.push.apply(o,r.split(",").map((t=>({type:"media-source",audio:{contentType:re(t,"audio"),channels:""+s}}))))}})))})),Promise.all(o.map((t=>{const e=function(t){const{audio:e,video:s}=t,i=s||e;if(i){const t=i.contentType.split('"')[1];if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${t}_${Math.ceil(s.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return Cs[e]||(Cs[e]=s.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:o,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:o,decodingInfoResults:[],error:t})))}function Ms(t,e){let s=!1,i=[];return t&&(s="SDR"!==t,i=[t]),e&&(i=e.allowedVideoRanges||Xe.slice(0),s=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i=s?i.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:s,allowedVideoRanges:i}}function Fs(t,e){A.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Os(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i-1===i.indexOf(t)))}(o,e.characteristics))&&(void 0===s||s(t,e))}function Us(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function Bs(t,e,s){for(let i=e;i;i--)if(s(t[i]))return i;for(let i=e+1;i1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var Gs="NOT_LOADED",Ks="APPENDING",Hs="PARTIAL",Vs="OK";class Ys{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(p.BUFFER_APPENDED,this.onBufferAppended,this),t.on(p.FRAG_BUFFERED,this.onFragBuffered,this),t.on(p.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(p.BUFFER_APPENDED,this.onBufferAppended,this),t.off(p.FRAG_BUFFERED,this.onFragBuffered,this),t.off(p.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const i=s[e];if(!i)break;const r=i.end;if(i.start<=t&&null!==r&&t<=r)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){const n=s[i[r]];if((null==n?void 0:n.body.type)===e&&n.buffered){const e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i){this.timeRanges&&(this.timeRanges[t]=e);const r=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const n=this.fragments[i];if(!n)return;if(r>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===s&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(n.body),s}))}))}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:i}=t;if(!e||"initSegment"===s.sn)return;const r=js(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;if(Object.keys(e).forEach((t=>{const r=s.elementaryStreams[t];if(!r)return;const o=e[t],l=a||!0===r.partial;n.range[t]=this.getBufferedTimes(s,i,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ws(n)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(n.body)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=s.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const s=js(t);let i=this.fragments[s];!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t=e&&o<=s){r.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(ne){const e=Math.max(n,i.start(t)),s=Math.min(a,i.end(t));s>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&Ws(h)&&(s=h.body.start-a,i=h.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=h.body,n=e)))})),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Ws(e))}getState(t){const e=js(t),s=this.fragments[e];return s?s.buffered?Ws(s)?Hs:Vs:Ks:Gs}isTimeBuffered(t,e,s){let i,r;for(let n=0;n=i&&e<=r)return!0;if(e<=i)return!1}return!1}onFragLoaded(t,e){const{frag:s,part:i}=e;if("initSegment"===s.sn||s.bitrateTest)return;const r=i?null:e,n=js(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r}=e;if("initSegment"===s.sn)return;const n=s.type;if(i){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(i)}this.timeRanges=r,Object.keys(r).forEach((t=>{const e=r[t];this.detectEvictedFragments(t,e,n,i)}))}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=js(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.startt&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(t){const e=js(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=s.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Ws(t){var e,s,i;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(i=t.range.audiovideo)?void 0:i.partial))}function js(t){return`${t.type}_${t.level}_${t.sn}`}const qs={length:0,start:()=>0,end:()=>0};class Xs{static isBuffered(t,e){try{if(t){const s=Xs.getBuffered(t);for(let t=0;t=s.start(t)&&e<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,s){try{if(t){const i=Xs.getBuffered(t),r=[];let n;for(n=0;nn&&(i[r-1].end=t[e].end):i.push(t[e])}else i.push(t[e])}else i=t;let r,n=0,a=e,o=e;for(let t=0;t=l&&es.startCC||t&&t.cc{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(ni(t));t.gap=!1}const l=this.loader=t.loader=r?new r(i):new n(i),d=ri(t),c=gs(i.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:si};t.stats=l.stats,l.load(d,u,{onSuccess:(e,s,i,r)=>{this.resetLoader(t,l);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,r,n)=>{this.resetLoader(t,l),o(new ai({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:h({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,l),o(new ai({type:v.NETWORK_ERROR,details:y.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,l),o(new ai({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:i,stats:e}))},onProgress:(s,i,r,n)=>{e&&e({frag:t,part:null,payload:r,networkDetails:n})}})}))}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(ni(t,e));const l=this.loader=t.loader=r?new r(i):new n(i),d=ri(t,e),c=gs(i.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:si};e.stats=l.stats,l.load(d,u,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new ai({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:h({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new ai({type:v.NETWORK_ERROR,details:y.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new ai({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:s}))}})}))}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function ri(t,e=null){const s=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(f(r)&&f(n)){var a;let e=r,s=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-r;t%16&&(s=n+(16-t%16)),0!==r&&(i.resetIV=!0,e=r-16)}i.rangeStart=e,i.rangeEnd=s}return i}function ni(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:v.MEDIA_ERROR,details:y.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new ai(i)}class ai extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class oi{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class li{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class hi{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new oi(this.subtle,new Uint8Array(s)).decrypt(t.buffer,e)})).catch((i=>(A.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,e,s))))}onWebCryptoError(t,e,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=st(t,0,s),this.remainderData=st(t,s)),e}logOnce(t){this.logEnabled&&(A.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ci=function(t){let e="";const s=t.length;for(let i=0;ia.end){const t=n>r;(n{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const s=this.state;this.fragContextChanged(t)?(s===mi||!this.fragCurrent&&s===yi)&&(this.fragmentTracker.removeFragment(t),this.state=fi):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(p.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((e=>{this.state!==ui&&this.state!==Si&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===Ks){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===Hs&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(p.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:s}=this,{payload:i}=e,r=t.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const r=self.performance.now();return s.trigger(p.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((e=>{this.state!==ui&&this.state!==Si&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=fi,t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var s,i,r,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===De?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(i=t.endPTS)?i:NaN).toFixed(3)}] > buffer:${a?ci(Xs.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==_e){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=fi)}const e=null==(o=this.levels)?void 0:o[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=fi,a&&(!this.loadedmetadata&&t.type==De&&a.buffered.length&&(null==(r=this.fragCurrent)?void 0:r.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some((t=>!t)),a=new zs(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,i){var r;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=gi,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(p.KEY_LOADED,t),this.state===gi&&(this.state=fi),t})),this.hls.trigger(p.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const r=n.partList;if(r&&i){s>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,s);if(o>-1){const l=r[o];let h;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${r.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=mi,h=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,i))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,i).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(p.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),f(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=mi;const o=this.config.progressive;let l;return l=o&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,i))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?i:void 0),a]).then((([t])=>(!o&&t&&i&&i(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(p.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,s,i){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,i).then((i=>{o[e.index]=i;const n=i.part;this.hls.trigger(p.FRAG_LOADED,i);const a=ls(s,t.sn,e.index+1)||hs(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});h(a)})).catch(n)};h(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===y.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(p.ERROR,e)}else this.hls.trigger(p.ERROR,{type:v.OTHER_ERROR,details:y.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==yi)return void(this.fragCurrent||this.state===ui||this.state===Si||(this.state=fi));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(s,i,r,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=n>-1?ls(a,r,n):null,l=o?o.fragment:function(t,e,s){if(null==t||!t.details)return null;const i=t.details;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,r&&r.sn===e?r:en&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const s=this.getLoadPosition();return f(s)?this.getFwdBufferInfoAtPos(t,s,e):null}getFwdBufferInfoAtPos(t,e,s){const{config:{maxBufferHole:i}}=this,r=Xs.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&r.nextStart=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=De){const s=this.fragmentTracker.getAppendedFrag(t,De);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start;let a;if(e.live){const o=r.initialLiveManifestSize;if(ie}getNextFragmentLoopLoading(t,e,s,i,r){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&s.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(null!==e&&s.len+e.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a-1&&ss.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!f(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let i=0;i=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function(t,e){return ps(t,(t=>t.cce?-1:0))}(e,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(i.lowLatencyMode&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),te-l?0:l)}else c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===Vs||e===Hs&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn)){if(r&&c.level===r.level){const e=n[t+1];c=c.sn=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r${t.startSN} prev-sn: ${r?r.sn:"na"} fragments: ${i}`),n}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;if(s ${null==(i=this.fragCurrent)?void 0:i.url}`);const r=e.details===y.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===As&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const i=fs(l,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${i}ms`),n.resolved=!0,this.retryDate=self.performance.now()+i,this.state=pi}else if(l&&n){if(this.resetFragmentErrors(t),!(o.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===Ie&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ui&&(this.state=fi)}afterBufferFlushed(t,e,s){if(!t)return;const i=Xs.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===Ti&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=fi}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){var r;const n=s.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,r)=>{const a=t.elementaryStreams[r];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${o})`),e||!1;const l=i?0:rs(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:n,level:s,drift:l,type:r,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&null===(null==(r=this.transmuxer)?void 0:r.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(0===s.fragmentError&&(s.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Ei,this.hls.trigger(p.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class bi{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let i=0;for(let e=0;e0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Be,duration:Number.POSITIVE_INFINITY});r{if(f(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function Ii(t,e){return 255===t[e]&&240==(246&t[e+1])}function _i(t,e){return 1&t[e+1]?7:9}function Ci(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function xi(t,e){return e+1=t.length)return!1;const i=Ci(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||xi(t,r)}return!1}function Mi(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){let r,n,a,o;const l=navigator.userAgent.toLowerCase(),h=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r=1+((192&e[s+2])>>>6);const c=(60&e[s+2])>>>2;if(!(c>d.length-1))return a=(1&e[s+2])<<2,a|=(192&e[s+3])>>>6,A.log(`manifest codec:${i}, ADTS type:${r}, samplingIndex:${c}`),/firefox/i.test(l)?c>=6?(r=5,o=new Array(4),n=c-3):(r=2,o=new Array(2),n=c):-1!==l.indexOf("android")?(r=2,o=new Array(2),n=c):(r=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&c>=6?n=c-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(c>=6&&1===a||/vivaldi/i.test(l))||!i&&1===a)&&(r=2,o=new Array(2)),n=c)),o[0]=r<<3,o[0]|=(14&c)>>1,o[1]|=(1&c)<<7,o[1]|=a<<3,5===r&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[c],channelCount:a,codec:"mp4a.40."+r,manifestCodec:h};{const e=new Error(`invalid ADTS sampling index:${c}`);t.emit(p.ERROR,p.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,s,i,r);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,A.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Fi(t){return 9216e4/t}function Oi(t,e,s,i,r){const n=i+r*Fi(t.samplerate),a=function(t,e){const s=_i(t,e);if(e+s<=t.length){const i=Ci(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,s+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Ni=null;const Ui=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Bi=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],$i=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Gi=[0,1,1,4];function Ki(t,e,s,i,r){if(s+24>e.length)return;const n=Hi(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Hi(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Ui[14*(3===s?3-i:3===i?3:4)+r-1],h=Bi[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=$i[s][i],u=Gi[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===Ni){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ni=t?parseInt(t[1]):0}return!!Ni&&Ni<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function Vi(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Yi(t,e){return e+1{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<>l,s=s?s<e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const h=e[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[s+6]<<8|e[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}class Qi{constructor(){this.VideoSample=null}createVideoSample(t,e,s,i){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:i,length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&A.log(t.pts+"/"+t.dts+":"+t.debug)}}class Ji{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&A.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?s<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,s=8,i=8;for(let r=0;r{var n;switch(i.type){case 1:{let e=!1;a=!0;const r=i.data;if(l&&r.length>4){const t=new Ji(r).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.frame=!0,o.key=e;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Kt(i.data,1,s.pts,e.samples);break;case 7:{var d,c;a=!0,l=!0;const e=i.data,s=new Ji(e).readSPS();if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(d=t.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=r;const i=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[i.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+i.type+" ")}if(o&&a){o.units.push(i)}})),i&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const s=e.byteLength;let i=t.naluState||0;const r=i,n=[];let a,o,l,h=0,d=-1,c=0;for(-1===i&&(d=0,c=31&e[0],i=0,h=1);h=0){const t={data:e.subarray(d,o),type:c};n.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(r&&h<=4-r&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-r)),o>0&&(s.data=Bt(s.data,e.subarray(0,o)),s.state=0))}h=0&&i>=0){const t={data:e.subarray(d,s),type:c,state:i};n.push(t)}if(0===n.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Bt(s.data,e))}return t.naluState=i,n}}class tr{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new di(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}))}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let i=0;for(let e=32;e{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}))}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}}const er=188;class sr{constructor(t,e,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.videoParser=new Zi}static probe(t){const e=sr.syncOffset(t);return e>0&&A.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let s=Math.min(940,e-er)+1,i=0;for(;i1&&(0===n&&a>2||o+er>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:At[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=sr.createTrack("video"),this._audioTrack=sr.createTrack("audio",i),this._id3Track=sr.createTrack("id3"),this._txtTrack=sr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=Bt(this.remainderData,t)).length,this.remainderData=null),y>4>1){if(T=e+5+t[e+4],T===e+er)continue}else T=e+4;switch(y){case h:i&&(d&&(r=lr(d))&&this.videoParser.parseAVCPES(n,l,r,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(T,e+er)),d.size+=e+er-T);break;case c:if(i){if(f&&(r=lr(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+er)),f.size+=e+er-T);break;case u:i&&(g&&(r=lr(g))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+er)),g.size+=e+er-T);break;case 0:i&&(T+=t[T]+1),v=this._pmtId=rr(t,T);break;case v:{i&&(T+=t[T]+1);const r=nr(t,T,this.typeSupported,s,this.observer);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===m||p||(A.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&ar(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`)),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:s,id3Track:i,textTrack:r}=t,n=s.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=lr(n))?(this.videoParser.parseAVCPES(s,r,l,!0,this._duration),s.pesData=null):s.pesData=n,a&&(l=lr(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&A.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=lr(o))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,s){const i=this.demux(t,s,!0,!this.config.progressive),r=this.sampleAes=new tr(this.observer,this.config,e);return this.decrypt(i,r)}decrypt(t,e){return new Promise((s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)})):s(t)})):r.samples&&e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)}))}))}destroy(){this._duration=0}parseAACPES(t,e){let s=0;const i=this.aacOverFlow;let r,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,r=i.sample.unit.byteLength;if(-1===e)o=Bt(i.sample.unit,o);else{const n=r-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void A.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=u({},e,{type:this._videoTrack?Ge:Be,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function ir(t,e){return((31&t[e+1])<<8)+t[e+2]}function rr(t,e){return(31&t[e+10])<<8|t[e+11]}function nr(t,e,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e0){let i=e+5,r=o;for(;r>2;){if(106===t[i])!0!==s.ac3?A.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return ar(r,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return ar(r,new Error("Unsupported HEVC in M2TS found")),n}e+=o+5}return n}function ar(t,e,s){A.warn(`parsing error: ${e.message}`),t.emit(p.ERROR,p.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:e,reason:e.message})}function or(t){A.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function lr(t){let e,s,i,r,n,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Bt(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(s=(e[4]<<8)+e[5],s&&s>t.size-6)return null;const l=e[7];192&l&&(r=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,r-n>54e5&&(A.warn(`${Math.round((r-n)/9e4)}s delta between PTS and DTS, align them`),r=n)):n=r),i=e[8];let h=i+9;if(t.size<=h)return null;t.size-=h;const d=new Uint8Array(t.size);for(let t=0,s=o.length;ts){h-=s;continue}e=e.subarray(h),s-=h,h=0}d.set(e,a),a+=s}return s&&(s-=i+3),{data:d,pts:r,dts:n,len:s}}return null}class hr{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const dr=Math.pow(2,32)-1;class cr{static init(){let t;for(t in cr.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},cr.types)cr.types.hasOwnProperty(t)&&(cr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);cr.HDLR_TYPES={video:e,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);cr.STTS=cr.STSC=cr.STCO=r,cr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),cr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),cr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),cr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);cr.FTYP=cr.box(cr.types.ftyp,n,o,n,a),cr.DINF=cr.box(cr.types.dinf,cr.box(cr.types.dref,i))}static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),i=0,s=8;i>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return cr.box(cr.types.mdia,cr.mdhd(t.timescale,t.duration),cr.hdlr(t.type),cr.minf(t))}static mfhd(t){return cr.box(cr.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?cr.box(cr.types.minf,cr.box(cr.types.smhd,cr.SMHD),cr.DINF,cr.stbl(t)):cr.box(cr.types.minf,cr.box(cr.types.vmhd,cr.VMHD),cr.DINF,cr.stbl(t))}static moof(t,e,s){return cr.box(cr.types.moof,cr.mfhd(t),cr.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=cr.trak(t[e]);return cr.box.apply(null,[cr.types.moov,cr.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(cr.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=cr.trex(t[e]);return cr.box.apply(null,[cr.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(dr+1)),i=Math.floor(e%(dr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return cr.box(cr.types.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(e=0;e>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=cr.box(cr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return cr.box(cr.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,cr.box(cr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),cr.box(cr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return cr.box(cr.types.mp4a,cr.audioStsd(t),cr.box(cr.types.esds,cr.esds(t)))}static mp3(t){return cr.box(cr.types[".mp3"],cr.audioStsd(t))}static ac3(t){return cr.box(cr.types["ac-3"],cr.audioStsd(t),cr.box(cr.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?cr.box(cr.types.stsd,cr.STSD,cr.mp3(t)):"ac3"===t.segmentCodec?cr.box(cr.types.stsd,cr.STSD,cr.ac3(t)):cr.box(cr.types.stsd,cr.STSD,cr.mp4a(t)):cr.box(cr.types.stsd,cr.STSD,cr.avc1(t))}static tkhd(t){const e=t.id,s=t.duration*t.timescale,i=t.width,r=t.height,n=Math.floor(s/(dr+1)),a=Math.floor(s%(dr+1));return cr.box(cr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const s=cr.sdtp(t),i=t.id,r=Math.floor(e/(dr+1)),n=Math.floor(e%(dr+1));return cr.box(cr.types.traf,cr.box(cr.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),cr.box(cr.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),cr.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,cr.box(cr.types.trak,cr.tkhd(t),cr.mdia(t))}static trex(t){const e=t.id;return cr.box(cr.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const s=t.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return cr.box(cr.types.trun,n)}static initSegment(t){cr.types||cr.init();const e=cr.moov(t);return Bt(cr.FTYP,e)}}cr.types=void 0,cr.HDLR_TYPES=void 0,cr.STTS=void 0,cr.STSC=void 0,cr.STCO=void 0,cr.STSZ=void 0,cr.VMHD=void 0,cr.SMHD=void 0,cr.STSD=void 0,cr.FTYP=void 0,cr.DINF=void 0;function ur(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function fr(t,e=!1){return ur(t,1e3,1/9e4,e)}let gr,mr=null,pr=null;class vr{constructor(t,e,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===mr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mr=t?parseInt(t[1]):0}if(null===pr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);pr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){A.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){A.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){A.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t.reduce(((t,s)=>{const i=s.pts-t;return i<-4294967296?(e=!0,yr(t,s.pts)):i>0?t:s.pts}),t[0].pts);return e&&A.debug("PTS rollover detected"),s}remux(t,e,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,m=r;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,L,R,b;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(L=t.pixelRatio)?void 0:L[0])&&(null==(R=e.pixelRatio)?void 0:R[1])===(null==(b=t.pixelRatio)?void 0:b[1])||this.resetInitSegment()}else d=this.generateIS(t,e,r,n);const s=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(t){for(let e=0;e0){A.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(A.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const s=this.getVideoStartPts(e.samples),i=(yr(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(t.samplerate||(A.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,r,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===Ie?m:void 0),T){const i=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(A.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,s,i)}}else T&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Er(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Tr(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4";if(u&&(h=d=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):cr.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=r[0].pts-Math.round(c*s))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:cr.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*s);d=Math.min(d,yr(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,s,i){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let h,d,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!s||null===c){const t=e*r,i=n[0].pts-yr(n[0].dts,n[0].pts);mr&&null!==c&&Math.abs(t-i-c)<15e3?s=!0:c=t-i}const S=l.baseTime*r/l.timescale;for(let t=0;t0?t-1:t].dts&&(T=!0)}T&&n.sort((function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i})),h=n[0].dts,d=n[n.length-1].dts;const L=d-h,R=L?Math.round(L/(o-1)):g||t.inputTimeScale/30;if(s){const t=h-c,s=t>R,i=t<-1;if((s||i)&&(s?A.warn(`AVC: ${fr(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):A.warn(`AVC: ${fr(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!i||c>=n[0].pts||mr)){h=c;const e=n[0].pts-t;if(s)n[0].dts=h,n[0].pts=e;else for(let s=0;se);s++)n[s].dts-=t,n[s].pts-=t;A.log(`Video: Initial PTS/DTS adjusted: ${fr(e,!0)}/${fr(h,!0)}, delta: ${fr(t,!0)} ms`)}}h=Math.max(0,h);let b=0,k=0,w=h;for(let t=0;t0?e.dts-n[t-1].dts:R;if(l=t>0?e.pts-n[t-1].pts:R,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*r),n=(i?m+i*r:this.nextAudioPts)-e.pts;n>t?(g=n-a,g<0?g=a:C=!0,A.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const d=Math.round(e.pts-e.dts);x=Math.min(x,g),M=Math.max(M,g),P=Math.min(P,l),F=Math.max(F,l),a.push(new Sr(e.key,g,h,d))}if(a.length)if(mr){if(mr<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(pr&&F-P0&&(i&&Math.abs(T-E)<9e3||Math.abs(yr(g[0].pts-S,T)-E)<20*l),g.forEach((function(t){t.pts=yr(t.pts-S,T)})),!s||E<0){if(g=g.filter((t=>t.pts>=0)),!g.length)return;E=0===r?0:i&&!f?Math.max(0,T):g[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=E;s=e*l&&h<1e4&&f){let e=Math.round(o/l);i=a-e*l,i<0&&(e--,i+=l),0===s&&(this.nextAudioPts=E=i),A.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(i/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n0))return;k+=m;try{L=new Uint8Array(k)}catch(t){return void this.observer.emit(p.ERROR,p.ERROR,{type:v.MUX_ERROR,details:y.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:`fail allocating audio mdat ${k}`})}if(!d){new DataView(L.buffer).setUint32(0,k),L.set(cr.types.mdat,4)}}L.set(r,m);const l=r.byteLength;m+=l,c.push(new Sr(!0,o,l,0)),b=n}const D=c.length;if(!D)return;const I=c[c.length-1];this.nextAudioPts=E=b+a*I.duration;const _=d?new Uint8Array(0):cr.moof(t.sequenceNumber++,R/a,u({},t,{samples:c}));t.samples=[];const C=R/n,x=E/n,P={data1:_,data2:L,startPTS:C,endPTS:x,startDTS:C,endDTS:x,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,P}remuxEmptyAudio(t,e,s,i){const r=t.inputTimeScale,n=r/(t.samplerate?t.samplerate:r),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:i.startDTS*r)+l,d=i.endDTS*r+l,c=1024*n,u=Math.ceil((d-h)/c),f=hr.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(A.warn("[mp4-remuxer]: remux empty Audio"),!f)return void A.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t4294967296;)t+=s;return t}function Er(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;at.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}class Sr{constructor(t,e,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=s,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function Lr(t,e){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(e===_){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return he(s,!1)}const t="mp4a.40.5";return A.info(`Parsed audio codec "${s}" or audio object type not handled. Using "${t}"`),t}return A.warn(`Unhandled video codec "${s}"`),"hvc1"===s||"hev1"===s?"hvc1.1.6.L120.90":"av01"===s?"av01.0.04M.08":"avc1.42e01e"}try{gr=self.performance.now.bind(self.performance)}catch(t){A.debug("Unable to use Performance API on this environment"),gr=null==$?void 0:$.Date.now}const Ar=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=ki("video",1),n=this.audioTrack=ki("audio",1),a=this.txtTrack=ki("text",1);if(this.id3Track=ki("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=xt(t);if(o.video){const{id:t,timescale:e,codec:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=At.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=i>1?s+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Bt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=_t(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=st(t,0,i.byteOffset-8),e.remainder=st(t,i.byteOffset-8),e}(s);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,e);return r.samples=$t(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=$t(t,e),{videoTrack:e,audioTrack:ki(),id3Track:i,textTrack:ki()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=_t(t.samples,["emsg"]);i&&i.forEach((t=>{const i=function(t){const e=t[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==Rt(t.subarray(h,h+1));)s+=Rt(t.subarray(h,h+1)),h+=1;for(s+=Rt(t.subarray(h,h+1)),h+=1;"\0"!==Rt(t.subarray(h,h+1));)i+=Rt(t.subarray(h,h+1)),h+=1;i+=Rt(t.subarray(h,h+1)),h+=1,r=kt(t,12),n=kt(t,16),o=kt(t,20),l=kt(t,24),h=28}else if(1===e){h+=4,r=kt(t,h),h+=4;const e=kt(t,h);h+=4;const n=kt(t,h);for(h+=4,a=2**32*e+n,g(a)||(a=Number.MAX_SAFE_INTEGER,A.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=kt(t,h),h+=4,l=kt(t,h),h+=4;"\0"!==Rt(t.subarray(h,h+1));)s+=Rt(t.subarray(h,h+1)),h+=1;for(s+=Rt(t.subarray(h,h+1)),h+=1;"\0"!==Rt(t.subarray(h,h+1));)i+=Rt(t.subarray(h,h+1)),h+=1;i+=Rt(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(ji.test(i.schemeIdUri)){const t=f(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale;let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Ge,duration:r})}}))}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;s&&e.isCommonEncryption&&_t(t,["moov","trak"]).forEach((t=>{const e=_t(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let i=_t(e,["enca"]);const r=i.length>0;r||(i=_t(e,["encv"])),i.forEach((t=>{_t(r?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=Nt(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(A.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Tt(t)} -> ${Tt(s)}`),e.set(s,8))}}))}))}));return t}(t,i)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const i=this.initData=xt(t);i.audio&&(e=Lr(i.audio,_)),i.video&&(s=Lr(i.video,C));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:e+","+s,initSegment:t,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:A.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(t,e,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};f(h)||(h=this.lastEndTime=r||0);const c=e.samples;if(null==c||!c.length)return d;const u={initPTS:void 0,timescale:1};let g=this.initData;if(null!=(a=g)&&a.length||(this.generateInitSegment(c),g=this.initData),null==(o=g)||!o.length)return A.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e){let s=0,i=0,r=0;const n=_t(t,["moof","traf"]);for(let t=0;tt+e.info.duration||0),0);s=Math.max(s,t+n.earliestPresentationTime/n.timescale),i=s-e}}if(i&&f(i))return i}return i||r}(c,g),p=function(t,e){return _t(e,["moof","traf"]).reduce(((e,s)=>{const i=_t(s,["tfdt"])[0],r=i[0],n=_t(s,["tfhd"]).reduce(((e,s)=>{const n=kt(s,4),a=t[n];if(a){let t=kt(i,4);if(1===r){if(t===St)return A.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=St+1,t+=kt(i,8)}const s=t/(a.timescale||9e4);if(f(s)&&(null===e||sr}(l,v,r,m)||u.timescale!==l.timescale&&n)&&(u.initPTS=v-r,l&&1===l.timescale&&A.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const y=t?v-l.baseTime/l.timescale:h,E=y+m;!function(t,e,s){_t(e,["moof","traf"]).forEach((e=>{_t(e,["tfhd"]).forEach((i=>{const r=kt(i,4),n=t[r];if(!n)return;const a=n.timescale||9e4;_t(e,["tfdt"]).forEach((t=>{const e=t[0],i=s*a;if(i){let s=kt(t,4);if(0===e)s-=i,s=Math.max(s,0),It(t,4,s);else{s*=Math.pow(2,32),s+=kt(t,8),s-=i,s=Math.max(s,0);const e=Math.floor(s/(St+1)),r=Math.floor(s%(St+1));It(t,4,e),It(t,8,r)}}}))}))}))}(g,c,l.baseTime/l.timescale),m>0?this.lastEndTime=E:(A.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!g.audio,S=!!g.video;let L="";T&&(L+="audio"),S&&(L+="video");const R={data1:c,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:L,hasAudio:T,hasVideo:S,nb:1,dropped:0};return d.audio="audio"===R.type?R:void 0,d.video="audio"!==R.type?R:void 0,d.initSegment=u,d.id3=Er(s,r,l,l),i.samples.length&&(d.text=Tr(i,r,l)),d}}},{demux:sr,remux:vr},{demux:class extends wi{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=nt(t,0);let s=(null==e?void 0:e.length)||0;if(Wi(t,s))return!1;for(let e=t.length;s0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(L&&"AES-128"===L.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,L.key.buffer,L.iv.buffer).then((t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e})),this.decryptionPromise;{let e=t.softwareDecrypt(n,L.key.buffer,L.iv.buffer);if(s.part>-1&&(e=t.flush()),!e)return r.executeEnd=gr(),br(s);n=new Uint8Array(e)}}const R=this.needsProbing(h,d);if(R){const t=this.configureTransmuxer(n);if(t)return A.warn(`[transmuxer] ${t.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=gr(),br(s)}(h||d||f||R)&&this.resetInitSegment(S,g,m,T,e),(h||f||R)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const b=this.transmux(n,L,u,c,s),k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,r.executeEnd=gr(),b}flush(t){const e=t.transmuxing;e.executeStart=gr();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then((()=>this.flush(t)));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=gr(),[br(t)];const h=o.flush(a);return kr(h)?h.then((e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,h,t),n)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;A.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=gr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,i,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer.demuxSampleAes(t,e,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id),chunkMeta:r})))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i,vendor:r}=this;let n;for(let e=0,s=Ar.length;e({remuxResult:{},chunkMeta:t});function kr(t){return"then"in t&&t.then instanceof Function}class wr{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Dr{constructor(t,e,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}var Ir={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||t,a),l=s?s+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r{(e=e||{}).frag=this.frag,e.id=this.id,t===p.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new _r,this.observer.on(p.FRAG_DECRYPTED,n),this.observer.on(p.ERROR,n);const a=te(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(A.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(r.workerPath)):(A.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const s=new Error(`${t.message} (${t.filename}:${t.lineno})`);r.enableWorker=!1,A.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:v.OTHER_ERROR,details:y.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:o,vendor:"",id:e,config:JSON.stringify(r)})}catch(t){A.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Rr(this.observer,o,r,"",e)}return}}this.transmuxer=new Rr(this.observer,o,r,"",e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:r.start,g=r.decryptdata,m=this.frag,p=!(m&&r.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===E||T&&E<=0)),L=self.performance.now();(v||y||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!E&&S||(n.stats.parsing.start=L);const R=!(m&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),b=new Dr(p,S,o,v,f,R);if(!S||p||R){A.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${R}`);const t=new wr(s,i,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,g,l,b);kr(e)?(u.async=!0,e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let s=e.flush(t);kr(s)||e.async?(kr(s)||(s=Promise.resolve(s)),s.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}))):this.handleFlushResult(s,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}onWorkerMessage(t){const e=t.data;if(null==e||!e.event)return void A.warn("worker message received with no "+(e?"event name":"data"));const s=this.hls;if(this.hls)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":A[e.data.logType]&&A[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,s.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function xr(t,e){if(t.length!==e.length)return!1;for(let s=0;st[s]!==e[s]))}function Mr(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class Fr{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}}class Or{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,s){const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const s=new Promise((t=>{e=t})),i={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,t),s}executeNext(t){const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){A.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),s.onError(e);const i=this.buffers[t];null!=i&&i.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Nr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Ur(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}const Br={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},$r=t=>String.fromCharCode(Br[t]||t),Gr=15,Kr=100,Hr={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Vr={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Yr={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Wr={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jr=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class qr{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;A.log(`${this.time} [${t}] ${s}`)}}}const Xr=function(t){const e=[];for(let s=0;sKr&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Kr)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t=144&&this.backSpace();const e=$r(t);this.pos>=Kr?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e"pacData = "+JSON.stringify(t)));let e=t.row-1;if(this.nrRollUpRows&&e"bkgData = "+JSON.stringify(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",i=-1;for(let s=0;s0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class tn{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Zr(s),this.nonDisplayedMemory=new Zr(s),this.lastOutputScreen=new Zr(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;ee+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class en{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new qr;this.channels=[null,new tn(t,e,i),new tn(t+1,s,i)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t"["+Xr([e[t],e[t+1]])+"] -> ("+Xr([s,i])+")"));const a=this.cmdHistory;if(s>=16&&s<=31){if(rn(s,i,a)){sn(null,null,a),this.logger.log(3,(()=>"Repeated command ("+Xr([s,i])+") is dropped"));continue}sn(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else sn(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Xr([s,i])+" orig: "+Xr([e[t],e[t+1]])))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=s,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+Xr([t,e])+")")),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?Hr[t]:Yr[t]:1===i?Vr[t]:Wr[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,(()=>"Special char '"+$r(t)+"' in channel "+s)),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,(()=>"Char codes = "+Xr(i).join(","))),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=jr[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var an=function(){if(null!=$&&$.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function i(t){return s(e,t)}function r(t,...e){let s=1;for(;s100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return L},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class on{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function ln(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class hn{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i=0&&s<=100)return this.set(t,s),!0}return!1}}function dn(t,e,s,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(s);if(2!==i.length)continue;e(i[0],i[1])}}const cn=new an(0,0,""),un="middle"===cn.align?"middle":"center";function fn(t,e,s){const i=t;function r(){const e=ln(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new hn;dn(t,(function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",un,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",un,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",un,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===cn.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",un);let n=i.get("position","auto");"auto"===n&&50===cn.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function gn(t){return t.replace(//gi,"\n")}class mn{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new on,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=gn(t);s>>0).toString()};function En(t,e,s){return yn(t.toString())+yn(e.toString())+yn(s)}function Tn(t,e,s,i,r,n,a){const o=new mn,l=vt(new Uint8Array(t)).trim().replace(pn,"\n").split("\n"),h=[],d=e?function(t,e=1){return ur(t,9e4,1/e)}(e.baseTime,e.timescale):0;let c,u="00:00.000",g=0,m=0,p=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(g-d)/9e4;if(null!=n&&n.new&&(void 0!==m?a=s.ccOffset=n.start:function(t,e,s){let i=t[e],r=t[i.prevCC];if(!r||!r.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=i.start-r.start,i.new=!1,i=r,r=t[i.prevCC]}t.presentationOffset=s}(s,i,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,u=yr(9e4*(t.startTime+a-m),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=En(t.startTime,t.endTime,f)),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(h)},l.forEach((t=>{if(p){if(vn(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{vn(t,"LOCAL:")?u=t.slice(6):vn(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))}));try{m=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(f(e)&&f(s)&&f(i)&&f(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e}(u)/1e3}catch(t){c=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}const Sn="stpp.ttml.im1t",Ln=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,An=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Rn={left:"start",center:"center",right:"end",start:"start",end:"end"};function bn(t,e,s,i){const r=_t(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map((t=>vt(t))),a=function(t,e,s=1,i=!1){return ur(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach((t=>s(function(t,e){const s=(new DOMParser).parseFromString(t,"text/xml"),i=s.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce(((t,e)=>(t[e]=i.getAttribute(`ttp:${e}`)||r[e],t)),{}),a="preserve"!==i.getAttribute("xml:space"),o=wn(kn(i,"styling","style")),l=wn(kn(i,"layout","region")),h=kn(i,"body","[begin]");return[].map.call(h,(t=>{const s=Dn(t,a);if(!s||!t.hasAttribute("begin"))return null;const i=Cn(t.getAttribute("begin"),n),r=Cn(t.getAttribute("dur"),n);let h=Cn(t.getAttribute("end"),n);if(null===i)throw _n(t);if(null===h){if(null===r)throw _n(t);h=i+r}const d=new an(i-e,h-e,s);d.id=En(d.startTime,d.endTime,d.text);const c=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce(((s,n)=>{const a=In(e,i,n)||In(t,i,n)||In(r,i,n);return a&&(s[n]=a),s}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:f}=c;if(f){const t=Rn[f];t&&(d.lineAlign=t),d.align=f}return u(d,c),d})).filter((t=>null!==t))}(t,a))))}catch(t){i(t)}}function kn(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function wn(t){return t.reduce(((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t}),{})}function Dn(t,e){return[].slice.call(t.childNodes).reduce(((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?Dn(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function In(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function _n(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Cn(t,e){if(!t)return null;let s=ln(t);return null===s&&(Ln.test(t)?s=function(t,e){const s=Ln.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):An.test(t)&&(s=function(t,e){const s=An.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}function xn(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Pn(t,e){return!!t&&t.kind===xn(e)&&Mr(e,t)}class Mn{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(p.MANIFEST_PARSED,this.onManifestParsed,this),t.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(p.BUFFER_CODECS,this.onBufferCodecs,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(p.MANIFEST_PARSED,this.onManifestParsed,this),t.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(p.BUFFER_CODECS,this.onBufferCodecs,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&f(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&A.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const s=e.filter(((e,s)=>this.isLevelAllowed(e)&&s<=t));return this.clientRect=null,Mn.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,s){if(null==t||!t.length)return-1;let i=t.length-1;const r=Math.max(e,s);for(let e=0;e=r||s.height>=r)&&(n=s,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){i=e;break}}var n,a;return i}}const Fn="[eme]";class On{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=On.CDMCleanupPromise?[On.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=A.debug.bind(A,Fn),this.log=A.log.bind(A,Fn),this.warn=A.warn.bind(A,Fn),this.error=A.error.bind(A,Fn),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=e[t];if(i)return i.licenseUrl;if(t===G.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map((t=>t.audioCodec)).filter(s),r=e.map((t=>t.videoCodec)).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise(((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?n(t):s(e instanceof Nn?e:new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===tt&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const i=function(t,e,s,i){let r;switch(t){case G.FAIRPLAY:r=["cenc","sinf"];break;case G.WIDEVINE:case G.PLAYREADY:r=["cenc"];break;case G.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}))),videoCapabilities:s.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null})))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let n=null==r?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(i)}`),n=this.requestMediaKeySystemAccess(t,i);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),i.then((s=>s?this.setMediaKeysServerCertificate(e,t,s):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>r.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${Tt(t.keyId||[])}`);const i=s.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return Tt(t.keyId)}updateKeySession(t,e){var s;const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Tt((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),i.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((e,s)=>{const i=Z(this.config),r=t.map(W).filter((t=>!!t&&-1!==i.indexOf(t)));return this.getKeySystemSelectionPromise(r).then((({keySystem:t})=>{const i=J(t);i?e(i):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)}))}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),i=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(e).then((({keySystem:s,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(s,r).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:r,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))))),r.catch((t=>this.handleError(t)))),r}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof Nn?this.hls.trigger(p.ERROR,t.data):this.hls.trigger(p.ERROR,{type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=W(t.keyFormat),s=e?[e]:Z(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=Z(this.config)),0===t.length)throw new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.debug(i),null===s)return;let r,n;if("sinf"===e&&this.config.drmSystems[G.FAIRPLAY]){const t=Rt(new Uint8Array(s));try{const e=N(JSON.parse(t).sinf),s=Nt(new Uint8Array(e));if(!s)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");r=s.subarray(8,24),n=G.FAIRPLAY}catch(t){return void this.warn(`${i} Failed to parse sinf: ${t}`)}}else{const t=function(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32t.systemId===z))[0];if(!e)return void(0===t.length||t.some((t=>!t.systemId))?this.warn(`${i} contains incomplete or invalid pssh data`):this.log(`ignoring ${i} for ${t.map((t=>Q(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(n=Q(e.systemId),0===e.version&&e.data){const t=e.data.length-22;r=e.data.subarray(t,t+16)}}if(!n||!r)return;const a=Tt(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let h=o[a];for(let t=0;tthis.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match")));break}}h||(h=o[a]=this.getKeySystemSelectionPromise([n]).then((({keySystem:t,mediaKeys:i})=>{var n;this.throwIfDestroyed();const o=new jt("ISO-23001-7",a,null!=(n=J(t))?n:"");return o.pssh=new Uint8Array(s),o.keyId=r,this.attemptSetMediaKeys(t,i).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-no-match")}))}))),h.catch((t=>this.handleError(t)))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(i),i.then((()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===s.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,s,i){var r,n;const a=null==(r=this.config.drmSystems)||null==(n=r[t.keySystem])?void 0:n.generateRequest;if(a)try{const i=a.call(this.hls,e,s,t);if(!i)throw new Error("Invalid response from configured generateRequest filter");e=i.initDataType,s=t.decryptdata.pssh=i.initData?new Uint8Array(i.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${i}": ${l} (init data type: ${e} length: ${s?s.byteLength:null})`);const h=new _r,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void h.emit("error",new Error("invalid state"));const{messageType:i,message:r}=e;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(t,r).catch((t=>{this.handleError(t),h.emit("error",t)})):"license-release"===i?t.keySystem===G.FAIRPLAY&&(this.updateKeySession(t,B("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${i}"`)},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;h.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",c);const u=new Promise(((t,e)=>{h.on("error",e),h.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return t.mediaKeysSession.generateRequest(e,s).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)})).catch((t=>{throw new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>u)).catch((e=>{throw h.removeAllListeners(),this.removeSession(t),e})).then((()=>(h.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${Tt("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Tt(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise(((r,n)=>{const a={responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:h({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(a,l,d)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise(((i,r)=>{t.setServerCertificate(s).then((r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),i(t)})).catch((t=>{r(new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((t=>{throw new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s in key message");return B(atob(l))}setupLicenseXHR(t,e,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,s,i)})).catch((n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,s,i)})).then((s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||i}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise(((i,r)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(t){this.error(t)}i(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Nn({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(i,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then((({xhr:e,licenseChallenge:s})=>{t.keySystem==G.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},jt.clearKeyUriToKeyIdMap();const s=e.length;On.CDMCleanupPromise=Promise.all(e.map((t=>this.removeSession(t))).concat(null==t?void 0:t.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}`)})))).then((()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);return i>-1&&this.mediaKeySessions.splice(i,1),e.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>e.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}On.CDMCleanupPromise=void 0;class Nn extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var Un,Bn,$n;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(Un||(Un={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(Bn||(Bn={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}($n||($n={}));const Gn={[$n.OBJECT]:["br","d","ot","tb"],[$n.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[$n.SESSION]:["cid","pr","sf","sid","st","v"],[$n.STATUS]:["bs","rtp"]};class Kn{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof Kn?t:new Kn(t)))),this.value=t,this.params=e}}class Hn{constructor(t){this.description=void 0,this.description=t}}function Vn(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}const Yn="Bare Item";const Wn=/[\x00-\x1f\x7f]+/;function jn(t,e,s){return Vn("serialize",t,e,s)}function qn(t){if(!1===ArrayBuffer.isView(t))throw jn(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Xn(t){if(function(t){return t<-999999999999999||99999999999999912)throw jn(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}function Jn(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw jn(e,"Token");return e}function Zn(t){switch(typeof t){case"number":if(!f(t))throw jn(t,Yn);return Number.isInteger(t)?Xn(t):Qn(t);case"string":return function(t){if(Wn.test(t))throw jn(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Jn(t);case"boolean":return function(t){if("boolean"!=typeof t)throw jn(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Xn(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return qn(t);if(t instanceof Hn)return Jn(t);default:throw jn(t,Yn)}}function ta(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw jn(t,"Key");return t}function ea(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${ta(t)}`:`;${ta(t)}=${Zn(e)}`)).join("")}function sa(t){return t instanceof Kn?`${Zn(t.value)}${ea(t.params)}`:Zn(t)}function ia(t,e={whitespace:!0}){if("object"!=typeof t)throw jn(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),i=null!=e&&e.whitespace?" ":"";return Array.from(s).map((([t,e])=>{e instanceof Kn==!1&&(e=new Kn(e));let s=ta(t);var i;return!0===e.value?s+=ea(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(sa).join(" ")})${ea(i.params)}`:s+=sa(e)),s})).join(`,${i}`)}const ra=t=>Math.round(t),na=t=>100*ra(t/100),aa={br:ra,d:ra,bl:na,dl:na,mtp:na,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const s=new URL(t),i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:na,tb:ra};function oa(t,e){const s={};if(null==t||"object"!=typeof t)return s;const i=Object.keys(t).sort(),r=u({},aa,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return i.forEach((i=>{if(null!=n&&n(i))return;let a=t[i];const o=r[i];o&&(a=o(a,e)),"v"===i&&1===a||"pr"==i&&1===a||(t=>"number"==typeof t?f(t):null!=t&&""!==t&&!1!==t)(a)&&((t=>"ot"===t||"sf"===t||"st"===t)(i)&&"string"==typeof a&&(a=new Hn(a)),s[i]=a)})),s}function la(t,e={}){return t?function(t,e){return ia(t,e)}(oa(t,e),u({whitespace:!1},e)):""}function ha(t,e,s){return u(t,function(t,e={}){if(!t)return{};const s=Object.entries(t),i=Object.entries(Gn).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),r=s.reduce(((t,e)=>{var s;const[r,n]=e,a=(null==(s=i.find((t=>t[1].includes(r))))?void 0:s[0])||$n.REQUEST;return null!=t[a]||(t[a]={}),t[a][r]=n,t}),{});return Object.entries(r).reduce(((t,[s,i])=>(t[s]=la(i,e),t)),{})}(e,s))}const da=/CMCD=[^&#]+/;function ca(t,e,s){const i=function(t,e={}){if(!t)return"";const s=la(t,e);return`CMCD=${encodeURIComponent(s)}`}(e,s);if(!i)return t;if(da.test(t))return t.replace(da,i);const r=t.includes("?")?"&":"?";return`${t}${r}${i}`}function ua(t,e,s,i){t&&Object.keys(e).forEach((r=>{const n=t.filter((t=>t.groupId===r)).map((t=>{const n=u({},t);return n.details=void 0,n.attrs=new k(n.attrs),n.url=n.attrs.URI=fa(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n}));t.push(...n)}))}function fa(t,e,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}const ga=/^age:\s*[\d.]+\s*$/im;class ma{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new I,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,e.url)})).catch((t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r(s,e.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)})).catch((t=>{this.callbacks.onError({code:s.status,text:t.message},e,s,i)})):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const e in i)t.setRequestHeader(e,i[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&f(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,n="text"!==e.responseType;if(i>=200&&i<300&&(n&&e.response||null!==e.responseText)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const r=n?e.response:e.responseText,a="arraybuffer"===e.responseType?r.byteLength:r.length;if(s.loaded=s.total=a,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(s,t,r,e),!this.callbacks)return;const l={url:e.responseURL,data:r,code:i};this.callbacks.onSuccess(l,s,t,e)}else{const n=r.loadPolicy.errorRetry;ms(n,s.retry,!1,{url:t.url,data:void 0,code:i})?this.retry(n):(A.error(`${i} while loading ${t.url}`),this.callbacks.onError({code:i,text:e.statusText},t,e,s))}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(ms(t,this.stats.retry,!0))this.retry(t);else{var e;A.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=fs(t,s.retry),s.retry++,A.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&ga.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const pa=/(\d+)-(\d+)\/(\d+)/;class va{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||ya,this.controller=new self.AbortController,this.stats=new I}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(u({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),n=s.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=l&&f(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(i,t,this.response)}),e.timeout),self.fetch(this.request).then((r=>{this.response=this.loader=r;const o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(i,t,this.response)}),h-(o-i.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new Ea(e||"fetch, bad network response",t,r)}return i.loading.first=o,i.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=pa.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(f(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(r.headers)||i.total,n&&f(e.highWaterMark)?this.loadProgressively(r,i,t,e.highWaterMark,n):a?r.arrayBuffer():"json"===t.responseType?r.json():r.text()})).then((r=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=r[o];l&&(i.loaded=i.total=l);const h={url:a.url,data:r,code:a.status};n&&!f(e.highWaterMark)&&n(i,t,r,a),s.onSuccess(h,i,t,a)})).catch((e=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=e&&e.code||0,n=e?e.message:null;s.onError({code:r,text:n},t,e?e.details:null,i)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,i=0,r){const n=new bi,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(e,s,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h=i&&r(e,s,n.flush(),t)):r(e,s,l,t),o()})).catch((()=>Promise.reject()));return o()}}function ya(t,e){return new self.Request(t.url,e)}class Ea extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const Ta=/\s/,Sa={newCue(t,e,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const i=gn(h.trim()),f=En(e,s,i);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),r.forEach((e=>Fe(t,e)))),r}},La=h(h({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ma,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:e,hls:s}=this,{autoLevelEnabled:i,media:r}=s;if(!t||!r)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=n-a.loading.start,h=s.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!i||r.paused||!r.playbackRate||!r.readyState)return;const d=s.mainForwardBufferInfo;if(null===d)return;const c=this.bwEstimator.getEstimateTTFB(),u=Math.abs(r.playbackRate);if(l<=Math.max(c,o/(2*u)*1e3))return;const g=d.len/u,m=a.loading.first?a.loading.first-a.loading.start:-1,v=a.loaded&&m>-1,y=this.getBwEstimate(),E=s.levels,T=E[t.level],S=a.total||Math.max(a.loaded,Math.round(o*T.averageBitrate/8));let L=v?l-m:l;L<1&&v&&(L=Math.min(l,8*a.loaded/y));const R=v?1e3*a.loaded/L:0,b=R?(S-a.loaded)/R:8*S/y+c/1e3;if(b<=g)return;const k=R?8*R:y;let w,D=Number.POSITIVE_INFINITY;for(w=t.level-1;w>h;w--){const t=E[w].maxBitrate;if(D=this.getTimeToLoadFrag(c/1e3,k,o*t,!E[w].details),D=b)return;if(D>10*o)return;s.nextLoadLevel=s.nextAutoLevel=w,v?this.bwEstimator.sample(l-Math.min(c,m),a.loaded):this.bwEstimator.sampleTTFB(l);const I=E[w].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>I&&this.resetEstimator(I),this.clearTimer(),A.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${g.toFixed(3)} s\n Estimated load time for current fragment: ${b.toFixed(3)} s\n Estimated load time for down switch fragment: ${D.toFixed(3)} s\n TTFB estimate: ${0|m} ms\n Current BW estimate: ${f(y)?0|y:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${w} @ ${0|I} bps`),s.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(A.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new Is(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.FRAG_LOADING,this.onFragLoading,this),t.on(p.FRAG_LOADED,this.onFragLoaded,this),t.on(p.FRAG_BUFFERED,this.onFragBuffered,this),t.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(p.LEVEL_LOADED,this.onLevelLoaded,this),t.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.FRAG_LOADING,this.onFragLoading,this),t.off(p.FRAG_LOADED,this.onFragLoaded,this),t.off(p.FRAG_BUFFERED,this.onFragBuffered,this),t.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(p.LEVEL_LOADED,this.onLevelLoaded,this),t.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case y.BUFFER_ADD_CODEC_ERROR:case y.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case y.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.start;f(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===De&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:s,id:e.type};this.onFragBuffered(p.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==De||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,e,t,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return A.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,h,d);if(t>=0)return t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,A.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(A.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=s.levels[n],g=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===g.length)return 0;const y=g[d],E=!(null==y||null==(o=y.details)||!o.live),T=-1===p||-1===h;let S,L="SDR",R=(null==y?void 0:y.frameRate)||0;const{audioPreference:b,videoPreference:k}=v,w=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(m));if(T){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce(((t,s)=>{if(!s.codecSet)return t;const i=s.audioGroups;let r=t[s.codecSet];r||(t[s.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,s.bitrate);const n=Math.min(s.height,s.width);return r.minHeight=Math.min(r.minHeight,n),r.minFramerate=Math.min(r.minFramerate,s.frameRate),r.maxScore=Math.max(r.maxScore,s.score),r.fragmentError+=s.fragmentError,r.videoRanges[s.videoRange]=(r.videoRanges[s.videoRange]||0)+1,i&&i.forEach((t=>{if(!t)return;const s=e.groups[t];s&&(r.hasDefaultAudio=r.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{r.channels[t]=(r.channels[t]||0)+s.channels[t]})))})),t}),{})}(g,w,e,s)),r=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=a&&2===parseInt(a);let h=!0,d=!1,c=1/0,u=1/0,g=1/0,m=0,p=[];const{preferHDR:v,allowedVideoRanges:y}=Ms(e,r);for(let e=n.length;e--;){const s=t[n[e]];h=s.channels[2]>0,c=Math.min(c,s.minHeight),u=Math.min(u,s.minFramerate),g=Math.min(g,s.minBitrate);const i=y.filter((t=>s.videoRanges[t]>0));i.length>0&&(d=!0,p=i)}c=f(c)?c:0,u=f(u)?u:0;const E=Math.max(1080,c),T=Math.max(30,u);return g=f(g)?g:s,s=Math.max(g,s),d||(e=void 0,p=[]),{codecSet:n.reduce(((e,i)=>{const r=t[i];if(i===e)return e;if(r.minBitrate>s)return Fs(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Fs(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Fs(i,`audio codec preference "${o}" not found`),e;if(a&&!l){if(!r.channels[a])return Fs(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||l)&&h&&0===r.channels[2])return Fs(i,"no renditions with stereo sound found"),e;return r.minHeight>E?(Fs(i,`min resolution of ${r.minHeight} > maximum of ${E}`),e):r.minFramerate>T?(Fs(i,`min framerate of ${r.minFramerate} > maximum of ${T}`),e):p.some((t=>r.videoRanges[t]>0))?r.maxScore=ae(e)||r.fragmentError>t[e].fragmentError)?e:(m=r.maxScore,i):(Fs(i,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),e)}),void 0),videoRanges:p,preferHDR:v,minFramerate:u,minBitrate:g}}(i,L,t,b,k),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=r;S=n,L=h?a[a.length-1]:a[0],R=o,t=Math.max(t,l),A.log(`[abr] picked start tier ${JSON.stringify(r)}`)}else S=null==y?void 0:y.codecSet,L=null==y?void 0:y.videoRange;const D=u?u.duration:c?c.duration:0,I=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let o=s;o>=e;o--){var C;const e=g[o],c=o>d;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&xs(e,w,L,R,t,b)?(e.supportedPromise=Ps(e,w,s),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?A.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${JSON.stringify(t)}`):t.supported||(A.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${i} ${JSON.stringify(t)}`),i>-1&&s.length>1&&(A.log(`[abr] Removing unsupported level ${i}`),this.hls.removeLevel(i)))}))):e.supportedResult=_s}if(S&&e.codecSet!==S||L&&e.videoRange!==L||c&&R>e.frameRate||!c&&R>0&&R=2*D&&0===r?g[o].averageBitrate:g[o].maxBitrate,M=this.getTimeToLoadFrag(I,x,P*k,void 0===m);if(x>=P&&(o===h||0===e.loadError&&0===e.fragmentError)&&(M<=I||!f(M)||E&&!this.bitrateTestDelay||M${o} adjustedbw(${Math.round(x)})-bitrate=${Math.round(x-P)} ttfb:${I.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${T} codecSet:${S} videoRange:${L} hls.loadLevel:${p}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls,i=Math.min(Math.max(t,s),e);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}},bufferController:class{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=t=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:t,mediaSource:e})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&A.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var s;this.appendSource=(s=te(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.log=A.log.bind(A,e),this.warn=A.warn.bind(A,e),this.error=A.error.bind(A,e),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:t}=this;t.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.MANIFEST_PARSED,this.onManifestParsed,this),t.on(p.BUFFER_RESET,this.onBufferReset,this),t.on(p.BUFFER_APPENDING,this.onBufferAppending,this),t.on(p.BUFFER_CODECS,this.onBufferCodecs,this),t.on(p.BUFFER_EOS,this.onBufferEos,this),t.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(p.FRAG_PARSED,this.onFragParsed,this),t.on(p.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.MANIFEST_PARSED,this.onManifestParsed,this),t.off(p.BUFFER_RESET,this.onBufferReset,this),t.off(p.BUFFER_APPENDING,this.onBufferAppending,this),t.off(p.BUFFER_CODECS,this.onBufferCodecs,this),t.off(p.BUFFER_EOS,this.onBufferEos,this),t.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(p.FRAG_PARSED,this.onFragParsed,this),t.off(p.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Or(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const s=this.media=e.media,i=te(this.appendSource);if(s&&i){var r;const t=this.mediaSource=new i;this.log(`created media source: ${null==(r=t.constructor)?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming));const e=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{s.removeAttribute("src");const i=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||i&&t instanceof i,Ur(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=this;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&Ur(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(p.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var s;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length,i=Object.keys(e);if(i.forEach((t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var i;const{id:r,codec:n,levelCodec:a,container:o,metadata:l}=e[t],h=de(s.codec,s.levelCodec),d=null==h?void 0:h.replace(Nr,"$1");let c=de(n,a);const u=null==(i=c)?void 0:i.replace(Nr,"$1");if(c&&d!==u){"audio"===t.slice(0,5)&&(c=he(c,this.appendSource));const e=`${o};codecs=${c}`;this.appendChangeType(t,e),this.log(`switching codec ${h} to ${c}`),this.tracks[t]={buffer:s.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:r}}}}else this.pendingTracks[t]=e[t]})),s)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:s}=this,i={execute:()=>{const i=this.sourceBuffer[t];i&&(this.log(`changing ${t} sourceBuffer type to ${e}`),i.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};s.append(i,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:s,operationQueue:i,tracks:r}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=e,d=h.buffering[a],c=self.performance.now();d.start=c;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=c),f&&0===f.start&&(f.start=c);const g=r.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const E=o.start,T={execute:()=>{if(d.executeStart=self.performance.now(),m){const t=this.sourceBuffer[a];if(t){const e=E-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${E} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=E)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();d.executeEnd=d.end=t,0===u.first&&(u.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=Xs.getBuffered(e[t]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:s})},onError:t=>{const e={type:v.MEDIA_ERROR,parent:o.type,details:y.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=y.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=y.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${s.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=s.config.appendErrorMaxRetry&&(e.fatal=!0)}s.trigger(p.ERROR,e)}};i.append(T,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:s}=this,i=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?s.append(i(e.type),e.type):this.getSourceBufferTypes().forEach((t=>{s.append(i(t),t)}))}onFragParsed(t,e){const{frag:s,part:i}=e,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[x]?r.push("audiovideo"):(n[_]&&r.push("audio"),n[C]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type})}),r)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce(((t,s)=>{const i=this.sourceBuffer[s];return!i||e.type&&e.type!==s||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${s} sourceBuffer now EOS`))),t&&!(i&&!i.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)}));const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||null===e)return;if(!this.getSourceBufferTypes().length)return;const i=t.config,r=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(f(a)&&a>0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}if(f(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){const t=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),e=Math.max(t,n),s=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(t,e,s){const{details:i,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((n=>{const a=r[n];if(a){const r=Xs.getBuffered(a);if(r.length>0&&s>r.start(0)){if(this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=i&&i.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(a.ended&&r.end(r.length-1)-t<2*e)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}}))}flushFrontBuffer(t,e,s){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach((r=>{const n=i[r];if(n){const i=Xs.getBuffered(n),a=i.length;if(a<2)return;const o=i.start(a-1),l=i.end(a-1);if(s>o||t>=o&&t<=l)return;if(n.ended&&t-l<2*e)return void this.log(`Cannot flush ${r} front buffer while SourceBuffer is in ended state`);this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:r})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:s,mediaSource:i}=this,r=t.fragments[0].start+t.totalduration,n=s.duration,a=f(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(t)):(r>a&&r>n||!f(n))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(t){const e=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=e&&e.setLiveSeekableRange){const i=Math.max(0,s[0].start),r=Math.max(i,i+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${i}-${r}.`),e.setLiveSeekableRange(i,r)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&(!t||2===i||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(p.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{e.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const r in t)if(!e[r]){var i;const n=t[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let a=-1===(null==(i=n.levelCodec)?void 0:i.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===r.slice(0,5)&&(a=he(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[r]=s.addSourceBuffer(o),i=r;this.addBufferListener(i,"updatestart",this._onSBUpdateStart),this.addBufferListener(i,"updateend",this._onSBUpdateEnd),this.addBufferListener(i,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(i,"bufferedchange",((t,e)=>{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:r})})),this.tracks[r]={buffer:t,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:r,mimeType:o})}}}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const{operationQueue:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(i)}removeExecutor(t,e,s){const{media:i,mediaSource:r,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!i||!r||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const l=f(i.duration)?i.duration:1/0,h=f(r.duration)?r.duration:1/0,d=Math.max(0,e),c=Math.min(s,l,h);c>d&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${d},${c}] from the ${t} SourceBuffer`),o.remove(d,c)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.sourceBuffer[e];if(s)s.ended=!1,s.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:s}=this,i=e.map((t=>s.appendBlocker(t)));Promise.all(i).then((()=>{t(),e.forEach((t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||s.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,s){const i=this.sourceBuffer[t];if(!i)return;const r=s.bind(this,t);this.listeners[t].push({event:e,listener:r}),i.addEventListener(e,r)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach((t=>{e.removeEventListener(t.event,t.listener)}))}},capLevelController:Mn,errorController:class{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=A.log.bind(A,"[info]:"),this.warn=A.warn.bind(A,"[warning]:"),this.error=A.error.bind(A,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(p.ERROR,this.onError,this),t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(p.ERROR,this.onError,this),t.off(p.ERROR,this.onErrorOut,this),t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===De?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var s,i;if(e.fatal)return;const r=this.hls,n=e.context;switch(e.details){case y.FRAG_LOAD_ERROR:case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_ERROR:case y.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case y.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction={action:Ts,flags:Rs});case y.FRAG_GAP:case y.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ss);case y.LEVEL_EMPTY_ERROR:case y.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===De?e.level:r.loadLevel;e.details===y.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case y.LEVEL_LOAD_ERROR:case y.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case y.AUDIO_TRACK_LOAD_ERROR:case y.AUDIO_TRACK_LOAD_TIMEOUT:case y.SUBTITLE_LOAD_ERROR:case y.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=r.levels[r.loadLevel];if(t&&(n.type===ke&&t.hasAudioGroup(n.groupId)||n.type===we&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Ss,void(e.errorAction.flags=bs)}return;case y.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.levels[r.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?e.errorAction={action:Ss,flags:ks,hdcpLevel:s}:this.keySystemError(e)}return;case y.BUFFER_ADD_CODEC_ERROR:case y.REMUX_ALLOC_ERROR:case y.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(i=e.level)?i:r.loadLevel));case y.INTERNAL_EXCEPTION:case y.BUFFER_APPENDING_ERROR:case y.BUFFER_FULL_ERROR:case y.LEVEL_SWITCH_ERROR:case y.BUFFER_STALLED_ERROR:case y.BUFFER_SEEK_OVER_HOLE:case y.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Ts,flags:Rs})}e.type===v.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const s=us(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(ms(s,i,cs(t),t.response))return{action:As,flags:Rs,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=us(t.details.startsWith("key")?n:r,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(i){t.details!==y.FRAG_GAP&&i.fragmentError++;if(ms(a,o,cs(t),t.response))return{action:As,flags:Rs,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,e===y.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===Ie&&e===y.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===y.BUFFER_ADD_CODEC_ERROR||e===y.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:t})=>i.audioCodec!==t)),m="video"===t.sourceBufferName&&(e===y.BUFFER_ADD_CODEC_ERROR||e===y.BUFFER_APPEND_ERROR)&&h.some((({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e)),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(e===y.FRAG_GAP&&f===De&&t.frag){const e=h[r].details;if(e){const s=vs(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===ke&&s.hasAudioGroup(v)||p===we&&s.hasSubtitleGroup(v))continue;if(f===Ie&&null!=(a=i.audioGroups)&&a.some((t=>s.hasAudioGroup(t)))||f===_e&&null!=(o=i.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||g&&i.audioCodec===s.audioCodec||!g&&i.audioCodec!==s.audioCodec||m&&i.codecSet===s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ss,flags:Rs,nextAutoLevel:l}}return{action:Ss,flags:bs}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Ts:break;case Ss:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===y.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case Rs:this.switchLevel(t,n);break;case ks:r&&(e.maxHdcpLevel=qe[qe.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,n)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(p.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;A.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:tt,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Sa,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Ri{constructor(t,e,s){super(t,e,s,"[subtitle-stream-controller]",_e),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.LEVEL_LOADED,this.onLevelLoaded,this),t.on(p.ERROR,this.onError,this),t.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.LEVEL_LOADED,this.onLevelLoaded,this),t.off(p.ERROR,this.onError,this),t.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=fi,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:i}=e;if(this.fragPrevious=s,this.state=fi,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let t=0;t=r[t].start&&a<=r[t].end){n=r[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let s=0;snew es(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new es(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,_e),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,os(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(ei(n,t),l=n.fragments[0].start):e&&(l=e.start,os(n,l))}if(o.details=n,this.levelLastLoaded=o,a===i&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===fi)){vs(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch((t=>{throw r.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((s=>{const i=performance.now();r.trigger(p.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:i}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=fi}))}}doTick(){if(this.media){if(this.state===fi){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;const{config:i}=this,r=this.getLoadPosition(),n=Xs.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,De),h=s.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const d=h.fragments,c=d.length,u=h.edge;let f=null;const g=this.fragPrevious;if(au-t?0:t;f=vs(g,d,Math.max(d[0].start,a),e),!f&&g&&g.startthis.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Ue(this.media.textTracks);for(let s=0;s-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.MANIFEST_PARSED,this.onManifestParsed,this),t.on(p.LEVEL_LOADING,this.onLevelLoading,this),t.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.MANIFEST_PARSED,this.onManifestParsed,this),t.off(p.LEVEL_LOADING,this.onLevelLoading,this),t.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(p.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Ue(this.media.textTracks).forEach((t=>{Oe(t)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=Os(e,t);if(s>-1)r=t[s];else{const t=Os(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i),t}if(s)return null;{const s=Os(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const s=e.id,i=e.groupId;let r=e.url;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Ue(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter((t=>Mr(s,t)))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==i&&(t.mode="disabled")})),i){const t=this.subtitleDisplay?"showing":"hidden";i.mode!==t&&(i.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!f(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=i;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(d)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(p.FRAG_LOADING,this.onFragLoading,this),t.on(p.FRAG_LOADED,this.onFragLoaded,this),t.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(p.FRAG_LOADING,this.onFragLoading,this),t.off(p.FRAG_LOADED,this.onFragLoaded,this),t.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new nn(this,"textTrack1"),e=new nn(this,"textTrack2"),s=new nn(this,"textTrack3"),i=new nn(this,"textTrack4");this.cea608Parser1=new en(1,t,e),this.cea608Parser2=new en(3,s,i)}}addCues(t,e,s,i,r){let n=!1;for(let t=r.length;t--;){const i=r[t],d=(a=i[0],o=i[1],l=e,h=s,Math.min(o,h)-Math.max(a,l));if(d>=0&&(i[0]=Math.min(i[0],e),i[1]=Math.max(i[1],s),n=!0,d/(s-e)>.5))return}var a,o,l,h;if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,s,i)}else{const r=this.Cues.newCue(null,e,s,i);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:n}=this;"main"===s&&(this.initPTS[e.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach((t=>{this.onFragLoaded(p.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i{Oe(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;tt.textCodec===Sn));if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(xr(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?Ue(t.textTracks):null;if(this.tracks.forEach(((t,s)=>{let i;if(e){let s=null;for(let i=0;inull!==t)).map((t=>t.label));t.length&&A.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s=`textTrack${e[1]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===De){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.type===_e)if(i.byteLength){const t=s.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===Sn?this._parseIMSC1(s,i):this._parseVTTs(e)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;bn(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),s.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{A.log(`Failed to parse IMSC1: ${e}`),s.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(t);const o=this.hls;Tn(null!=(e=s.initSegment)&&e.data?Bt(s.initSegment.data,new Uint8Array(i)):i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(s,i),A.log(`Failed to parse VTT cue: ${e}`),r&&a>s.cc||o.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})}))}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||bn(e,this.initPTS[t.cc],(()=>{s.textCodec=Sn,this._parseIMSC1(t,e)}),(()=>{s.textCodec="wvtt"}))}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach((t=>Fe(s,t)))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger(p.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===_e&&this.onFragLoaded(p.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!s||!i)return;const{frag:r,samples:n}=e;if(r.type!==De||"NONE"!==this.closedCaptionsForLevel(r))for(let t=0;tNe(t[i],e,s)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==i){const{textTracks:t}=this;Object.keys(t).forEach((s=>Ne(t[s],e,i)))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=fi):(this.loadedmetadata=!1,this.state=vi),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case fi:this.doTickIdle();break;case vi:{var t;const{levels:e,trackId:s}=this,i=null==e||null==(t=e[s])?void 0:t.details;if(i){if(this.waitForCdnTuneIn(i))break;this.state=Li}break}case pi:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=fi}break}case Li:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=mi;const t={frag:e,part:s,payload:i.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=Xs.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);ys(s.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=fi}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=fi)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:s,trackId:i}=this,r=t.config;if(!s&&(this.startFragRequested||!r.startFragPrefetch)||null==e||!e[i])return;const n=e[i],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=vi);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,_,Ie));const l=this.getFwdBufferInfo(o,Ie);if(null===l)return;const{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return t.trigger(p.BUFFER_EOS,{type:"audio"}),void(this.state=Ti);const c=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,De),u=l.len,f=this.getMaxBufferLength(null==c?void 0:c.len),g=a.fragments,m=g[0].start;let v=this.flushing?this.getLoadPosition():l.end;if(d&&s){const t=this.getLoadPosition();h&&!Pr(d.attrs,h.attrs)&&(v=t),a.PTSKnown&&tm||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05)}if(u>=f&&!d&&vc.end+a.targetduration;if(T||(null==c||!c.len)&&l.len){const t=this.getAppendedFrag(y.start,De);if(null===t)return;if(E||(E=!!t.gap||!!T&&0===c.len),T&&!E||E&&l.nextStart&&l.nextStartnew es(t)))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=e,this.state=fi,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=ui),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(p.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:i}=this,{details:r,id:n}=e;if(!i)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const a=i[n];let o=0;if(r.live||null!=(s=a.details)&&s.live){this.checkLiveUpdate(r);const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;var l;if(!a.details&&r.hasProgramDateTime&&t.hasProgramDateTime)ei(r,t),o=r.fragments[0].start;else o=this.alignPlaylists(r,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=r,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(this.mainDetails||r,o),this.state!==vi||this.waitForCdnTuneIn(r)||(this.state=fi),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:i,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Cr(this.hls,Ie,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new zs(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n);c.push(r,f,d,"",s,i,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new bi,complete:!1};t.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=Li}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===Ie)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==s.sn){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,h({},t)))}this.fragBufferedComplete(s,i)}else if(!this.loadedmetadata&&s.type===De){const t=this.videoBuffer||this.media;if(t){Xs.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var s;if(e.fatal)this.state=Si;else switch(e.details){case y.FRAG_GAP:case y.FRAG_PARSING_ERROR:case y.FRAG_DECRYPT_ERROR:case y.FRAG_LOAD_ERROR:case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_ERROR:case y.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ie,e);break;case y.AUDIO_TRACK_LOAD_ERROR:case y.AUDIO_TRACK_LOAD_TIMEOUT:case y.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==vi||(null==(s=e.context)?void 0:s.type)!==ke||(this.state=fi);break;case y.BUFFER_APPEND_ERROR:case y.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===y.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case y.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==C&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==C){this.flushing=!1,this.bufferFlushed=!0,this.state===Ti&&(this.state=fi);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,Ie),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:f,id3:g,initSegment:m}=r;if(!this.fragContextChanged(o)&&d){if(this.state=yi,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,m.tracks,t,n),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:m.tracks})}if(c){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[_]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(_,t,e,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=g&&null!=(e=g.samples)&&e.length){const t=u({id:s,frag:o,details:d},g);i.trigger(p.FRAG_PARSING_METADATA,t)}if(f){const t=u({id:s,frag:o,details:d},f);i.trigger(p.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s,i){if(this.state!==yi)return;e.video&&delete e.video;const r=e.audio;if(!r)return;r.id="audio";const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(p.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(p.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.fragCurrent=t,this.switchingTrack||i===Gs||i===Hs)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Li;const s=this.mainDetails;s&&s.fragments[0].start!==e.details.fragments[0].start&&ei(e.details,s)}else this.startFragRequested=!0,super.loadFragment(t,e,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:s}=this,i=null==s?void 0:s.attrs,r=t.attrs;e&&i&&(i.CHANNELS!==r.CHANNELS||s.name!==t.name||s.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(p.AUDIO_TRACK_SWITCHED,h({},t))}},audioTrackController:class extends ws{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.MANIFEST_PARSED,this.onManifestParsed,this),t.on(p.LEVEL_LOADING,this.onLevelLoading,this),t.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.MANIFEST_PARSED,this.onManifestParsed,this),t.off(p.LEVEL_LOADING,this.onLevelLoading,this),t.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=Os(e,t,Us);if(s>-1)r=t[s];else{const t=Os(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==ke||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Ns(t,i,Us))return i;const r=Os(t,this.tracksInGroup,Us);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce(((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t}),{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Bs(e,i,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return Os(t,n,r)>-1}));return d>-1?d:Bs(e,i,(e=>{const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return Os(t,n,r)>-1}))}(t,e.levels,s,i,Us);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=Os(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t],r=i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,h({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:Un.MANIFEST,su:!this.initialized})}catch(t){A.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,s=this.hls.levels[e.level],i=this.getObjectType(e),r={d:1e3*e.duration,ot:i};i!==Un.VIDEO&&i!==Un.AUDIO&&i!=Un.MUXED||(r.br=s.bitrate/1e3,r.tb=this.getTopBandwidth(i)/1e3,r.bl=this.getBufferLength(i)),this.apply(t,r)}catch(t){A.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)}))}}}(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(p.MEDIA_DETACHED,this.onMediaDetached,this),t.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(p.MEDIA_DETACHED,this.onMediaDetached,this),t.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,i;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer}createData(){var t;return{v:1,sf:Bn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){u(e,this.createData());const s=e.ot===Un.INIT||e.ot===Un.VIDEO||e.ot===Un.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce(((t,s)=>(i.includes(s)&&(t[s]=e[s]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),ha(t.headers,e)):t.url=ca(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?Un.TIMED_TEXT:"initSegment"===t.sn?Un.INIT:"audio"===e?Un.AUDIO:"main"===e?this.hls.audioTracks.length?Un.VIDEO:Un.MUXED:void 0}getTopBandwidth(t){let e,s=0;const i=this.hls;if(t===Un.AUDIO)e=i.audioTracks;else{const t=i.maxAutoLevel,s=t>-1?t+1:i.levels.length;e=i.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.hls.media,s=t===Un.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*Xs.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}},contentSteeringController:class{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=A.log.bind(A,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(p.MANIFEST_PARSED,this.onManifestParsed,this),t.on(p.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(p.MANIFEST_PARSED,this.onManifestParsed,this),t.off(p.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Ss&&s.flags===bs){const t=this.levels;let i=this.pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=t.reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),s.resolved||A.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${JSON.stringify(i)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this.pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach((t=>{i-s[t]>3e5&&delete s[t]}));for(let i=0;i0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,ds(e),this.hls.trigger(p.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new k(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=fa(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new es({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,r);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}});function Aa(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Aa):Object.keys(t).reduce(((e,s)=>(e[s]=Aa(t[s]),e)),{}):t}function Ra(t){const e=t.loader;if(e!==va&&e!==ma)A.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=va,t.progressive=!0,t.enableSoftwareAES=!0,A.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let ba;class ka extends ws{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(p.MANIFEST_LOADING,this.onManifestLoading,this),t.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(p.LEVEL_LOADED,this.onLevelLoaded,this),t.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(p.FRAG_BUFFERED,this.onFragBuffered,this),t.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(p.MANIFEST_LOADING,this.onManifestLoading,this),t.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(p.LEVEL_LOADED,this.onLevelLoaded,this),t.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(p.FRAG_BUFFERED,this.onFragBuffered,this),t.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e,h;const d=t.attrs;let{audioCodec:c,videoCodec:u}=t;-1!==(null==(e=c)?void 0:e.indexOf("mp4a.40.34"))&&(ba||(ba=/chrome|firefox/i.test(navigator.userAgent)),ba&&(t.audioCodec=c=void 0)),c&&(t.audioCodec=c=he(c,s)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}(u));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!c),null!=m&&m.length||c&&!se(c,"audio",s)||u&&!se(u,"video",s))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=d,L=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(r[L])if(r[L].uri===t.url||t.attrs["PATHWAY-ID"])r[L].addGroupId("audio",d.AUDIO),r[L].addGroupId("text",d.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=new es(t);r[L]=s,i.push(s)}else{const e=new es(t);r[L]=e,n[L]=1,i.push(e)}})),this.filterAndSortMediaOptions(i,e,a,o,l)}filterAndSortMediaOptions(t,e,s,i,r){let n=[],a=[],o=t;if((s||i)&&r&&(o=o.filter((({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&(!!(r=e)&&Xe.indexOf(r)>-1);var r}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}));if(e.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;n=e.audioTracks.filter((e=>!e.audioCodec||se(e.audioCodec,"audio",t))),wa(n)}e.subtitles&&(a=e.subtitles,wa(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Xe.indexOf(t.videoRange)-Xe.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=ne(t.videoCodec),i=ne(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=ae(t.codecSet),i=ae(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;ts&&s===La.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const c=r&&!i,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:!c&&n.some((t=>!!t.url))};this.hls.trigger(p.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const s=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(p.ERROR,{type:v.OTHER_ERROR,details:y.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&n.details&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===be&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===De){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=this._levels[i];var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));i===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(i,e,n.details)):null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let i=s.uri;if(t)try{i=t.addDirectives(i)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${r?" Pathway "+r:""} ${i}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:e,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const s=this._levels.filter(((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));ds(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function wa(t){const e={};t.forEach((t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++}))}class Da{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=y.KEY_LOAD_ERROR,s,i,r){return new ai({type:v.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=t;for(let t=0;t{r.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var s,i;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const s=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,y.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,y.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(i=a)&&i.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(r.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,y.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,s)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,i=new(0,s.loader)(s);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,i)=>{const{frag:a,keyInfo:o,url:l}=s;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,y.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,y.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,h({url:a.url,data:void 0},t)))},onTimeout:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,y.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,y.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,d)}))}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function Ia(){return self.SourceBuffer||self.WebKitSourceBuffer}function _a(){if(!te())return!1;const t=Ia();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class Ca{constructor(t,e,s,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:s,media:i,stalled:r}=this;if(null===i)return;const{currentTime:n,seeking:a}=i,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==t){if(this.moved=!0,a||(this.nudgeRetry=0),null!==r){if(this.stallReported){const t=self.performance.now()-r;A.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(i.paused&&!a||i.ended||0===i.playbackRate||!Xs.getBuffered(i).length)return void(this.nudgeRetry=0);const h=Xs.bufferInfo(i,n,0),d=h.nextStart||0;if(a){const t=h.len>2,s=!d||e&&e.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;if(!(h.len>0)&&!d)return;const t=Math.max(d,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(c=e.details)?void 0:c.live)?2*e.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||r))return void(i.paused||this._trySkipBufferHole(r))}const u=self.performance.now();if(null===r)return void(this.stalled=u);const f=u-r;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=Xs.bufferInfo(i,n,s.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:s,fragmentTracker:i,media:r}=this;if(null===r)return;const n=r.currentTime,a=i.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-n1e3*s.highBufferWatchdogPeriod&&(A.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);A.warn(i.message),e.trigger(p.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:s,media:i}=this;if(null===i)return 0;const r=i.currentTime,n=Xs.bufferInfo(i,r,0),a=r0&&n.len<1&&i.readyState<3,h=a-r;if(h>0&&(o||l)){if(h>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===r){const t=e.getAppendedFrag(0,De);t&&a1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=fi,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=ui}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ai:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(i))break;this.state=fi;break}if(this.hls.nextLoadLevel!==this.level){this.state=fi;break}break}case pi:{var t;const e=self.performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,s=null==t?void 0:t[e];this.resetStartWhenNotLoaded(s||null),this.state=fi}}}this.state===fi&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=t.nextLoadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(p.BUFFER_EOS,t),void(this.state=Ti)}t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===Ai||l.live&&this.levelLastLoaded!==n)return this.level=r,void(this.state=Ai);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==Vs){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?_:C,e=(t===C?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,De)}u=this.getNextFragmentLoopLoading(u,l,a,De,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);this.fragCurrent=t,i===Gs||i===Hs?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,s)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,De)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let s;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case gi:case mi:case pi:case yi:case Ei:this.state=fi}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new Ca(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;f(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(t,e){let s=!1,i=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&i&&!function(){var t;const e=Ia();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==fi)return;const i=s[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=Ai)}onLevelLoaded(t,e){var s;const{levels:i}=this,r=e.level,n=e.details,a=n.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=i[r],l=this.fragCurrent;!l||this.state!==mi&&this.state!==pi||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(s=o.details)&&s.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(p.LEVEL_UPDATED,{details:n,level:r}),this.state===Ai){if(this.waitForCdnTuneIn(n))return;this.state=fi}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:i,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Cr(this.hls,De,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new zs(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const s=this.altAudio;if(!!!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;s&&(t.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(p.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=e.id,i=!!this.hls.audioTracks[s].url;if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s&&s.type!==De)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ei&&(this.state=fi));const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(t,e){var s;if(e.fatal)this.state=Si;else switch(e.details){case y.FRAG_GAP:case y.FRAG_PARSING_ERROR:case y.FRAG_DECRYPT_ERROR:case y.FRAG_LOAD_ERROR:case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_ERROR:case y.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(De,e);break;case y.LEVEL_LOAD_ERROR:case y.LEVEL_LOAD_TIMEOUT:case y.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ai||(null==(s=e.context)?void 0:s.type)!==be||(this.state=fi);break;case y.BUFFER_APPEND_ERROR:case y.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===y.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case y.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!Xs.getBuffered(t).length){const t=this.state!==fi?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=fi,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==_||this.audioOnly&&!this.altAudio){const t=(e===C?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,De),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e0&&(r{const{hls:i}=this;if(!s||this.fragContextChanged(t))return;e.fragmentError=0,this.state=fi,this.startFragRequested=!1,this.bitrateTest=!1;const r=t.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:d,text:c,id3:u,initSegment:g}=r,{details:m}=h,v=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=yi,g){if(null!=g&&g.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,g.tracks,t,n),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}const t=g.initPTS,e=g.timescale;f(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},i.trigger(p.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:e}))}if(d&&m&&"initSegment"!==o.sn){const t=m.fragments[o.sn-1-m.startSN],e=o.sn===m.startSN,s=!t||o.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:i,startDTS:r,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:r,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,t,i,r,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,e||s)}else{if(!e&&!s)return void this.backtrack(o);o.gap=!0}}if(v){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=v;l&&(l.elementaryStreams[_]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(_,t,e,s,i),this.bufferFragmentData(v,o,l,n)}if(m&&null!=u&&null!=(e=u.samples)&&e.length){const t={id:s,frag:o,details:m,samples:u.samples};i.trigger(p.FRAG_PARSING_METADATA,t)}if(m&&c){const t={id:s,frag:o,details:m,samples:c.samples};i.trigger(p.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,i){if(this.state!==yi)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:r,video:n,audiovideo:a}=e;if(r){let e=t.audioCodec;const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===s.indexOf("firefox")&&(e="mp4a.40.5")}e&&-1!==e.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==r.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),r.levelCodec=e,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${r.codec}]`)}n&&(n.levelCodec=t.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(p.BUFFER_CODECS,e),Object.keys(e).forEach((t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,De)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=fi}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(Xs.isBuffered(t,s)?e=this.getAppendedFrag(s):Xs.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger(p.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(p.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,s=this.currentFrag;if(s&&f(e)&&f(s.programDateTime)){const t=s.programDateTime+1e3*(e-s.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Pa{static get version(){return"1.5.15"}static isMSESupported(){return _a()}static isSupported(){return function(){if(!_a())return!1;const t=te();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(re(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(re(e,"audio")))))}()}static getMediaSource(){return te()}static get Events(){return p}static get ErrorTypes(){return v}static get ErrorDetails(){return y}static get DefaultConfig(){return Pa.defaultConfig?Pa.defaultConfig:La}static set DefaultConfig(t){Pa.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new _r,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){L(t,"debug","log","info","warn","error");try{S.log(`Debug logs enabled for "${e}" in hls.js version 1.5.15`)}catch(t){S=T}}else S=T}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Aa(t),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,n=void 0===e[r],a=[];i.forEach((i=>{const o=`${t}Loading${i}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=s[r].default;switch(e[r]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&A.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${r}": ${JSON.stringify(e[r])}`)})),h(h({},s),e)}(Pa.DefaultConfig,t);this.userConfig=t,e.progressive&&Ra(e);const{abrController:s,bufferController:i,capLevelController:r,errorController:n,fpsController:a}=e,o=new n(this),l=this.abrController=new s(this),d=this.bufferController=new i(this),c=this.capLevelController=new r(this),u=new a(this),f=new Pe(this),g=new We(this),m=e.contentSteeringController,v=m?new m(this):null,y=this.levelController=new ka(this,v),E=new Ys(this),R=new Da(this.config),b=this.streamController=new xa(this,E,R);c.setStreamController(b),u.setStreamController(b);const k=[f,y,b];v&&k.splice(1,0,v),this.networkControllers=k;const w=[l,d,c,u,g,E];this.audioTrackController=this.createController(e.audioTrackController,k);const D=e.audioStreamController;D&&k.push(new D(this,E,R)),this.subtitleTrackController=this.createController(e.subtitleTrackController,k);const I=e.subtitleStreamController;I&&k.push(new I(this,E,R)),this.createController(e.timelineController,w),R.emeController=this.emeController=this.createController(e.emeController,w),this.cmcdController=this.createController(e.cmcdController,w),this.latencyController=this.createController(je,w),this.coreComponents=w,k.push(o);const _=o.onErrorOut;"function"==typeof _&&this.on(p.ERROR,_,o)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(A.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===p.ERROR;this.trigger(p.ERROR,{type:v.OTHER_ERROR,details:y.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){A.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){A.log("attachMedia"),this._media=t,this.trigger(p.MEDIA_ATTACHING,{media:t})}detachMedia(){A.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,s=this.url,i=this.url=o.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,A.log(`loadSource:${i}`),e&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(p.MANIFEST_LOADING,{url:t})}startLoad(t=-1){A.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach((e=>{e.startLoad(t)}))}stopLoad(){A.log("stopLoad"),this.started=!1,this.networkControllers.forEach((t=>{t.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.stopLoad()}))}swapAudioCodec(){A.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){A.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){A.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){A.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){A.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){A.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){A.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(A.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return qe.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let i=0;i=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=s)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Pa.defaultConfig=void 0;class Ma{constructor(){this._ranges=[]}get length(){return this._ranges.length}start(t){if(t<0||t>=this._ranges.length)throw new DOMException("Invalid index","IndexSizeError");return this._ranges[t].start}end(t){if(t<0||t>=this._ranges.length)throw new DOMException("Invalid index","IndexSizeError");return this._ranges[t].end}_addRange(t,e){this._ranges.push({start:t,end:e}),this._normalizeRanges()}_removeRange(t,e){let s=[];for(let i of this._ranges)i.end<=t||i.start>=e?s.push(i):i.starte?(s.push({start:i.start,end:t}),s.push({start:e,end:i.end})):i.start>=t&&i.end<=e||(i.startt&&i.end<=e?s.push({start:i.start,end:t}):i.start>=t&&i.starte&&s.push({start:e,end:i.end}));this._ranges=s}_normalizeRanges(){this._ranges.sort(((t,e)=>t.start-e.start));let t=[];for(let e of this._ranges)if(0===t.length)t.push(e);else{let s=t[t.length-1];e.start<=s.end?s.end=Math.max(s.end,e.end):t.push(e)}this._ranges=t}}class Fa extends EventTarget{constructor(t="",e="",s=""){super(),this.kind=t,this.label=e,this.language=s,this.mode="disabled",this.cues=new Oa,this.activeCues=new Oa}addCue(t){this.cues._add(t)}removeCue(t){this.cues._remove(t)}}class Oa{constructor(){this._cues=[]}get length(){return this._cues.length}item(t){return this._cues[t]}getCueById(t){return this._cues.find((e=>e.id===t))||null}_add(t){this._cues.push(t)}_remove(t){const e=this._cues.indexOf(t);-1!==e&&this._cues.splice(e,1)}[Symbol.iterator](){return this._cues[Symbol.iterator]()}}class Na extends EventTarget{constructor(){super(),this._tracks=[]}get length(){return this._tracks.length}item(t){return this._tracks[t]}_add(t){this._tracks.push(t),this.dispatchEvent(new Event("addtrack"))}_remove(t){const e=this._tracks.indexOf(t);-1!==e&&(this._tracks.splice(e,1),this.dispatchEvent(new Event("removetrack")))}[Symbol.iterator](){return this._tracks[Symbol.iterator]()}}class Ua extends EventTarget{constructor(t){super(),this.instanceId=t,this.bridgeId=window.nextInternalId,window.nextInternalId+=1,window.bridgeObjectMap[this.bridgeId]=this,this._currentTime=0,this.duration=NaN,this.paused=!0,this._playbackRate=1,this.volume=1,this.muted=!1,this.readyState=0,this.networkState=0,this.buffered=new Ma,this.seeking=!1,this.loop=!1,this.autoplay=!1,this.controls=!1,this.error=null,this._src="",this.videoWidth=0,this.videoHeight=0,this.textTracks=new Na,this.isWaiting=!1,this.currentMedia=null,window.bridgeInvokeAsync(this.bridgeId,"VideoElement","constructor",{instanceId:this.instanceId}),setTimeout((()=>{this.readyState=4,this.dispatchEvent(new Event("loadedmetadata")),this.dispatchEvent(new Event("loadeddata")),this.dispatchEvent(new Event("canplay")),this.dispatchEvent(new Event("canplaythrough"))}),0)}get currentTime(){return this._currentTime}set currentTime(t){this._currentTime!=t&&(this._currentTime=t,this.dispatchEvent(new Event("seeking")),window.bridgeInvokeAsync(this.bridgeId,"VideoElement","setCurrentTime",{instanceId:this.instanceId,currentTime:t}).then((t=>{this.dispatchEvent(new Event("seeked"))})))}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,window.bridgeInvokeAsync(this.bridgeId,"VideoElement","setPlaybackRate",{instanceId:this.instanceId,playbackRate:t}).then((t=>{}))}get src(){return this._src}set src(t){this.currentMedia&&this.currentMedia.removeEventListener("bufferChanged",!1),this._src=t;var e=window.mediaSourceMap[this._src];this.currentMedia=e,e&&(e.addEventListener("bufferChanged",(()=>{this.updateBufferedFromMediaSource()}),!1),window.bridgeInvokeAsync(this.bridgeId,"VideoElement","setMediaSource",{instanceId:this.instanceId,mediaSourceId:e.bridgeId}).then((t=>{})))}removeAttribute(t){"src"===t&&(this._src="")}querySelectorAll(t){return document.createDocumentFragment().querySelectorAll("*")}updateBufferedFromMediaSource(){var t=this.currentMedia;this.buffered._ranges=t?t.getBufferedRanges():[]}bridgeUpdateStatus(t){var e=!t.isPlaying,s=t.isWaiting,i=t.currentTime;this.paused!=e&&(this.paused=e,e?this.dispatchEvent(new Event("pause")):(this.dispatchEvent(new Event("play")),this.dispatchEvent(new Event("playing")))),this.isWaiting!=s&&(this.isWaiting=s,s&&this.dispatchEvent(new Event("waiting"))),this._currentTime!=i&&(this._currentTime=i,this.dispatchEvent(new Event("timeupdate")))}play(){return this.paused?window.bridgeInvokeAsync(this.bridgeId,"VideoElement","play",{instanceId:this.instanceId}).then((t=>{this.dispatchEvent(new Event("play")),this.dispatchEvent(new Event("playing"))})):Promise.resolve()}pause(){if(!this.paused)return this.paused=!0,this.dispatchEvent(new Event("pause")),window.bridgeInvokeAsync(this.bridgeId,"VideoElement","pause",{instanceId:this.instanceId}).then((t=>{}))}canPlayType(t){return"probably"}addTextTrack(t,e,s){const i=new Fa(t,e,s);return this.textTracks._add(i),i}load(){}notifySeeked(){this.dispatchEvent(new Event("seeking")),this.dispatchEvent(new Event("seeked"))}}function Ba(t){const e=Array.from(t,(t=>String.fromCodePoint(t))).join("");return btoa(e)}class $a extends EventTarget{constructor(){super(),this._buffers=[]}_add(t){this._buffers.push(t),this.dispatchEvent(new Event("addsourcebuffer"))}_remove(t){const e=this._buffers.indexOf(t);return-1!==e&&(this._buffers.splice(e,1),this.dispatchEvent(new Event("removesourcebuffer")),!0)}get length(){return this._buffers.length}item(t){return this._buffers[t]}[Symbol.iterator](){return this._buffers[Symbol.iterator]()}}class Ga extends EventTarget{constructor(t,e){super(),this.mediaSource=t,this.mimeType=e,this.updating=!1,this.buffered=new Ma,this.timestampOffset=0,this.appendWindowStart=0,this.appendWindowEnd=1/0,this.bridgeId=window.nextInternalId,window.nextInternalId+=1,window.bridgeObjectMap[this.bridgeId]=this,window.bridgeInvokeAsync(this.bridgeId,"SourceBuffer","constructor",{mediaSourceId:this.mediaSource.bridgeId,mimeType:e})}appendBuffer(t){if(this.updating)throw new DOMException("SourceBuffer is updating","InvalidStateError");this.updating=!0,this.dispatchEvent(new Event("updatestart")),window.bridgeInvokeAsync(this.bridgeId,"SourceBuffer","appendBuffer",{data:Ba(t)}).then((t=>{const e=t.ranges;for(var s=[],i=0;i{})))}remove(t,e){if(this.updating)throw new DOMException("SourceBuffer is updating","InvalidStateError");this.updating=!0,this.dispatchEvent(new Event("updatestart")),window.bridgeInvokeAsync(this.bridgeId,"SourceBuffer","remove",{start:t,end:e}).then((t=>{const e=t.ranges;for(var s=[],i=0;i{this.readyState="open",this.dispatchEvent(new Event("sourceopen"))}),0)}static isTypeSupported(t){return!0}emitUpdatedBuffer(){this.dispatchEvent(new Event("bufferChanged"))}getBufferedRanges(){return 0!=this.sourceBuffers._buffers.length?this.sourceBuffers._buffers[0].buffered._ranges:[]}addSourceBuffer(t){if("open"!==this.readyState)throw new DOMException("MediaSource is not open","InvalidStateError");const e=new Ga(this,t);return this.sourceBuffers._add(e),this.activeSourceBuffers._add(e),this.dispatchEvent(new Event("bufferChanged")),window.bridgeInvokeAsync(this.bridgeId,"MediaSource","updateSourceBuffers",{ids:this.sourceBuffers._buffers.map((t=>t.bridgeId))}).then((t=>{})),e}removeSourceBuffer(t){if(!this.sourceBuffers._remove(t))throw new DOMException("SourceBuffer not found","NotFoundError");this.activeSourceBuffers._remove(t),this.dispatchEvent(new Event("bufferChanged")),window.bridgeInvokeAsync(this.bridgeId,"MediaSource","updateSourceBuffers",{ids:this.sourceBuffers._buffers.map((t=>t.bridgeId))}).then((t=>{}))}endOfStream(t){if("open"!==this.readyState)throw new DOMException("MediaSource is not open","InvalidStateError");this.readyState="ended",this.dispatchEvent(new Event("sourceended"))}_reopen(){"open"!==this.readyState&&(this.readyState="open",this.dispatchEvent(new Event("sourceopen")))}set duration(t){if("closed"===this.readyState)throw new DOMException("MediaSource is closed","InvalidStateError");this._duration=t,window.bridgeInvokeAsync(this.bridgeId,"MediaSource","setDuration",{duration:t}).then((t=>{}))}get duration(){return this._duration}}class Ha extends EventTarget{constructor(){super(),this.bridgeId=window.nextInternalId,window.nextInternalId+=1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.responseXML=null,this._responseData=null,this.onreadystatechange=null,this._requestHeaders={},this._responseHeaders={},this._method="",this._url="",this._async=!0,this._user=null,this._password=null,this._responseType=""}open(t,e,s=!0,i=null,r=null){this._method=t,this._url=e,this._async=s,this._user=i,this._password=r,this.readyState=1,this._triggerReadyStateChange()}setRequestHeader(t,e){this._requestHeaders[t]=e}getResponseHeader(t){return this._responseHeaders[t.toLowerCase()]||null}getAllResponseHeaders(){return Object.entries(this._responseHeaders).map((([t,e])=>`${t}: ${e}`)).join("\r\n")}send(t=null){this.readyState=2,this._triggerReadyStateChange(),this.readyState=3,this._triggerReadyStateChange(),this.dispatchEvent(new Event("loadstart")),window.bridgeInvokeAsync(this.bridgeId,"XMLHttpRequest","load",{id:this.bridgeId,url:this._url,requestHeaders:this._requestHeaders}).then((t=>{t.error?this.dispatchEvent(new Event("error")):(this.status=t.status,this.statusText=t.statusText,t.responseData?("arraybuffer"===this._responseType?this._responseData=function(t){for(var e=atob(t),s=new Uint8Array(e.length),i=0;i{this.refreshPlayerStatus()})),this.video.addEventListener("pause",(()=>{this.refreshPlayerStatus()})),this.video.addEventListener("seeking",(()=>{this.refreshPlayerStatus()})),this.video.addEventListener("waiting",(()=>{this.refreshPlayerStatus()})),this.hls=new Pa({startLevel:0,testBandwidth:!1,debug:t.debug||!0,autoStartLoad:!1,backBufferLength:30,maxBufferLength:60,maxMaxBufferLength:60,maxFragLookUpTolerance:.001,nudgeMaxRetry:1e4}),this.hls.on(Pa.Events.MANIFEST_PARSED,(()=>{this.isManifestParsed=!0,this.refreshPlayerStatus()})),this.hls.on(Pa.Events.LEVEL_SWITCHED,(()=>{this.refreshPlayerStatus()})),this.hls.on(Pa.Events.LEVELS_UPDATED,(()=>{this.refreshPlayerStatus()})),this.hls.loadSource(t.urlPrefix+"master.m3u8"),this.hls.attachMedia(this.video)}playerLoad(t){this.hls.startLevel=t,this.hls.startLoad(-1,!1)}playerPlay(){this.video.play()}playerPause(){this.video.pause()}playerSetBaseRate(t){this.video.playbackRate=t}playerSetLevel(t){this.hls.currentLevel=t>=0?t:-1}playerSeek(t){this.video.currentTime=t}playerSetIsMuted(t){this.video.muted=t}getLevels(){for(var t=[],e=0;e2&&(t=!0),Va(this.id,"playerStatus",{isReady:this.isManifestParsed,isPlaying:!this.video.paused,rate:t?this.video.playbackRate:0,defaultRate:this.video.playbackRate,levels:this.getLevels(),currentLevel:this.hls.currentLevel}),this.refreshPlayerCurrentTime(),t?null==this.currentTimeUpdateTimeout&&(this.currentTimeUpdateTimeout=setTimeout((()=>{this.refreshPlayerCurrentTime()}),200)):null!=this.currentTimeUpdateTimeout&&(clearTimeout(this.currentTimeUpdateTimeout),this.currentTimeUpdateTimeout=null),this.notifySeekedOnNextStatusUpdate&&(this.notifySeekedOnNextStatusUpdate=!1,this.video.notifySeeked())}playerNotifySeekedOnNextStatusUpdate(){this.notifySeekedOnNextStatusUpdate=!0}refreshPlayerCurrentTime(){Va(this.id,"playerCurrentTime",{value:this.video.currentTime}),this.currentTimeUpdateTimeout=setTimeout((()=>{this.refreshPlayerCurrentTime()}),200)}}window.invokeOnLoad=function(){Va(this.id,"windowOnLoad",{})},window.onload=()=>{window.invokeOnLoad()},window.hlsPlayer_instances={},window.hlsPlayer_makeInstance=function(t){window.hlsPlayer_instances[t]=new Ya(t)},window.hlsPlayer_destroyInstance=function(t){const e=window.hlsPlayer_instances[t];e&&(delete window.hlsPlayer_instances[t],e.video.pause(),e.hls.destroy())},window.bridgeInvokeCallback=function(t,e){const s=window.bridgeCallbackMap[t];s&&s(e)}})(); \ No newline at end of file diff --git a/submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js b/submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js new file mode 100644 index 0000000000..c2942c473c --- /dev/null +++ b/submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js @@ -0,0 +1,2 @@ +/*! For license information please see index.bundle.js.LICENSE.txt */ +(()=>{var t={914:function(t,e,s){var i;t=s.nmd(t),function(){var r=e,n=(t&&t.exports,"object"==typeof s.g&&s.g);n.global!==n&&n.window;var a=function(t){this.message=t};(a.prototype=new Error).name="InvalidCharacterError";var o=function(t){throw new a(t)},l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=/[\t\n\f\r ]/g,d={encode:function(t){t=String(t),/[^\0-\xFF]/.test(t)&&o("The string to be encoded contains characters outside of the Latin1 range.");for(var e,s,i,r,n=t.length%3,a="",h=-1,d=t.length-n;++h>18&63)+l.charAt(r>>12&63)+l.charAt(r>>6&63)+l.charAt(63&r);return 2==n?(e=t.charCodeAt(h)<<8,s=t.charCodeAt(++h),a+=l.charAt((r=e+s)>>10)+l.charAt(r>>4&63)+l.charAt(r<<2&63)+"="):1==n&&(r=t.charCodeAt(h),a+=l.charAt(r>>2)+l.charAt(r<<4&63)+"=="),a},decode:function(t){var e=(t=String(t).replace(h,"")).length;e%4==0&&(e=(t=t.replace(/==?$/,"")).length),(e%4==1||/[^+a-zA-Z0-9/]/.test(t))&&o("Invalid character: the string to be decoded is not correctly encoded.");for(var s,i,r=0,n="",a=-1;++a>(-2*r&6)));return n},version:"1.0.0"};void 0===(i=function(){return d}.call(e,s,e,t))||(t.exports=i)}()},537:(t,e,s)=>{const i="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==s.g&&s.g,r=function(){try{new i.Event("")}catch(t){return!0}return!1}(),n=function(){try{new i.EventTarget}catch(t){return!0}return!1}();r&&(i.Event=function(t,e){this.bubbles=!!e&&!!e.bubbles,this.cancelable=!!e&&!!e.cancelable,this.composed=!!e&&!!e.composed,this.type=t}),n&&(i.EventTarget=function(){function t(){this.__listeners=new Map}return t.prototype=Object.create(Object.prototype),t.prototype.addEventListener=function(t,e,s){if(arguments.length<2)throw new TypeError("TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only "+arguments.length+" present.");const i=this.__listeners,r=t.toString();i.has(r)||i.set(r,new Map);const n=i.get(r);n.has(e)||n.set(e,s)},t.prototype.removeEventListener=function(t,e,s){if(arguments.length<2)throw new TypeError("TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only "+arguments.length+" present.");const i=this.__listeners,r=t.toString();if(i.has(r)){const t=i.get(r);t.has(e)&&t.delete(e)}},t.prototype.dispatchEvent=function(t){if(!(t instanceof Event))throw new TypeError("Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.");const e=t.type,s=this.__listeners.get(e);if(s)for(var i of s.entries()){const e=i[0],r=i[1];try{"function"==typeof e?e.call(this,t):e&&"function"==typeof e.handleEvent&&e.handleEvent(t)}catch(t){setTimeout((()=>{throw t}))}r&&r.once&&s.delete(e)}return!0},t}())}},e={};function s(i){var r=e[i];if(void 0!==r)return r.exports;var n=e[i]={id:i,loaded:!1,exports:{}};return t[i].call(n.exports,n,n.exports,s),n.loaded=!0,n.exports}s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),s.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),(()=>{"use strict";s(537);var t=s(914);class e{constructor(){this._ranges=[]}get length(){return this._ranges.length}start(t){if(t<0||t>=this._ranges.length)throw new DOMException("Invalid index","IndexSizeError");return this._ranges[t].start}end(t){if(t<0||t>=this._ranges.length)throw new DOMException("Invalid index","IndexSizeError");return this._ranges[t].end}_addRange(t,e){this._ranges.push({start:t,end:e}),this._normalizeRanges()}_removeRange(t,e){let s=[];for(let i of this._ranges)i.end<=t||i.start>=e?s.push(i):i.starte?(s.push({start:i.start,end:t}),s.push({start:e,end:i.end})):i.start>=t&&i.end<=e||(i.startt&&i.end<=e?s.push({start:i.start,end:t}):i.start>=t&&i.starte&&s.push({start:e,end:i.end}));this._ranges=s}_normalizeRanges(){this._ranges.sort(((t,e)=>t.start-e.start));let t=[];for(let e of this._ranges)if(0===t.length)t.push(e);else{let s=t[t.length-1];e.start<=s.end?s.end=Math.max(s.end,e.end):t.push(e)}this._ranges=t}}class i extends EventTarget{constructor(t="",e="",s=""){super(),this.kind=t,this.label=e,this.language=s,this.mode="disabled",this.cues=new r,this.activeCues=new r}addCue(t){this.cues._add(t)}removeCue(t){this.cues._remove(t)}}class r{constructor(){this._cues=[]}get length(){return this._cues.length}item(t){return this._cues[t]}getCueById(t){return this._cues.find((e=>e.id===t))||null}_add(t){this._cues.push(t)}_remove(t){const e=this._cues.indexOf(t);-1!==e&&this._cues.splice(e,1)}[Symbol.iterator](){return this._cues[Symbol.iterator]()}}class n extends EventTarget{constructor(){super(),this._tracks=[]}get length(){return this._tracks.length}item(t){return this._tracks[t]}_add(t){this._tracks.push(t),this.dispatchEvent(new Event("addtrack"))}_remove(t){const e=this._tracks.indexOf(t);-1!==e&&(this._tracks.splice(e,1),this.dispatchEvent(new Event("removetrack")))}[Symbol.iterator](){return this._tracks[Symbol.iterator]()}}class a extends EventTarget{constructor(t){super(),this.instanceId=t,this.bridgeId=window.nextInternalId,window.nextInternalId+=1,window.bridgeObjectMap[this.bridgeId]=this,this._currentTime=0,this.duration=NaN,this.paused=!0,this._playbackRate=1,this.volume=1,this.muted=!1,this.readyState=0,this.networkState=0,this.buffered=new e,this.seeking=!1,this.loop=!1,this.autoplay=!1,this.controls=!1,this.error=null,this._src="",this.videoWidth=0,this.videoHeight=0,this.textTracks=new n,this.isWaiting=!1,this.currentMedia=null,window.bridgeInvokeAsync(this.bridgeId,"VideoElement","constructor",{instanceId:this.instanceId}),setTimeout((()=>{this.readyState=4,this.dispatchEvent(new Event("loadedmetadata")),this.dispatchEvent(new Event("loadeddata")),this.dispatchEvent(new Event("canplay")),this.dispatchEvent(new Event("canplaythrough"))}),0)}get currentTime(){return this._currentTime}set currentTime(t){this._currentTime!=t&&(this._currentTime=t,this.dispatchEvent(new Event("seeking")),window.bridgeInvokeAsync(this.bridgeId,"VideoElement","setCurrentTime",{instanceId:this.instanceId,currentTime:t}).then((t=>{this.dispatchEvent(new Event("seeked"))})))}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,window.bridgeInvokeAsync(this.bridgeId,"VideoElement","setPlaybackRate",{instanceId:this.instanceId,playbackRate:t}).then((t=>{}))}get src(){return this._src}set src(t){this.currentMedia&&this.currentMedia.removeEventListener("bufferChanged",!1),this._src=t;var e=window.mediaSourceMap[this._src];this.currentMedia=e,e&&(e.addEventListener("bufferChanged",(()=>{this.updateBufferedFromMediaSource()}),!1),window.bridgeInvokeAsync(this.bridgeId,"VideoElement","setMediaSource",{instanceId:this.instanceId,mediaSourceId:e.bridgeId}).then((t=>{})))}removeAttribute(t){"src"===t&&(this._src="")}querySelectorAll(t){if(s.g.isJsCore)return[];return document.createDocumentFragment().querySelectorAll("*")}removeChild(t){}updateBufferedFromMediaSource(){var t=this.currentMedia;this.buffered._ranges=t?t.getBufferedRanges():[]}bridgeUpdateStatus(t){var e=!t.isPlaying,s=t.isWaiting,i=t.currentTime;this.paused!=e&&(this.paused=e,e?this.dispatchEvent(new Event("pause")):(this.dispatchEvent(new Event("play")),this.dispatchEvent(new Event("playing")))),this.isWaiting!=s&&(this.isWaiting=s,s&&this.dispatchEvent(new Event("waiting"))),this._currentTime!=i&&(this._currentTime=i,this.dispatchEvent(new Event("timeupdate")))}play(){return this.paused?window.bridgeInvokeAsync(this.bridgeId,"VideoElement","play",{instanceId:this.instanceId}).then((t=>{this.dispatchEvent(new Event("play")),this.dispatchEvent(new Event("playing"))})):Promise.resolve()}pause(){if(!this.paused)return this.paused=!0,this.dispatchEvent(new Event("pause")),window.bridgeInvokeAsync(this.bridgeId,"VideoElement","pause",{instanceId:this.instanceId}).then((t=>{}))}canPlayType(t){return"probably"}addTextTrack(t,e,s){const r=new i(t,e,s);return this.textTracks._add(r),r}load(){}notifySeeked(){this.dispatchEvent(new Event("seeking")),this.dispatchEvent(new Event("seeked"))}}function o(t){const e=Array.from(t,(t=>String.fromCodePoint(t))).join("");return btoa(e)}class l extends EventTarget{constructor(){super(),this._buffers=[]}_add(t){this._buffers.push(t),this.dispatchEvent(new Event("addsourcebuffer"))}_remove(t){const e=this._buffers.indexOf(t);return-1!==e&&(this._buffers.splice(e,1),this.dispatchEvent(new Event("removesourcebuffer")),!0)}get length(){return this._buffers.length}item(t){return this._buffers[t]}[Symbol.iterator](){return this._buffers[Symbol.iterator]()}}class h extends EventTarget{constructor(t,s){super(),this.mediaSource=t,this.mimeType=s,this.updating=!1,this.buffered=new e,this.timestampOffset=0,this.appendWindowStart=0,this.appendWindowEnd=1/0,this.bridgeId=window.nextInternalId,window.nextInternalId+=1,window.bridgeObjectMap[this.bridgeId]=this,window.bridgeInvokeAsync(this.bridgeId,"SourceBuffer","constructor",{mediaSourceId:this.mediaSource.bridgeId,mimeType:s})}appendBuffer(t){if(this.updating)throw new DOMException("SourceBuffer is updating","InvalidStateError");this.updating=!0,this.dispatchEvent(new Event("updatestart")),window.bridgeInvokeAsync(this.bridgeId,"SourceBuffer","appendBuffer",{data:o(t)}).then((t=>{const e=t.ranges;for(var s=[],i=0;i{})))}remove(t,e){if(this.updating)throw new DOMException("SourceBuffer is updating","InvalidStateError");this.updating=!0,this.dispatchEvent(new Event("updatestart")),window.bridgeInvokeAsync(this.bridgeId,"SourceBuffer","remove",{start:t,end:e}).then((t=>{const e=t.ranges;for(var s=[],i=0;i{this.readyState="open",this.dispatchEvent(new Event("sourceopen"))}),0)}static isTypeSupported(t){return!0}emitUpdatedBuffer(){this.dispatchEvent(new Event("bufferChanged"))}getBufferedRanges(){return 0!=this.sourceBuffers._buffers.length?this.sourceBuffers._buffers[0].buffered._ranges:[]}addSourceBuffer(t){if("open"!==this.readyState)throw new DOMException("MediaSource is not open","InvalidStateError");const e=new h(this,t);return this.sourceBuffers._add(e),this.activeSourceBuffers._add(e),this.dispatchEvent(new Event("bufferChanged")),window.bridgeInvokeAsync(this.bridgeId,"MediaSource","updateSourceBuffers",{ids:this.sourceBuffers._buffers.map((t=>t.bridgeId))}).then((t=>{})),e}removeSourceBuffer(t){if(!this.sourceBuffers._remove(t))throw new DOMException("SourceBuffer not found","NotFoundError");this.activeSourceBuffers._remove(t),this.dispatchEvent(new Event("bufferChanged")),window.bridgeInvokeAsync(this.bridgeId,"MediaSource","updateSourceBuffers",{ids:this.sourceBuffers._buffers.map((t=>t.bridgeId))}).then((t=>{}))}endOfStream(t){if("open"!==this.readyState)throw new DOMException("MediaSource is not open","InvalidStateError");this.readyState="ended",this.dispatchEvent(new Event("sourceended"))}_reopen(){"open"!==this.readyState&&(this.readyState="open",this.dispatchEvent(new Event("sourceopen")))}set duration(t){if("closed"===this.readyState)throw new DOMException("MediaSource is closed","InvalidStateError");this._duration=t,window.bridgeInvokeAsync(this.bridgeId,"MediaSource","setDuration",{duration:t}).then((t=>{}))}get duration(){return this._duration}}class c extends EventTarget{constructor(){super(),this.bridgeId=window.nextInternalId,window.nextInternalId+=1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.responseXML=null,this._responseData=null,this.onreadystatechange=null,this._requestHeaders={},this._responseHeaders={},this._method="",this._url="",this._async=!0,this._user=null,this._password=null,this._responseType=""}open(t,e,s=!0,i=null,r=null){this._method=t,this._url=e,this._async=s,this._user=i,this._password=r,this.readyState=1,this._triggerReadyStateChange()}setRequestHeader(t,e){this._requestHeaders[t]=e}getResponseHeader(t){return this._responseHeaders[t.toLowerCase()]||null}getAllResponseHeaders(){return Object.entries(this._responseHeaders).map((([t,e])=>`${t}: ${e}`)).join("\r\n")}send(t=null){this.readyState=2,this._triggerReadyStateChange(),this.readyState=3,this._triggerReadyStateChange(),this.dispatchEvent(new Event("loadstart")),window.bridgeInvokeAsync(this.bridgeId,"XMLHttpRequest","load",{id:this.bridgeId,url:this._url,requestHeaders:this._requestHeaders}).then((t=>{t.error?this.dispatchEvent(new Event("error")):(this.status=t.status,this.statusText=t.statusText,t.responseData?("arraybuffer"===this._responseType?this._responseData=function(t){for(var e=atob(t),s=new Uint8Array(e.length),i=0;i`):C}(e)}))}const F=P,O=/^(\d+)x(\d+)$/,N=/(.+?)=(".*?"|.*?)(?:,|$)/g;class U{constructor(t){"string"==typeof t&&(t=U.parseAttrList(t)),R(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const s=new Uint8Array(e.length/2);for(let t=0;tNumber.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=O.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const s={};for(N.lastIndex=0;null!==(e=N.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));s[e[1].trim()]=t}return s}}function B(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class ${constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){F.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=R(new U({}),s,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);b(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(b(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&b(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class G{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var K="audio",H="video",V="audiovideo";class Y{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[K]:null,[H]:null,[V]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=E.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class W extends Y{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new G,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!b(this.programDateTime))return null;const t=b(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[K]=null,t[H]=null,t[V]=null}}class j extends Y{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new G,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class q{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&b(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function X(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function z(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=X(r)):s=function(t){const e=Q(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}function Q(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const J="undefined"!=typeof self?self:void 0;var Z={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},tt="org.w3.clearkey",et="com.apple.streamingkeydelivery",st="com.microsoft.playready",it="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function rt(t){switch(t){case et:return Z.FAIRPLAY;case st:return Z.PLAYREADY;case it:return Z.WIDEVINE;case tt:return Z.CLEARKEY}}var nt="1077efecc0b24d02ace33c1e52e2fb4b",at="e2719d58a985b3c9781ab030af78d30e",ot="9a04f07998404286ab92e65be0885f95",lt="edef8ba979d64acea3c827dcd51d21ed";function ht(t){return t===lt?Z.WIDEVINE:t===ot?Z.PLAYREADY:t===nt||t===at?Z.CLEARKEY:void 0}function dt(t){switch(t){case Z.FAIRPLAY:return et;case Z.PLAYREADY:return st;case Z.WIDEVINE:return it;case Z.CLEARKEY:return tt}}function ct(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[Z.FAIRPLAY,Z.WIDEVINE,Z.PLAYREADY,Z.CLEARKEY].filter((t=>!!e[t])):[];return!i[Z.WIDEVINE]&&s&&i.push(Z.WIDEVINE),i}const ut=null!=J&&null!=(ft=J.navigator)&&ft.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ft;function gt(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const mt=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,pt=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,vt=(t,e)=>{const s=e;let i=0;for(;mt(t,e);){i+=10;i+=yt(t,e+6),pt(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(s,s+i)},yt=(t,e)=>{let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s},Et=(t,e)=>mt(t,e)&&yt(t,e+6)+10<=t.length-e,Tt=t=>{const e=At(t);for(let t=0;tt&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,Lt=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=yt(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},At=t=>{let e=0;const s=[];for(;mt(t,e);){const i=yt(t,e+6);e+=10;const r=e+i;for(;e+8"PRIV"===t.type?bt(t):"W"===t.type[0]?kt(t):wt(t),bt=t=>{if(t.size<2)return;const e=It(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},wt=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=It(t.data.subarray(e),!0);e+=s.length+1;const i=It(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=It(t.data.subarray(1));return{key:t.type,data:e}},kt=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=It(t.data.subarray(e),!0);e+=s.length+1;const i=It(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=It(t.data);return{key:t.type,data:e}},Dt=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}},It=(t,e=!1)=>{const s=Ct();if(s){const i=s.decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let r,n,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=t[l++],o+=String.fromCharCode((31&r)<<6|63&n);break;case 14:n=t[l++],a=t[l++],o+=String.fromCharCode((15&r)<<12|(63&n)<<6|63&a)}}return o};let _t;function Ct(){if(!navigator.userAgent.includes("PlayStation 4"))return _t||void 0===self.TextDecoder||(_t=new self.TextDecoder("utf-8")),_t}const xt=function(t){let e="";for(let s=0;s>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function Kt(t,e){const s=[];if(!e.length)return s;const i=t.byteLength;for(let r=0;r1?r+n:i;if(Ot(t.subarray(r+4,r+8))===e[0])if(1===e.length)s.push(t.subarray(r+8,a));else{const i=Kt(t.subarray(r+8,a),e.slice(1));i.length&&Mt.apply(s,i)}r=a}return s}function Ht(t){const e=[],s=t[0];let i=8;const r=Ut(t,i);i+=4;let n=0,a=0;0===s?(n=Ut(t,i),a=Ut(t,i+4),i+=8):(n=Bt(t,i),a=Bt(t,i+8),i+=16),i+=2;let o=t.length+a;const l=Nt(t,i);i+=2;for(let s=0;s>>31)return F.warn("SIDX has hierarchical references (not supported)"),null;const l=Ut(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function Vt(t){const e=[],s=Kt(t,["moov","trak"]);for(let t=0;t{const s=Ut(t,4),i=e[s];i&&(i.default={duration:Ut(t,12),flags:Ut(t,20)})})),e}function Yt(t){const e=t.subarray(8),s=e.subarray(86),i=Ot(e.subarray(4,8));let r=i;const n="enca"===i||"encv"===i;if(n){const t=Kt(e,[i])[0];Kt(t.subarray("enca"===i?28:78),["sinf"]).forEach((t=>{const e=Kt(t,["schm"])[0];if(e){const s=Ot(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=Kt(t,["frma"])[0];e&&(r=Ot(e))}}}))}switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Kt(s,["avcC"])[0];r+="."+jt(t[1])+jt(t[2])+jt(t[3]);break}case"mp4a":{const t=Kt(e,[i])[0],s=Kt(t.subarray(28),["esds"])[0];if(s&&s.length>12){let t=4;if(3!==s[t++])break;t=Wt(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=Wt(s,t);const i=s[t++];if(64!==i)break;if(r+="."+jt(i),t+=12,5!==s[t++])break;t=Wt(s,t);const n=s[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&s[t])>>5)),r+="."+a}break}case"hvc1":case"hev1":{const t=Kt(s,["hvcC"])[0],e=t[1],i=["","A","B","C"][e>>6],n=31&e,a=Ut(t,2),o=(32&e)>>5?"H":"L",l=t[12],h=t.subarray(6,12);r+="."+i+n,r+="."+a.toString(16).toUpperCase(),r+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}r+=d;break}case"dvh1":case"dvhe":{const t=Kt(s,["dvcC"])[0],e=t[2]>>1&127,i=t[2]<<5&32|t[3]>>3&31;r+="."+qt(e)+"."+qt(i);break}case"vp09":{const t=Kt(s,["vpcC"])[0],e=t[4],i=t[5],n=t[6]>>4&15;r+="."+qt(e)+"."+qt(i)+"."+qt(n);break}case"av01":{const t=Kt(s,["av1C"])[0],e=t[1]>>>5,i=31&t[1],n=t[2]>>>7?"H":"M",a=(64&t[2])>>6,o=(32&t[2])>>5,l=2===e&&a?o?12:10:a?10:8,h=(16&t[2])>>4,d=(8&t[2])>>3,c=(4&t[2])>>2,u=3&t[2],f=1,g=1,m=1,p=0;r+="."+e+"."+qt(i)+n+"."+qt(l)+"."+h+"."+d+c+u+"."+qt(f)+"."+qt(g)+"."+qt(m)+"."+p;break}}return{codec:r,encrypted:n}}function Wt(t,e){const s=e+5;for(;128&t[e++]&&e{const l=o.byteOffset-8;Kt(o,["traf"]).map((o=>{const h=Kt(o,["tfdt"]).map((t=>{const e=t[0];let s=Ut(t,4);return 1===e&&(s*=Math.pow(2,32),s+=Ut(t,8)),s/r}))[0];return void 0!==h&&(t=h),Kt(o,["tfhd"]).map((h=>{const d=Ut(h,4),c=16777215&Ut(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=Ut(h,p),p+=4),f&&(g=Ut(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),s=e<0?t:t.substring(0,e);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(e.codec)),Kt(o,["trun"]).map((n=>{const o=n[0],h=16777215&Ut(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const L=Ut(n,4);let A=8;d&&(c=Ut(n,A),A+=4),f&&(A+=4);let R=c+l;for(let l=0;l>1&63;return 39===t||40===t}return 6===(31&e)}function te(t,e,s,i){const r=ee(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(ot){F.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Nt(r,e);if(e+=2,49===t){const t=Ut(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=xt(new Uint8Array(n,s+12,16)),o=t.getUint32(28);let l=null,h=null;if(0===r){if(e-32>8*(15-s)&255;return e}(t);return new ne(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=z(this.uri);if(e)switch(this.keyFormat){case it:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case st:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=se(t,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(s)),r=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=X(t).subarray(0,16);!function(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=re[this.uri];if(!t){const e=Object.keys(re).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),re[this.uri]=t}this.keyId=t}return this}}const ae=/\{\$([a-zA-Z0-9-_]+)\}/g;function oe(t){return ae.test(t)}function le(t,e,s){if(null!==t.variableList||t.hasVariableRefs)for(let i=s.length;i--;){const r=s[i],n=e[r];n&&(e[r]=he(t,n))}}function he(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(ae,(e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r}))}return e}function de(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function ce(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function ue(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const fe={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ge(t,e,s=!0){return!t.split(",").some((t=>!me(t,e,s)))}function me(t,e,s=!0){var i;const r=ue(s);return null!=(i=null==r?void 0:r.isTypeSupported(pe(t,e)))&&i}function pe(t,e){return`${e}/mp4;codecs="${t}"`}function ve(t){if(t){const e=t.substring(0,4);return fe.video[e]}return 2}function ye(t){return t.split(",").reduce(((t,e)=>{const s=fe.video[e];return s?(2*s+t)/(t?3:2):(fe.audio[e]+t)/(t?2:1)}),0)}const Ee={};const Te=/flac|opus/i;function Se(t,e=!0){return t.replace(Te,(t=>function(t,e=!0){if(Ee[t])return Ee[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let i=0;i0&&i.length({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Re.lastIndex=0;null!==(i=Re.exec(t));){const t=new U(i[1]),n=t.TYPE;if(n){const i=a[n],l=r[n]||[];r[n]=l,le(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?De.resolve(t.URI,e):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const t=De.findGroup(i,g.groupId)||i[0];xe(g,t,"audioCodec"),xe(g,t,"textCodec")}l.push(g)}}return r}static parseLevelPlaylist(t,e,s,i,r,n){const a=new q(e),o=a.fragments;let l,h,d,c=null,u=0,f=0,g=0,m=0,p=null,v=new W(i,e),y=-1,E=!1,T=null;for(we.lastIndex=0,a.m3u8=t,a.hasVariableRefs=oe(t);null!==(l=we.exec(t));){E&&(E=!1,v=new W(i,e),v.start=g,v.sn=u,v.cc=m,v.level=s,c&&(v.initSegment=c,v.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,T&&(v.setByteRange(T),T=null)));const t=l[1];if(t){v.duration=parseFloat(t);const e=(" "+l[2]).slice(1);v.title=e||null,v.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(b(v.duration)){v.start=g,d&&Fe(v,d,a),v.sn=u,v.level=s,v.cc=m,o.push(v);const t=(" "+l[3]).slice(1);v.relurl=he(a,t),Pe(v,p),p=v,g+=v.duration,u++,f=0,E=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);p?v.setByteRange(t,p):v.setByteRange(t)}else if(l[5])v.rawProgramDateTime=(" "+l[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===y&&(y=o.length);else{if(l=l[0].match(ke),!l){F.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new U(r);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const s=f>0?t[t.length-1]:void 0,i=f++,n=new U(r);le(a,n,["BYTERANGE","URI"]);const o=new j(n,v,e,i,s);t.push(o),v.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new U(r);le(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new U(r);le(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:F.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(Pe(v,p),v.cc=m,a.fragmentHint=v,d&&Fe(v,d,a));const S=o.length,L=o[0],A=o[S-1];if(g+=a.skippedSegments*a.targetduration,g>0&&S&&A){a.averagetargetduration=g/S;const t=A.sn;a.endSN="initSegment"!==t?t:0,a.live||(A.endList=!0),L&&(a.startCC=L.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,y>0&&function(t,e){let s=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(o,y),a}}function Ie(t,e,s){var i,r;const n=new U(t);le(s,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&F.error(`Invalid IV: ${n.IV}`);const c=o?De.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ne(a,c,d,u,l)}function _e(t){const e=new U(t).decimalFloatingPoint("TIME-OFFSET");return b(e)?e:null}function Ce(t,e){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const i=s.filter((e=>function(t,e){const s=fe[e];return!!s&&!!s[t.slice(0,4)]}(e,t)));i.length&&(e[`${t}Codec`]=i.join(","),s=s.filter((t=>-1===i.indexOf(t))))})),e.unknownCodecs=s}function xe(t,e,s){const i=e[s];i&&(t[s]=i)}function Pe(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),b(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Me(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function Fe(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||i.push(t)}var Oe="manifest",Ne="level",Ue="audioTrack",Be="subtitleTrack",$e="main",Ge="audio",Ke="subtitle";function He(t){const{type:e}=t;switch(e){case Ue:return Ge;case Be:return Ke;default:return $e}}function Ve(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class Ye{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.LEVEL_LOADING,this.onLevelLoading,this),t.on(D.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(D.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.LEVEL_LOADING,this.onLevelLoading,this),t.off(D.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(D.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Oe,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Ne,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:Ue,url:r,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:Be,url:r,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=r.context;if(e&&e.url===t.url&&e.level===t.level)return void F.trace("[playlist-loader]: playlist request ongoing");F.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===Oe?s.manifestLoadPolicy.default:R({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),b(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===Ne&&null!==t.level?e=this.hls.levels[t.level].details:t.type===Ue&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===Be&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);i=R({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),De.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),i||null,e)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};r.load(t,a,o)}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Ve(t,s),o=De.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=De.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((t=>!t.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(F.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new U({}),bitrate:0,url:""}))}r.trigger(D.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=Ve(t,s),d=b(o)?o:b(a)?a:0,c=He(s),u=De.parseLevelPlaylist(t.data,h,d,c,0,this.variableList);if(l===Oe){const t={attrs:new U({}),bitrate:0,details:u,name:"",url:h};n.trigger(D.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(D.ERROR,{type:I.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:e.type===Oe,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===Ne?n+=`: ${t.level} id: ${t.id}`:t.type!==Ue&&t.type!==Be||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);F.warn(`[playlist-loader]: ${n}`);let o=_.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case Oe:o=s?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,l=!0;break;case Ne:o=s?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,l=!1;break;case Ue:o=s?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Be:o=s?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const d={type:I.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:r};if(i){const s=(null==e?void 0:e.url)||t.url;d.response=S({url:s,data:void 0},i)}this.hls.trigger(D.ERROR,d)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:c}=i,u=Ve(e,i),f=He(i),g="number"==typeof i.level&&f===$e?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(D.ERROR,{type:I.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:t,reason:t.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m)a.trigger(D.ERROR,{type:I.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Oe:case Ne:a.trigger(D.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:c});break;case Ue:a.trigger(D.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c});break;case Be:a.trigger(D.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c})}}}function We(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function je(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){F.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){F.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function qe(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}function Xe(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(et[s].endTime)return-1;let i=0,r=s;for(;i<=r;){const n=Math.floor((r+i)/2);if(et[n].startTime&&i-1)for(let n=r,a=t.length;n=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e{const t=ts();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function is(t,e){return t.getTime()/1e3-e}class rs{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(D.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(D.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(qe(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;ess&&(i=ss);i-s<=0&&(i=s+.25);for(let t=0;tt.type===Qe&&o:"video"===i?t=>t.type===Ze&&a:t=>t.type===Qe&&o||t.type===Ze&&a,Xe(r,e,s,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:i}=this,{dateRanges:r}=e,n=Object.keys(r);if(i){const t=Object.keys(s).filter((t=>!n.includes(t)));for(let e=t.length;e--;){const r=t[e];Object.keys(s[r].cues).forEach((t=>{i.removeCue(s[r].cues[t])})),delete s[r]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!b(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=ts();for(let t=0;t{if(e!==i.id){const s=r[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDatethis.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:s,targetduration:i}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,s=this.levelDetails;if(null===t||null===e||null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(D.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(D.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(D.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(D.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var s;e.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&F.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,s))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const as=["NONE","TYPE-0","TYPE-1",null];const os=["SDR","PQ","HLG"];var ls="",hs="YES",ds="v2";function cs(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i!!t)).map((t=>t.substring(0,4))).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return gs(this._audioGroups,t)}hasSubtitleGroup(t){return gs(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function gs(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function ms(t,e){const s=e.startPTS;if(b(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&(i.duration=r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function ps(t,e,s,i,r,n){i-s<=0&&(F.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let a=s,o=i;const l=e.startPTS,h=e.endPTS;if(b(l)){const t=Math.abs(l-s);b(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(s,l),s=Math.min(s,l),r=Math.min(r,e.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,e.endDTS)}const d=s-e.start;0!==e.start&&(e.start=s),e.duration=i-e.start,e.startPTS=s,e.maxStartPTS=a,e.startDTS=r,e.endPTS=i,e.minEndPTS=o,e.endDTS=n;const c=e.sn;if(!t||ct.endSN)return 0;let u;const f=c-t.startSN,g=t.fragments;for(g[f]=e,u=f;u>0;u--)ms(g[u],g[u-1]);for(u=f;u=0;t--){const e=i[t].initSegment;if(e){s=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let r,n=0;if(function(t,e,s){const i=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=r;t<=n;t++){const r=l[a+t];let n=o[t];i&&!n&&t{t.relurl&&(n=t.cc-i.cc),b(t.startPTS)&&b(t.endPTS)&&(i.start=i.startPTS=t.startPTS,i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.duration=t.endPTS-t.startPTS,i.duration&&(r=i),e.PTSKnown=e.alignedSliding=!0),i.elementaryStreams=t.elementaryStreams,i.loader=t.loader,i.stats=t.stats,t.initSegment&&(i.initSegment=t.initSegment,s=t.initSegment)})),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)}))}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((t=>!t)),e.deltaUpdateFailed){F.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const i=R({},t);s&&s.forEach((t=>{delete i[t]}));return Object.keys(e).forEach((t=>{const s=new $(e[t].attr,i[t]);s.isValid?i[t]=s:F.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)})),i}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){F.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),r?ps(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):ys(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function ys(t,e){const s=e.startSN+e.skippedSegments-t.startSN,i=t.fragments;s<0||s>=i.length||Es(e,i[s].start)}function Es(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach((t=>{t.level=e}))}))}function As(t){switch(t.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Rs(t,e){const s=As(e);return t.default[(s?"timeout":"error")+"Retry"]}function bs(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function ws(t){return S(S({},t),{errorRetry:null,timeoutRetry:null})}function ks(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}const Ds=function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function Is(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[t.sn-e[0].sn+1]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===_s(s,i,n)||function(t,e,s){if(e&&0===e.start&&e.level0){const i=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=Ds(e,_s.bind(null,s,i));return!a||a===t&&n?n:a}function _s(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function Cs(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}var xs=0,Ps=2,Ms=3,Fs=5,Os=0,Ns=1,Us=2;class Bs{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=F.log.bind(F,`${e}:`),this.warn=F.warn.bind(F,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let r=-1;for(let s=0;s=0&&t>e.partTarget&&(a+=1)}const o=s&&cs(s);return new us(n,a>=0?a:void 0,o)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;if(i.advancedDateTime=Date.now()-a,i.live||null!=s&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&vs(s,i),!this.canLoad||!i.live)return;let a,o,l;if(i.canBlockReload&&i.endSN&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,n=i.endSN,h=i.lastPartIndex,d=r===n;-1!==h?(o=d?n+1:r,l=d?t?0:h:h+1):o=n+1;const c=i.age,u=c+i.ageHeader;let f=Math.min(u-i.partTarget,1.5*i.targetduration);if(f>0){if(s&&f>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${f} with playlist age: ${i.age}`),f=0;else{const t=Math.floor(f/i.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}i.tuneInGoal=f}if(a=this.getDeliveryDirectives(i,e.deliveryDirectives,o,l),t||!d)return void this.loadPlaylist(a)}else(i.canBlockReload||i.canSkipUntil)&&(a=this.getDeliveryDirectives(i,e.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=function(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments,r=4;if(i.length&&s*r>e){const t=1e3*i[i.length-1].duration;tthis.requestScheduled+c&&(this.requestScheduled=r.loading.start),void 0!==o&&i.canBlockReload?this.requestScheduled=r.loading.first+c-(1e3*i.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+cthis.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(t,e,s,i){let r=cs(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=ls),new us(s,i,r)}checkRetry(t){const e=t.details,s=As(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Fs||!i.resolved&&r===Ps);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=bs(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}}class $s{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Gs{constructor(t,e,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new $s(t),this.fast_=new $s(e),this.defaultTTFB_=i,this.ttfb_=new $s(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new $s(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new $s(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new $s(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const Ks={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Hs={};function Vs(t,e,s,i,r,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce(((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach((e=>{t[e]=(t[e]||0)+i.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!d&&b(h)&&Object.keys(d).some((t=>parseInt(t)>h))}function Ys(t,e,s){const i=t.videoCodec,r=t.audioCodec;if(!i||!r||!s)return Promise.resolve(Ks);const n={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=i.split(",").map((t=>({type:"media-source",video:S(S({},n),{},{contentType:pe(t,"video")})})));return r&&t.audioGroups&&t.audioGroups.forEach((t=>{var s;t&&(null==(s=e.groups[t])||s.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",s=parseFloat(t);b(s)&&s>2&&o.push.apply(o,r.split(",").map((t=>({type:"media-source",audio:{contentType:pe(t,"audio"),channels:""+s}}))))}})))})),Promise.all(o.map((t=>{const e=function(t){const{audio:e,video:s}=t,i=s||e;if(i){const t=i.contentType.split('"')[1];if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${t}_${Math.ceil(s.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return Hs[e]||(Hs[e]=s.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:o,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:o,decodingInfoResults:[],error:t})))}function Ws(t,e){let s=!1,i=[];return t&&(s="SDR"!==t,i=[t]),e&&(i=e.allowedVideoRanges||os.slice(0),s=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i=s?i.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:s,allowedVideoRanges:i}}function js(t,e){F.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function qs(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i-1===i.indexOf(t)))}(o,e.characteristics))&&(void 0===s||s(t,e))}function zs(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function Qs(t,e,s){for(let i=e;i;i--)if(s(t[i]))return i;for(let i=e+1;i1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var Zs="NOT_LOADED",ti="APPENDING",ei="PARTIAL",si="OK";class ii{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(D.BUFFER_APPENDED,this.onBufferAppended,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this),t.on(D.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(D.BUFFER_APPENDED,this.onBufferAppended,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this),t.off(D.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const i=s[e];if(!i)break;const r=i.end;if(i.start<=t&&null!==r&&t<=r)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){const n=s[i[r]];if((null==n?void 0:n.body.type)===e&&n.buffered){const e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i){this.timeRanges&&(this.timeRanges[t]=e);const r=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const n=this.fragments[i];if(!n)return;if(r>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===s&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(n.body),s}))}))}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:i}=t;if(!e||"initSegment"===s.sn)return;const r=ni(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;if(Object.keys(e).forEach((t=>{const r=s.elementaryStreams[t];if(!r)return;const o=e[t],l=a||!0===r.partial;n.range[t]=this.getBufferedTimes(s,i,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ri(n)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(n.body)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=s.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const s=ni(t);let i=this.fragments[s];!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t=e&&o<=s){r.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(ne){const e=Math.max(n,i.start(t)),s=Math.min(a,i.end(t));s>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&ri(h)&&(s=h.body.start-a,i=h.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=h.body,n=e)))})),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||ri(e))}getState(t){const e=ni(t),s=this.fragments[e];return s?s.buffered?ri(s)?ei:si:ti:Zs}isTimeBuffered(t,e,s){let i,r;for(let n=0;n=i&&e<=r)return!0;if(e<=i)return!1}return!1}onFragLoaded(t,e){const{frag:s,part:i}=e;if("initSegment"===s.sn||s.bitrateTest)return;const r=i?null:e,n=ni(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r}=e;if("initSegment"===s.sn)return;const n=s.type;if(i){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(i)}this.timeRanges=r,Object.keys(r).forEach((t=>{const e=r[t];this.detectEvictedFragments(t,e,n,i)}))}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ni(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.startt&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(t){const e=ni(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=s.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function ri(t){var e,s,i;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(i=t.range.audiovideo)?void 0:i.partial))}function ni(t){return`${t.type}_${t.level}_${t.sn}`}const ai={length:0,start:()=>0,end:()=>0};class oi{static isBuffered(t,e){try{if(t){const s=oi.getBuffered(t);for(let t=0;t=s.start(t)&&e<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,s){try{if(t){const i=oi.getBuffered(t),r=[];let n;for(n=0;nn&&(i[r-1].end=t[e].end):i.push(t[e])}else i.push(t[e])}else i=t;let r,n=0,a=e,o=e;for(let t=0;t=l&&es.startCC||t&&t.cc{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(vi(t));t.gap=!1}const l=this.loader=t.loader=r?new r(i):new n(i),h=pi(t),d=ws(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:gi};t.stats=l.stats,l.load(h,c,{onSuccess:(e,s,i,r)=>{this.resetLoader(t,l);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,r,n)=>{this.resetLoader(t,l),o(new yi({type:I.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:S({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,l),o(new yi({type:I.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,l),o(new yi({type:I.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:e}))},onProgress:(s,i,r,n)=>{e&&e({frag:t,part:null,payload:r,networkDetails:n})}})}))}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(vi(t,e));const l=this.loader=t.loader=r?new r(i):new n(i),h=pi(t,e),d=ws(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gi};e.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new yi({type:I.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:S({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new yi({type:I.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new yi({type:I.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})}))}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function pi(t,e=null){const s=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(b(r)&&b(n)){var a;let e=r,s=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-r;t%16&&(s=n+(16-t%16)),0!==r&&(i.resetIV=!0,e=r-16)}i.rangeStart=e,i.rangeEnd=s}return i}function vi(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:I.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new yi(i)}class yi extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Ei{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class Ti{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Si{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ei(this.subtle,new Uint8Array(s)).decrypt(t.buffer,e)})).catch((i=>(F.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,e,s))))}onWebCryptoError(t,e,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=gt(t,0,s),this.remainderData=gt(t,s)),e}logOnce(t){this.logEnabled&&(F.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ai=function(t){let e="";const s=t.length;for(let i=0;ia.end){const t=n>r;(n{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const s=this.state;this.fragContextChanged(t)?(s===ki||!this.fragCurrent&&s===_i)&&(this.fragmentTracker.removeFragment(t),this.state=bi):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(D.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((e=>{this.state!==Ri&&this.state!==Pi&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===ti){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===ei&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(D.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:s}=this,{payload:i}=e,r=t.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const r=self.performance.now();return s.trigger(D.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((e=>{this.state!==Ri&&this.state!==Pi&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=bi,t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var s,i,r,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===$e?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(i=t.endPTS)?i:NaN).toFixed(3)}] > buffer:${a?Ai(oi.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==Ke){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=bi)}const e=null==(o=this.levels)?void 0:o[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=bi,a&&(!this.loadedmetadata&&t.type==$e&&a.buffered.length&&(null==(r=this.fragCurrent)?void 0:r.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some((t=>!t)),a=new li(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,i){var r;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=wi,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(D.KEY_LOADED,t),this.state===wi&&(this.state=bi),t})),this.hls.trigger(D.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const r=n.partList;if(r&&i){s>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,s);if(o>-1){const l=r[o];let h;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${r.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=ki,h=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,i))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,i).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(D.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),b(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ki;const o=this.config.progressive;let l;return l=o&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,i))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?i:void 0),a]).then((([t])=>(!o&&t&&i&&i(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(D.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,s,i){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,i).then((i=>{o[e.index]=i;const n=i.part;this.hls.trigger(D.FRAG_LOADED,i);const a=Ts(s,t.sn,e.index+1)||Ss(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});h(a)})).catch(n)};h(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(D.ERROR,e)}else this.hls.trigger(D.ERROR,{type:I.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==_i)return void(this.fragCurrent||this.state===Ri||this.state===Pi||(this.state=bi));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(s,i,r,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=n>-1?Ts(a,r,n):null,l=o?o.fragment:function(t,e,s){if(null==t||!t.details)return null;const i=t.details;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,r&&r.sn===e?r:en&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const s=this.getLoadPosition();return b(s)?this.getFwdBufferInfoAtPos(t,s,e):null}getFwdBufferInfoAtPos(t,e,s){const{config:{maxBufferHole:i}}=this,r=oi.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&r.nextStart=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=$e){const s=this.fragmentTracker.getAppendedFrag(t,$e);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start;let a;if(e.live){const o=r.initialLiveManifestSize;if(ie}getNextFragmentLoopLoading(t,e,s,i,r){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&s.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(null!==e&&s.len+e.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a-1&&ss.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!b(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let i=0;i=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function(t,e){return Ds(t,(t=>t.cce?-1:0))}(e,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(i.lowLatencyMode&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),te-l?0:l)}else c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===si||e===ei&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn)){if(r&&c.level===r.level){const e=n[t+1];c=c.sn=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r${t.startSN} prev-sn: ${r?r.sn:"na"} fragments: ${i}`),n}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;if(s ${null==(i=this.fragCurrent)?void 0:i.url}`);const r=e.details===_.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===Fs&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const i=bs(l,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${i}ms`),n.resolved=!0,this.retryDate=self.performance.now()+i,this.state=Di}else if(l&&n){if(this.resetFragmentErrors(t),!(o.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===Ge&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Ri&&(this.state=bi)}afterBufferFlushed(t,e,s){if(!t)return;const i=oi.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===xi&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=bi}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){var r;const n=s.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,r)=>{const a=t.elementaryStreams[r];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${o})`),e||!1;const l=i?0:ps(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(D.LEVEL_PTS_UPDATED,{details:n,level:s,drift:l,type:r,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&null===(null==(r=this.transmuxer)?void 0:r.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(0===s.fragmentError&&(s.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Ci,this.hls.trigger(D.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class Ni{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let i=0;for(let e=0;e0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Qe,duration:Number.POSITIVE_INFINITY});r{if(b(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function Gi(t,e){return 255===t[e]&&240==(246&t[e+1])}function Ki(t,e){return 1&t[e+1]?7:9}function Hi(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Vi(t,e){return e+1=t.length)return!1;const i=Hi(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||Vi(t,r)}return!1}function Wi(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){let r,n,a,o;const l=navigator.userAgent.toLowerCase(),h=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r=1+((192&e[s+2])>>>6);const c=(60&e[s+2])>>>2;if(!(c>d.length-1))return a=(1&e[s+2])<<2,a|=(192&e[s+3])>>>6,F.log(`manifest codec:${i}, ADTS type:${r}, samplingIndex:${c}`),/firefox/i.test(l)?c>=6?(r=5,o=new Array(4),n=c-3):(r=2,o=new Array(2),n=c):-1!==l.indexOf("android")?(r=2,o=new Array(2),n=c):(r=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&c>=6?n=c-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(c>=6&&1===a||/vivaldi/i.test(l))||!i&&1===a)&&(r=2,o=new Array(2)),n=c)),o[0]=r<<3,o[0]|=(14&c)>>1,o[1]|=(1&c)<<7,o[1]|=a<<3,5===r&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[c],channelCount:a,codec:"mp4a.40."+r,manifestCodec:h};{const e=new Error(`invalid ADTS sampling index:${c}`);t.emit(D.ERROR,D.ERROR,{type:I.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,s,i,r);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,F.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function ji(t){return 9216e4/t}function qi(t,e,s,i,r){const n=i+r*ji(t.samplerate),a=function(t,e){const s=Ki(t,e);if(e+s<=t.length){const i=Hi(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,s+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Xi=null;const zi=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Qi=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ji=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Zi=[0,1,1,4];function tr(t,e,s,i,r){if(s+24>e.length)return;const n=er(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function er(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*zi[14*(3===s?3-i:3===i?3:4)+r-1],h=Qi[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=Ji[s][i],u=Zi[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===Xi){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Xi=t?parseInt(t[1]):0}return!!Xi&&Xi<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function sr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function ir(t,e){return e+1{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<>l,s=s?s<e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const h=e[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[s+6]<<8|e[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}class hr{constructor(){this.VideoSample=null}createVideoSample(t,e,s,i){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:i,length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&F.log(t.pts+"/"+t.dts+":"+t.debug)}}class dr{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&F.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?s<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,s=8,i=8;for(let r=0;r{var n;switch(i.type){case 1:{let e=!1;a=!0;const r=i.data;if(l&&r.length>4){const t=new dr(r).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.frame=!0,o.key=e;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,te(i.data,1,s.pts,e.samples);break;case 7:{var d,c;a=!0,l=!0;const e=i.data,s=new dr(e).readSPS();if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(d=t.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=r;const i=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[i.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+i.type+" ")}if(o&&a){o.units.push(i)}})),i&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const s=e.byteLength;let i=t.naluState||0;const r=i,n=[];let a,o,l,h=0,d=-1,c=0;for(-1===i&&(d=0,c=31&e[0],i=0,h=1);h=0){const t={data:e.subarray(d,o),type:c};n.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(r&&h<=4-r&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-r)),o>0&&(s.data=Qt(s.data,e.subarray(0,o)),s.state=0))}h=0&&i>=0){const t={data:e.subarray(d,s),type:c,state:i};n.push(t)}if(0===n.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Qt(s.data,e))}return t.naluState=i,n}}class ur{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Li(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}))}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let i=0;for(let e=32;e{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}))}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}}const fr=188;class gr{constructor(t,e,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.videoParser=new cr}static probe(t){const e=gr.syncOffset(t);return e>0&&F.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let s=Math.min(940,e-fr)+1,i=0;for(;i1&&(0===n&&a>2||o+fr>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Ft[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=gr.createTrack("video"),this._audioTrack=gr.createTrack("audio",i),this._id3Track=gr.createTrack("id3"),this._txtTrack=gr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=Qt(this.remainderData,t)).length,this.remainderData=null),y>4>1){if(T=e+5+t[e+4],T===e+fr)continue}else T=e+4;switch(y){case h:i&&(d&&(r=Tr(d))&&this.videoParser.parseAVCPES(n,l,r,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(T,e+fr)),d.size+=e+fr-T);break;case c:if(i){if(f&&(r=Tr(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+fr)),f.size+=e+fr-T);break;case u:i&&(g&&(r=Tr(g))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+fr)),g.size+=e+fr-T);break;case 0:i&&(T+=t[T]+1),v=this._pmtId=pr(t,T);break;case v:{i&&(T+=t[T]+1);const r=vr(t,T,this.typeSupported,s,this.observer);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===m||p||(F.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&yr(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`)),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:s,id3Track:i,textTrack:r}=t,n=s.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=Tr(n))?(this.videoParser.parseAVCPES(s,r,l,!0,this._duration),s.pesData=null):s.pesData=n,a&&(l=Tr(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&F.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=Tr(o))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,s){const i=this.demux(t,s,!0,!this.config.progressive),r=this.sampleAes=new ur(this.observer,this.config,e);return this.decrypt(i,r)}decrypt(t,e){return new Promise((s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)})):s(t)})):r.samples&&e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)}))}))}destroy(){this._duration=0}parseAACPES(t,e){let s=0;const i=this.aacOverFlow;let r,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,r=i.sample.unit.byteLength;if(-1===e)o=Qt(i.sample.unit,o);else{const n=r-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void F.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=R({},e,{type:this._videoTrack?Ze:Qe,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function mr(t,e){return((31&t[e+1])<<8)+t[e+2]}function pr(t,e){return(31&t[e+10])<<8|t[e+11]}function vr(t,e,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e0){let i=e+5,r=o;for(;r>2;){if(106===t[i])!0!==s.ac3?F.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return yr(r,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return yr(r,new Error("Unsupported HEVC in M2TS found")),n}e+=o+5}return n}function yr(t,e,s){F.warn(`parsing error: ${e.message}`),t.emit(D.ERROR,D.ERROR,{type:I.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:e,reason:e.message})}function Er(t){F.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Tr(t){let e,s,i,r,n,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Qt(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(s=(e[4]<<8)+e[5],s&&s>t.size-6)return null;const l=e[7];192&l&&(r=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,r-n>54e5&&(F.warn(`${Math.round((r-n)/9e4)}s delta between PTS and DTS, align them`),r=n)):n=r),i=e[8];let h=i+9;if(t.size<=h)return null;t.size-=h;const d=new Uint8Array(t.size);for(let t=0,s=o.length;ts){h-=s;continue}e=e.subarray(h),s-=h,h=0}d.set(e,a),a+=s}return s&&(s-=i+3),{data:d,pts:r,dts:n,len:s}}return null}class Sr{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Lr=Math.pow(2,32)-1;class Ar{static init(){let t;for(t in Ar.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Ar.types)Ar.types.hasOwnProperty(t)&&(Ar.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Ar.HDLR_TYPES={video:e,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Ar.STTS=Ar.STSC=Ar.STCO=r,Ar.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ar.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ar.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ar.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Ar.FTYP=Ar.box(Ar.types.ftyp,n,o,n,a),Ar.DINF=Ar.box(Ar.types.dinf,Ar.box(Ar.types.dref,i))}static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),i=0,s=8;i>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return Ar.box(Ar.types.mdia,Ar.mdhd(t.timescale,t.duration),Ar.hdlr(t.type),Ar.minf(t))}static mfhd(t){return Ar.box(Ar.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Ar.box(Ar.types.minf,Ar.box(Ar.types.smhd,Ar.SMHD),Ar.DINF,Ar.stbl(t)):Ar.box(Ar.types.minf,Ar.box(Ar.types.vmhd,Ar.VMHD),Ar.DINF,Ar.stbl(t))}static moof(t,e,s){return Ar.box(Ar.types.moof,Ar.mfhd(t),Ar.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=Ar.trak(t[e]);return Ar.box.apply(null,[Ar.types.moov,Ar.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(Ar.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=Ar.trex(t[e]);return Ar.box.apply(null,[Ar.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(Lr+1)),i=Math.floor(e%(Lr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Ar.box(Ar.types.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(e=0;e>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=Ar.box(Ar.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return Ar.box(Ar.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Ar.box(Ar.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ar.box(Ar.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Ar.box(Ar.types.mp4a,Ar.audioStsd(t),Ar.box(Ar.types.esds,Ar.esds(t)))}static mp3(t){return Ar.box(Ar.types[".mp3"],Ar.audioStsd(t))}static ac3(t){return Ar.box(Ar.types["ac-3"],Ar.audioStsd(t),Ar.box(Ar.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?Ar.box(Ar.types.stsd,Ar.STSD,Ar.mp3(t)):"ac3"===t.segmentCodec?Ar.box(Ar.types.stsd,Ar.STSD,Ar.ac3(t)):Ar.box(Ar.types.stsd,Ar.STSD,Ar.mp4a(t)):Ar.box(Ar.types.stsd,Ar.STSD,Ar.avc1(t))}static tkhd(t){const e=t.id,s=t.duration*t.timescale,i=t.width,r=t.height,n=Math.floor(s/(Lr+1)),a=Math.floor(s%(Lr+1));return Ar.box(Ar.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const s=Ar.sdtp(t),i=t.id,r=Math.floor(e/(Lr+1)),n=Math.floor(e%(Lr+1));return Ar.box(Ar.types.traf,Ar.box(Ar.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),Ar.box(Ar.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Ar.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,Ar.box(Ar.types.trak,Ar.tkhd(t),Ar.mdia(t))}static trex(t){const e=t.id;return Ar.box(Ar.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const s=t.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Ar.box(Ar.types.trun,n)}static initSegment(t){Ar.types||Ar.init();const e=Ar.moov(t);return Qt(Ar.FTYP,e)}}Ar.types=void 0,Ar.HDLR_TYPES=void 0,Ar.STTS=void 0,Ar.STSC=void 0,Ar.STCO=void 0,Ar.STSZ=void 0,Ar.VMHD=void 0,Ar.SMHD=void 0,Ar.STSD=void 0,Ar.FTYP=void 0,Ar.DINF=void 0;function Rr(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function br(t,e=!1){return Rr(t,1e3,1/9e4,e)}let wr,kr=null,Dr=null;class Ir{constructor(t,e,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===kr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);kr=t?parseInt(t[1]):0}if(null===Dr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Dr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){F.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){F.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){F.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t.reduce(((t,s)=>{const i=s.pts-t;return i<-4294967296?(e=!0,_r(t,s.pts)):i>0?t:s.pts}),t[0].pts);return e&&F.debug("PTS rollover detected"),s}remux(t,e,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,m=r;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,L,A,R;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(L=t.pixelRatio)?void 0:L[0])&&(null==(A=e.pixelRatio)?void 0:A[1])===(null==(R=t.pixelRatio)?void 0:R[1])||this.resetInitSegment()}else d=this.generateIS(t,e,r,n);const s=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(t){for(let e=0;e0){F.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(F.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const s=this.getVideoStartPts(e.samples),i=(_r(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(t.samplerate||(F.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,r,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===Ge?m:void 0),T){const i=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(F.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,s,i)}}else T&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Cr(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=xr(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4";if(u&&(h=d=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Ar.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=r[0].pts-Math.round(c*s))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Ar.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*s);d=Math.min(d,_r(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,s,i){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let h,d,c=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!s||null===c){const t=e*r,i=n[0].pts-_r(n[0].dts,n[0].pts);kr&&null!==c&&Math.abs(t-i-c)<15e3?s=!0:c=t-i}const v=l.baseTime*r/l.timescale;for(let t=0;t0?t-1:t].dts&&(p=!0)}p&&n.sort((function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i})),h=n[0].dts,d=n[n.length-1].dts;const y=d-h,E=y?Math.round(y/(o-1)):f||t.inputTimeScale/30;if(s){const t=h-c,s=t>E,i=t<-1;if((s||i)&&(s?F.warn(`AVC: ${br(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):F.warn(`AVC: ${br(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!i||c>=n[0].pts||kr)){h=c;const e=n[0].pts-t;if(s)n[0].dts=h,n[0].pts=e;else for(let s=0;se);s++)n[s].dts-=t,n[s].pts-=t;F.log(`Video: Initial PTS/DTS adjusted: ${br(e,!0)}/${br(h,!0)}, delta: ${br(t,!0)} ms`)}}h=Math.max(0,h);let T=0,S=0,L=h;for(let t=0;t0?e.dts-n[t-1].dts:E;if(l=t>0?e.pts-n[t-1].pts:E,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*r),n=(i?g+i*r:this.nextAudioPts)-e.pts;n>t?(f=n-a,f<0?f=a:k=!0,F.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(e.pts-e.dts);C=Math.min(C,f),P=Math.max(P,f),x=Math.min(x,l),M=Math.max(M,l),a.push(new Pr(e.key,f,h,d))}if(a.length)if(kr){if(kr<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Dr&&M-x0&&(i&&Math.abs(p-m)<9e3||Math.abs(_r(f[0].pts-v,p)-m)<20*l),f.forEach((function(t){t.pts=_r(t.pts-v,p)})),!s||m<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;m=0===r?0:i&&!u?Math.max(0,p):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=m;s=e*l&&h<1e4&&u){let e=Math.round(o/l);i=a-e*l,i<0&&(e--,i+=l),0===s&&(this.nextAudioPts=m=i),F.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(i/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n0))return;S+=g;try{y=new Uint8Array(S)}catch(t){return void this.observer.emit(D.ERROR,D.ERROR,{type:I.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!d){new DataView(y.buffer).setUint32(0,S),y.set(Ar.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,c.push(new Pr(!0,o,l,0)),T=n}const A=c.length;if(!A)return;const b=c[c.length-1];this.nextAudioPts=m=T+a*b.duration;const w=d?new Uint8Array(0):Ar.moof(t.sequenceNumber++,E/a,R({},t,{samples:c}));t.samples=[];const k=E/n,C=m/n,x={data1:w,data2:y,startPTS:k,endPTS:C,startDTS:k,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,x}remuxEmptyAudio(t,e,s,i){const r=t.inputTimeScale,n=r/(t.samplerate?t.samplerate:r),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:i.startDTS*r)+l,d=i.endDTS*r+l,c=1024*n,u=Math.ceil((d-h)/c),f=Sr.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(F.warn("[mp4-remuxer]: remux empty Audio"),!f)return void F.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t4294967296;)t+=s;return t}function Cr(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;at.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}class Pr{constructor(t,e,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=s,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function Mr(t,e){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(e===K){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Se(s,!1)}const t="mp4a.40.5";return F.info(`Parsed audio codec "${s}" or audio object type not handled. Using "${t}"`),t}return F.warn(`Unhandled video codec "${s}"`),"hvc1"===s||"hev1"===s?"hvc1.1.6.L120.90":"av01"===s?"av01.0.04M.08":"avc1.42e01e"}try{wr=self.performance.now.bind(self.performance)}catch(t){F.debug("Unable to use Performance API on this environment"),wr=null==J?void 0:J.Date.now}const Fr=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=Ui("video",1),n=this.audioTrack=Ui("audio",1),a=this.txtTrack=Ui("text",1);if(this.id3Track=Ui("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Vt(t);if(o.video){const{id:t,timescale:e,codec:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=Ft.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=i>1?s+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Qt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=Kt(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=gt(t,0,i.byteOffset-8),e.remainder=gt(t,i.byteOffset-8),e}(s);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,e);return r.samples=Jt(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=Jt(t,e),{videoTrack:e,audioTrack:Ui(),id3Track:i,textTrack:Ui()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=Kt(t.samples,["emsg"]);i&&i.forEach((t=>{const i=function(t){const e=t[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==Ot(t.subarray(h,h+1));)s+=Ot(t.subarray(h,h+1)),h+=1;for(s+=Ot(t.subarray(h,h+1)),h+=1;"\0"!==Ot(t.subarray(h,h+1));)i+=Ot(t.subarray(h,h+1)),h+=1;i+=Ot(t.subarray(h,h+1)),h+=1,r=Ut(t,12),n=Ut(t,16),o=Ut(t,20),l=Ut(t,24),h=28}else if(1===e){h+=4,r=Ut(t,h),h+=4;const e=Ut(t,h);h+=4;const n=Ut(t,h);for(h+=4,a=2**32*e+n,w(a)||(a=Number.MAX_SAFE_INTEGER,F.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ut(t,h),h+=4,l=Ut(t,h),h+=4;"\0"!==Ot(t.subarray(h,h+1));)s+=Ot(t.subarray(h,h+1)),h+=1;for(s+=Ot(t.subarray(h,h+1)),h+=1;"\0"!==Ot(t.subarray(h,h+1));)i+=Ot(t.subarray(h,h+1)),h+=1;i+=Ot(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(nr.test(i.schemeIdUri)){const t=b(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale;let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Ze,duration:r})}}))}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;s&&e.isCommonEncryption&&Kt(t,["moov","trak"]).forEach((t=>{const e=Kt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let i=Kt(e,["enca"]);const r=i.length>0;r||(i=Kt(e,["encv"])),i.forEach((t=>{Kt(r?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=Xt(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(F.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${xt(t)} -> ${xt(s)}`),e.set(s,8))}}))}))}));return t}(t,i)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const i=this.initData=Vt(t);i.audio&&(e=Mr(i.audio,K)),i.video&&(s=Mr(i.video,H));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:e+","+s,initSegment:t,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:F.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(t,e,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};b(h)||(h=this.lastEndTime=r||0);const c=e.samples;if(null==c||!c.length)return d;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return F.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e){let s=0,i=0,r=0;const n=Kt(t,["moof","traf"]);for(let t=0;tt+e.info.duration||0),0);s=Math.max(s,t+n.earliestPresentationTime/n.timescale),i=s-e}}if(i&&b(i))return i}return i||r}(c,f),m=function(t,e){return Kt(e,["moof","traf"]).reduce(((e,s)=>{const i=Kt(s,["tfdt"])[0],r=i[0],n=Kt(s,["tfhd"]).reduce(((e,s)=>{const n=Ut(s,4),a=t[n];if(a){let t=Ut(i,4);if(1===r){if(t===Pt)return F.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Pt+1,t+=Ut(i,8)}const s=t/(a.timescale||9e4);if(b(s)&&(null===e||sr}(l,p,r,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-r,l&&1===l.timescale&&F.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const v=t?p-l.baseTime/l.timescale:h,y=v+g;!function(t,e,s){Kt(e,["moof","traf"]).forEach((e=>{Kt(e,["tfhd"]).forEach((i=>{const r=Ut(i,4),n=t[r];if(!n)return;const a=n.timescale||9e4;Kt(e,["tfdt"]).forEach((t=>{const e=t[0],i=s*a;if(i){let s=Ut(t,4);if(0===e)s-=i,s=Math.max(s,0),Gt(t,4,s);else{s*=Math.pow(2,32),s+=Ut(t,8),s-=i,s=Math.max(s,0);const e=Math.floor(s/(Pt+1)),r=Math.floor(s%(Pt+1));Gt(t,4,e),Gt(t,8,r)}}}))}))}))}(f,c,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(F.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const E=!!f.audio,T=!!f.video;let S="";E&&(S+="audio"),T&&(S+="video");const L={data1:c,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:S,hasAudio:E,hasVideo:T,nb:1,dropped:0};return d.audio="audio"===L.type?L:void 0,d.video="audio"!==L.type?L:void 0,d.initSegment=u,d.id3=Cr(s,r,l,l),i.samples.length&&(d.text=xr(i,r,l)),d}}},{demux:gr,remux:Ir},{demux:class extends Bi{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=vt(t,0);let s=(null==e?void 0:e.length)||0;if(rr(t,s))return!1;for(let e=t.length;s0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(E&&"AES-128"===E.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer).then((t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e})),this.decryptionPromise;{let e=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer);if(s.part>-1&&(e=t.flush()),!e)return r.executeEnd=wr(),Nr(s);n=new Uint8Array(e)}}const T=this.needsProbing(h,d);if(T){const t=this.configureTransmuxer(n);if(t)return F.warn(`[transmuxer] ${t.message}`),this.observer.emit(D.ERROR,D.ERROR,{type:I.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=wr(),Nr(s)}(h||d||f||T)&&this.resetInitSegment(y,g,m,v,e),(h||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,u,c,s),L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,r.executeEnd=wr(),S}flush(t){const e=t.transmuxing;e.executeStart=wr();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then((()=>this.flush(t)));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=wr(),[Nr(t)];const h=o.flush(a);return Ur(h)?h.then((e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,h,t),n)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;F.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=wr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,i,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer.demuxSampleAes(t,e,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id),chunkMeta:r})))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i,vendor:r}=this;let n;for(let e=0,s=Fr.length;e({remuxResult:{},chunkMeta:t});function Ur(t){return"then"in t&&t.then instanceof Function}class Br{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class $r{constructor(t,e,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}var Gr={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||t,a),l=s?s+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r{(e=e||{}).frag=this.frag,e.id=this.id,t===D.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new Kr,this.observer.on(D.FRAG_DECRYPTED,n),this.observer.on(D.ERROR,n);const a=ue(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(F.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(r.workerPath)):(F.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const s=new Error(`${t.message} (${t.filename}:${t.lineno})`);r.enableWorker=!1,F.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(D.ERROR,{type:I.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:o,vendor:"",id:e,config:JSON.stringify(r)})}catch(t){F.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Or(this.observer,o,r,"",e)}return}}this.transmuxer=new Or(this.observer,o,r,"",e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:r.start,g=r.decryptdata,m=this.frag,p=!(m&&r.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===E||T&&E<=0)),L=self.performance.now();(v||y||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!E&&S||(n.stats.parsing.start=L);const A=!(m&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),R=new $r(p,S,o,v,f,A);if(!S||p||A){F.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${A}`);const t=new Br(s,i,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:R},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,g,l,R);Ur(e)?(u.async=!0,e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let s=e.flush(t);Ur(s)||e.async?(Ur(s)||(s=Promise.resolve(s)),s.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}))):this.handleFlushResult(s,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}onWorkerMessage(t){const e=t.data;if(null==e||!e.event)return void F.warn("worker message received with no "+(e?"event name":"data"));const s=this.hls;if(this.hls)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":F[e.data.logType]&&F[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,s.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Vr(t,e){if(t.length!==e.length)return!1;for(let s=0;st[s]!==e[s]))}function Wr(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class jr{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}}class qr{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,s){const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const s=new Promise((t=>{e=t})),i={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,t),s}executeNext(t){const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){F.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),s.onError(e);const i=this.buffers[t];null!=i&&i.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Xr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function zr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}const Qr={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Jr=t=>String.fromCharCode(Qr[t]||t),Zr=15,tn=100,en={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},sn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},nn={25:2,26:4,29:6,30:8,31:10,27:13,28:15},an=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class on{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;F.log(`${this.time} [${t}] ${s}`)}}}const ln=function(t){const e=[];for(let s=0;stn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=tn)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t=144&&this.backSpace();const e=Jr(t);this.pos>=tn?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e"pacData = "+JSON.stringify(t)));let e=t.row-1;if(this.nrRollUpRows&&e"bkgData = "+JSON.stringify(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",i=-1;for(let s=0;s0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class fn{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new un(s),this.nonDisplayedMemory=new un(s),this.lastOutputScreen=new un(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;ee+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class gn{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new on;this.channels=[null,new fn(t,e,i),new fn(t+1,s,i)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t"["+ln([e[t],e[t+1]])+"] -> ("+ln([s,i])+")"));const a=this.cmdHistory;if(s>=16&&s<=31){if(pn(s,i,a)){mn(null,null,a),this.logger.log(3,(()=>"Repeated command ("+ln([s,i])+") is dropped"));continue}mn(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else mn(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+ln([s,i])+" orig: "+ln([e[t],e[t+1]])))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=s,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+ln([t,e])+")")),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?en[t]:rn[t]:1===i?sn[t]:nn[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,(()=>"Special char '"+Jr(t)+"' in channel "+s)),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,(()=>"Char codes = "+ln(i).join(","))),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=an[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var yn=function(){if(null!=J&&J.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function i(t){return s(e,t)}function r(t,...e){let s=1;for(;s100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return L},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class En{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Tn(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class Sn{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i=0&&s<=100)return this.set(t,s),!0}return!1}}function Ln(t,e,s,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(s);if(2!==i.length)continue;e(i[0],i[1])}}const An=new yn(0,0,""),Rn="middle"===An.align?"middle":"center";function bn(t,e,s){const i=t;function r(){const e=Tn(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new Sn;Ln(t,(function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",Rn,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",Rn,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Rn,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===An.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Rn);let n=i.get("position","auto");"auto"===n&&50===An.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function wn(t){return t.replace(//gi,"\n")}class kn{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new En,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=wn(t);s>>0).toString()};function Cn(t,e,s){return _n(t.toString())+_n(e.toString())+_n(s)}function xn(t,e,s,i,r,n,a){const o=new kn,l=It(new Uint8Array(t)).trim().replace(Dn,"\n").split("\n"),h=[],d=e?function(t,e=1){return Rr(t,9e4,1/e)}(e.baseTime,e.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(f-d)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:function(t,e,s){let i=t[e],r=t[i.prevCC];if(!r||!r.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=i.start-r.start,i.new=!1,i=r,r=t[i.prevCC]}t.presentationOffset=s}(s,i,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,u=_r(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=Cn(t.startTime,t.endTime,m)),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(h)},l.forEach((t=>{if(m){if(In(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach((t=>{In(t,"LOCAL:")?u=t.slice(6):In(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{g=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(b(e)&&b(s)&&b(i)&&b(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e}(u)/1e3}catch(t){c=t}return}""===t&&(m=!1)}o.parse(t+"\n")})),o.flush()}const Pn="stpp.ttml.im1t",Mn=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Fn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,On={left:"start",center:"center",right:"end",start:"start",end:"end"};function Nn(t,e,s,i){const r=Kt(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map((t=>It(t))),a=function(t,e,s=1,i=!1){return Rr(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach((t=>s(function(t,e){const s=(new DOMParser).parseFromString(t,"text/xml"),i=s.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce(((t,e)=>(t[e]=i.getAttribute(`ttp:${e}`)||r[e],t)),{}),a="preserve"!==i.getAttribute("xml:space"),o=Bn(Un(i,"styling","style")),l=Bn(Un(i,"layout","region")),h=Un(i,"body","[begin]");return[].map.call(h,(t=>{const s=$n(t,a);if(!s||!t.hasAttribute("begin"))return null;const i=Hn(t.getAttribute("begin"),n),r=Hn(t.getAttribute("dur"),n);let h=Hn(t.getAttribute("end"),n);if(null===i)throw Kn(t);if(null===h){if(null===r)throw Kn(t);h=i+r}const d=new yn(i-e,h-e,s);d.id=Cn(d.startTime,d.endTime,d.text);const c=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce(((s,n)=>{const a=Gn(e,i,n)||Gn(t,i,n)||Gn(r,i,n);return a&&(s[n]=a),s}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=On[u];t&&(d.lineAlign=t),d.align=u}return R(d,c),d})).filter((t=>null!==t))}(t,a))))}catch(t){i(t)}}function Un(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function Bn(t){return t.reduce(((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t}),{})}function $n(t,e){return[].slice.call(t.childNodes).reduce(((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?$n(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function Gn(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function Kn(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Hn(t,e){if(!t)return null;let s=Tn(t);return null===s&&(Mn.test(t)?s=function(t,e){const s=Mn.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):Fn.test(t)&&(s=function(t,e){const s=Fn.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}function Vn(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Yn(t,e){return!!t&&t.kind===Vn(e)&&Wr(e,t)}class Wn{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(D.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(D.BUFFER_CODECS,this.onBufferCodecs,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(D.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(D.BUFFER_CODECS,this.onBufferCodecs,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&b(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&F.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const s=e.filter(((e,s)=>this.isLevelAllowed(e)&&s<=t));return this.clientRect=null,Wn.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,s){if(null==t||!t.length)return-1;let i=t.length-1;const r=Math.max(e,s);for(let e=0;e=r||s.height>=r)&&(n=s,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){i=e;break}}var n,a;return i}}const jn="[eme]";class qn{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=qn.CDMCleanupPromise?[qn.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=F.debug.bind(F,jn),this.log=F.log.bind(F,jn),this.warn=F.warn.bind(F,jn),this.error=F.error.bind(F,jn),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(D.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(D.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(D.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(D.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=e[t];if(i)return i.licenseUrl;if(t===Z.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map((t=>t.audioCodec)).filter(s),r=e.map((t=>t.videoCodec)).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise(((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?n(t):s(e instanceof Xn?e:new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===ut&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const i=function(t,e,s,i){let r;switch(t){case Z.FAIRPLAY:r=["cenc","sinf"];break;case Z.WIDEVINE:case Z.PLAYREADY:r=["cenc"];break;case Z.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}))),videoCapabilities:s.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null})))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let n=null==r?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(i)}`),n=this.requestMediaKeySystemAccess(t,i);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),i.then((s=>s?this.setMediaKeysServerCertificate(e,t,s):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>r.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${xt(t.keyId||[])}`);const i=s.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return xt(t.keyId)}updateKeySession(t,e){var s;const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${xt((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),i.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((e,s)=>{const i=ct(this.config),r=t.map(rt).filter((t=>!!t&&-1!==i.indexOf(t)));return this.getKeySystemSelectionPromise(r).then((({keySystem:t})=>{const i=dt(t);i?e(i):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)}))}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),i=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(e).then((({keySystem:s,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(s,r).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:r,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))))),r.catch((t=>this.handleError(t)))),r}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof Xn?this.hls.trigger(D.ERROR,t.data):this.hls.trigger(D.ERROR,{type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=rt(t.keyFormat),s=e?[e]:ct(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=ct(this.config)),0===t.length)throw new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.debug(i),null===s)return;let r,n;if("sinf"===e&&this.config.drmSystems[Z.FAIRPLAY]){const t=Ot(new Uint8Array(s));try{const e=X(JSON.parse(t).sinf),s=Xt(new Uint8Array(e));if(!s)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");r=s.subarray(8,24),n=Z.FAIRPLAY}catch(t){return void this.warn(`${i} Failed to parse sinf: ${t}`)}}else{const t=function(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32t.systemId===lt))[0];if(!e)return void(0===t.length||t.some((t=>!t.systemId))?this.warn(`${i} contains incomplete or invalid pssh data`):this.log(`ignoring ${i} for ${t.map((t=>ht(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(n=ht(e.systemId),0===e.version&&e.data){const t=e.data.length-22;r=e.data.subarray(t,t+16)}}if(!n||!r)return;const a=xt(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let h=o[a];for(let t=0;tthis.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match")));break}}h||(h=o[a]=this.getKeySystemSelectionPromise([n]).then((({keySystem:t,mediaKeys:i})=>{var n;this.throwIfDestroyed();const o=new ne("ISO-23001-7",a,null!=(n=dt(t))?n:"");return o.pssh=new Uint8Array(s),o.keyId=r,this.attemptSetMediaKeys(t,i).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-no-match")}))}))),h.catch((t=>this.handleError(t)))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(i),i.then((()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===s.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,s,i){var r,n;const a=null==(r=this.config.drmSystems)||null==(n=r[t.keySystem])?void 0:n.generateRequest;if(a)try{const i=a.call(this.hls,e,s,t);if(!i)throw new Error("Invalid response from configured generateRequest filter");e=i.initDataType,s=t.decryptdata.pssh=i.initData?new Uint8Array(i.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${i}": ${l} (init data type: ${e} length: ${s?s.byteLength:null})`);const h=new Kr,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void h.emit("error",new Error("invalid state"));const{messageType:i,message:r}=e;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(t,r).catch((t=>{this.handleError(t),h.emit("error",t)})):"license-release"===i?t.keySystem===Z.FAIRPLAY&&(this.updateKeySession(t,Q("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${i}"`)},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;h.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",c);const u=new Promise(((t,e)=>{h.on("error",e),h.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return t.mediaKeysSession.generateRequest(e,s).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)})).catch((t=>{throw new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>u)).catch((e=>{throw h.removeAllListeners(),this.removeSession(t),e})).then((()=>(h.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${xt("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${xt(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise(((r,n)=>{const a={responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:S({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise(((i,r)=>{t.setServerCertificate(s).then((r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),i(t)})).catch((t=>{r(new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((t=>{throw new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s in key message");return Q(atob(l))}setupLicenseXHR(t,e,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,s,i)})).catch((n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,s,i)})).then((s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||i}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise(((i,r)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(t){this.error(t)}i(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Xn({type:I.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(i,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then((({xhr:e,licenseChallenge:s})=>{t.keySystem==Z.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ne.clearKeyUriToKeyIdMap();const s=e.length;qn.CDMCleanupPromise=Promise.all(e.map((t=>this.removeSession(t))).concat(null==t?void 0:t.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}`)})))).then((()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);return i>-1&&this.mediaKeySessions.splice(i,1),e.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>e.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}qn.CDMCleanupPromise=void 0;class Xn extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var zn,Qn,Jn;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(zn||(zn={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(Qn||(Qn={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(Jn||(Jn={}));const Zn={[Jn.OBJECT]:["br","d","ot","tb"],[Jn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Jn.SESSION]:["cid","pr","sf","sid","st","v"],[Jn.STATUS]:["bs","rtp"]};class ta{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof ta?t:new ta(t)))),this.value=t,this.params=e}}class ea{constructor(t){this.description=void 0,this.description=t}}function sa(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}const ia="Bare Item";const ra=/[\x00-\x1f\x7f]+/;function na(t,e,s){return sa("serialize",t,e,s)}function aa(t){if(!1===ArrayBuffer.isView(t))throw na(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function oa(t){if(function(t){return t<-999999999999999||99999999999999912)throw na(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}function da(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw na(e,"Token");return e}function ca(t){switch(typeof t){case"number":if(!b(t))throw na(t,ia);return Number.isInteger(t)?oa(t):ha(t);case"string":return function(t){if(ra.test(t))throw na(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return da(t);case"boolean":return function(t){if("boolean"!=typeof t)throw na(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${oa(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return aa(t);if(t instanceof ea)return da(t);default:throw na(t,ia)}}function ua(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw na(t,"Key");return t}function fa(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${ua(t)}`:`;${ua(t)}=${ca(e)}`)).join("")}function ga(t){return t instanceof ta?`${ca(t.value)}${fa(t.params)}`:ca(t)}function ma(t,e={whitespace:!0}){if("object"!=typeof t)throw na(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),i=null!=e&&e.whitespace?" ":"";return Array.from(s).map((([t,e])=>{e instanceof ta==!1&&(e=new ta(e));let s=ua(t);var i;return!0===e.value?s+=fa(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(ga).join(" ")})${fa(i.params)}`:s+=ga(e)),s})).join(`,${i}`)}const pa=t=>Math.round(t),va=t=>100*pa(t/100),ya={br:pa,d:pa,bl:va,dl:va,mtp:va,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const s=new URL(t),i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:va,tb:pa};function Ea(t,e){const s={};if(null==t||"object"!=typeof t)return s;const i=Object.keys(t).sort(),r=R({},ya,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return i.forEach((i=>{if(null!=n&&n(i))return;let a=t[i];const o=r[i];o&&(a=o(a,e)),"v"===i&&1===a||"pr"==i&&1===a||(t=>"number"==typeof t?b(t):null!=t&&""!==t&&!1!==t)(a)&&((t=>"ot"===t||"sf"===t||"st"===t)(i)&&"string"==typeof a&&(a=new ea(a)),s[i]=a)})),s}function Ta(t,e={}){return t?function(t,e){return ma(t,e)}(Ea(t,e),R({whitespace:!1},e)):""}function Sa(t,e,s){return R(t,function(t,e={}){if(!t)return{};const s=Object.entries(t),i=Object.entries(Zn).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),r=s.reduce(((t,e)=>{var s;const[r,n]=e,a=(null==(s=i.find((t=>t[1].includes(r))))?void 0:s[0])||Jn.REQUEST;return null!=t[a]||(t[a]={}),t[a][r]=n,t}),{});return Object.entries(r).reduce(((t,[s,i])=>(t[s]=Ta(i,e),t)),{})}(e,s))}const La=/CMCD=[^&#]+/;function Aa(t,e,s){const i=function(t,e={}){if(!t)return"";const s=Ta(t,e);return`CMCD=${encodeURIComponent(s)}`}(e,s);if(!i)return t;if(La.test(t))return t.replace(La,i);const r=t.includes("?")?"&":"?";return`${t}${r}${i}`}function Ra(t,e,s,i){t&&Object.keys(e).forEach((r=>{const n=t.filter((t=>t.groupId===r)).map((t=>{const n=R({},t);return n.details=void 0,n.attrs=new U(n.attrs),n.url=n.attrs.URI=ba(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n}));t.push(...n)}))}function ba(t,e,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}const wa=/^age:\s*[\d.]+\s*$/im;class ka{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new G,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,e.url)})).catch((t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r(s,e.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)})).catch((t=>{this.callbacks.onError({code:s.status,text:t.message},e,s,i)})):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const e in i)t.setRequestHeader(e,i[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&b(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,n="text"!==e.responseType;if(i>=200&&i<300&&(n&&e.response||null!==e.responseText)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const r=n?e.response:e.responseText,a="arraybuffer"===e.responseType?r.byteLength:r.length;if(s.loaded=s.total=a,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(s,t,r,e),!this.callbacks)return;const l={url:e.responseURL,data:r,code:i};this.callbacks.onSuccess(l,s,t,e)}else{const n=r.loadPolicy.errorRetry;ks(n,s.retry,!1,{url:t.url,data:void 0,code:i})?this.retry(n):(F.error(`${i} while loading ${t.url}`),this.callbacks.onError({code:i,text:e.statusText},t,e,s))}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(ks(t,this.stats.retry,!0))this.retry(t);else{var e;F.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=bs(t,s.retry),s.retry++,F.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&wa.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Da=/(\d+)-(\d+)\/(\d+)/;class Ia{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||_a,this.controller=new self.AbortController,this.stats=new G}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(R({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),n=s.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=l&&b(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(i,t,this.response)}),e.timeout),self.fetch(this.request).then((r=>{this.response=this.loader=r;const o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(i,t,this.response)}),h-(o-i.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new Ca(e||"fetch, bad network response",t,r)}return i.loading.first=o,i.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Da.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(b(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(r.headers)||i.total,n&&b(e.highWaterMark)?this.loadProgressively(r,i,t,e.highWaterMark,n):a?r.arrayBuffer():"json"===t.responseType?r.json():r.text()})).then((r=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=r[o];l&&(i.loaded=i.total=l);const h={url:a.url,data:r,code:a.status};n&&!b(e.highWaterMark)&&n(i,t,r,a),s.onSuccess(h,i,t,a)})).catch((e=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=e&&e.code||0,n=e?e.message:null;s.onError({code:r,text:n},t,e?e.details:null,i)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,i=0,r){const n=new Ni,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(e,s,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h=i&&r(e,s,n.flush(),t)):r(e,s,l,t),o()})).catch((()=>Promise.reject()));return o()}}function _a(t,e){return new self.Request(t.url,e)}class Ca extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const xa=/\s/,Pa={newCue(t,e,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const i=wn(h.trim()),f=Cn(e,s,i);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),r.forEach((e=>je(t,e)))),r}},Ma=S(S({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ka,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:e,hls:s}=this,{autoLevelEnabled:i,media:r}=s;if(!t||!r)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=n-a.loading.start,h=s.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!i||r.paused||!r.playbackRate||!r.readyState)return;const d=s.mainForwardBufferInfo;if(null===d)return;const c=this.bwEstimator.getEstimateTTFB(),u=Math.abs(r.playbackRate);if(l<=Math.max(c,o/(2*u)*1e3))return;const f=d.len/u,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),v=s.levels,y=v[t.level],E=a.total||Math.max(a.loaded,Math.round(o*y.averageBitrate/8));let T=m?l-g:l;T<1&&m&&(T=Math.min(l,8*a.loaded/p));const S=m?1e3*a.loaded/T:0,L=S?(E-a.loaded)/S:8*E/p+c/1e3;if(L<=f)return;const A=S?8*S:p;let R,w=Number.POSITIVE_INFINITY;for(R=t.level-1;R>h;R--){const t=v[R].maxBitrate;if(w=this.getTimeToLoadFrag(c/1e3,A,o*t,!v[R].details),w=L)return;if(w>10*o)return;s.nextLoadLevel=s.nextAutoLevel=R,m?this.bwEstimator.sample(l-Math.min(c,g),a.loaded):this.bwEstimator.sampleTTFB(l);const k=v[R].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>k&&this.resetEstimator(k),this.clearTimer(),F.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${L.toFixed(3)} s\n Estimated load time for down switch fragment: ${w.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${b(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${R} @ ${0|k} bps`),s.trigger(D.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(F.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new Gs(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.FRAG_LOADING,this.onFragLoading,this),t.on(D.FRAG_LOADED,this.onFragLoaded,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this),t.on(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(D.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(D.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.FRAG_LOADING,this.onFragLoading,this),t.off(D.FRAG_LOADED,this.onFragLoaded,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this),t.off(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(D.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(D.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.start;b(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===$e&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:s,id:e.type};this.onFragBuffered(D.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==$e||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,e,t,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return F.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,h,d);if(t>=0)return t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,F.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(F.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=s.levels[n],g=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[d],y=!(null==v||null==(o=v.details)||!o.live),E=-1===m||-1===h;let T,S="SDR",L=(null==v?void 0:v.frameRate)||0;const{audioPreference:A,videoPreference:R}=p,w=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce(((t,s)=>{if(!s.codecSet)return t;const i=s.audioGroups;let r=t[s.codecSet];r||(t[s.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,s.bitrate);const n=Math.min(s.height,s.width);return r.minHeight=Math.min(r.minHeight,n),r.minFramerate=Math.min(r.minFramerate,s.frameRate),r.maxScore=Math.max(r.maxScore,s.score),r.fragmentError+=s.fragmentError,r.videoRanges[s.videoRange]=(r.videoRanges[s.videoRange]||0)+1,i&&i.forEach((t=>{if(!t)return;const s=e.groups[t];s&&(r.hasDefaultAudio=r.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{r.channels[t]=(r.channels[t]||0)+s.channels[t]})))})),t}),{})}(f,w,e,s)),r=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=a&&2===parseInt(a);let h=!0,d=!1,c=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:v}=Ws(e,r);for(let e=n.length;e--;){const s=t[n[e]];h=s.channels[2]>0,c=Math.min(c,s.minHeight),u=Math.min(u,s.minFramerate),f=Math.min(f,s.minBitrate);const i=v.filter((t=>s.videoRanges[t]>0));i.length>0&&(d=!0,m=i)}c=b(c)?c:0,u=b(u)?u:0;const y=Math.max(1080,c),E=Math.max(30,u);return f=b(f)?f:s,s=Math.max(f,s),d||(e=void 0,m=[]),{codecSet:n.reduce(((e,i)=>{const r=t[i];if(i===e)return e;if(r.minBitrate>s)return js(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return js(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return js(i,`audio codec preference "${o}" not found`),e;if(a&&!l){if(!r.channels[a])return js(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||l)&&h&&0===r.channels[2])return js(i,"no renditions with stereo sound found"),e;return r.minHeight>y?(js(i,`min resolution of ${r.minHeight} > maximum of ${y}`),e):r.minFramerate>E?(js(i,`min framerate of ${r.minFramerate} > maximum of ${E}`),e):m.some((t=>r.videoRanges[t]>0))?r.maxScore=ye(e)||r.fragmentError>t[e].fragmentError)?e:(g=r.maxScore,i):(js(i,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),e)}),void 0),videoRanges:m,preferHDR:p,minFramerate:u,minBitrate:f}}(i,S,t,A,R),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=r;T=n,S=h?a[a.length-1]:a[0],L=o,t=Math.max(t,l),F.log(`[abr] picked start tier ${JSON.stringify(r)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const k=u?u.duration:c?c.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,I=[];for(let o=s;o>=e;o--){var _;const e=f[o],c=o>d;if(!e)continue;if(p.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&Vs(e,w,S,L,t,A)?(e.supportedPromise=Ys(e,w,s),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?F.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${JSON.stringify(t)}`):t.supported||(F.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${i} ${JSON.stringify(t)}`),i>-1&&s.length>1&&(F.log(`[abr] Removing unsupported level ${i}`),this.hls.removeLevel(i)))}))):e.supportedResult=Ks}if(T&&e.codecSet!==T||S&&e.videoRange!==S||c&&L>e.frameRate||!c&&L>0&&L=2*k&&0===r?f[o].averageBitrate:f[o].maxBitrate,P=this.getTimeToLoadFrag(D,C,x*R,void 0===g);if(C>=x&&(o===h||0===e.loadError&&0===e.fragmentError)&&(P<=D||!b(P)||y&&!this.bitrateTestDelay||P${o} adjustedbw(${Math.round(C)})-bitrate=${Math.round(C-x)} ttfb:${D.toFixed(1)} avgDuration:${R.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${P.toFixed(1)} firstSelection:${E} codecSet:${T} videoRange:${S} hls.loadLevel:${m}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls,i=Math.min(Math.max(t,s),e);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}},bufferController:class{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=t=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(D.MEDIA_ATTACHED,{media:t,mediaSource:e})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&F.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var s;this.appendSource=(s=ue(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.log=F.log.bind(F,e),this.warn=F.warn.bind(F,e),this.error=F.error.bind(F,e),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:t}=this;t.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.BUFFER_RESET,this.onBufferReset,this),t.on(D.BUFFER_APPENDING,this.onBufferAppending,this),t.on(D.BUFFER_CODECS,this.onBufferCodecs,this),t.on(D.BUFFER_EOS,this.onBufferEos,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(D.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(D.FRAG_PARSED,this.onFragParsed,this),t.on(D.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.BUFFER_RESET,this.onBufferReset,this),t.off(D.BUFFER_APPENDING,this.onBufferAppending,this),t.off(D.BUFFER_CODECS,this.onBufferCodecs,this),t.off(D.BUFFER_EOS,this.onBufferEos,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(D.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(D.FRAG_PARSED,this.onFragParsed,this),t.off(D.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new qr(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const s=this.media=e.media,i=ue(this.appendSource);if(s&&i){var r;const t=this.mediaSource=new i;this.log(`created media source: ${null==(r=t.constructor)?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming));const e=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{s.removeAttribute("src");const i=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||i&&t instanceof i,zr(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=this;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&zr(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(D.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var s;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length,i=Object.keys(e);if(i.forEach((t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var i;const{id:r,codec:n,levelCodec:a,container:o,metadata:l}=e[t],h=Le(s.codec,s.levelCodec),d=null==h?void 0:h.replace(Xr,"$1");let c=Le(n,a);const u=null==(i=c)?void 0:i.replace(Xr,"$1");if(c&&d!==u){"audio"===t.slice(0,5)&&(c=Se(c,this.appendSource));const e=`${o};codecs=${c}`;this.appendChangeType(t,e),this.log(`switching codec ${h} to ${c}`),this.tracks[t]={buffer:s.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:r}}}}else this.pendingTracks[t]=e[t]})),s)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:s}=this,i={execute:()=>{const i=this.sourceBuffer[t];i&&(this.log(`changing ${t} sourceBuffer type to ${e}`),i.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};s.append(i,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:s,operationQueue:i,tracks:r}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=e,d=h.buffering[a],c=self.performance.now();d.start=c;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=c),f&&0===f.start&&(f.start=c);const g=r.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=o.start,v={execute:()=>{if(d.executeStart=self.performance.now(),m){const t=this.sourceBuffer[a];if(t){const e=p-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();d.executeEnd=d.end=t,0===u.first&&(u.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=oi.getBuffered(e[t]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(D.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:s})},onError:t=>{const e={type:I.MEDIA_ERROR,parent:o.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=_.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=_.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${s.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=s.config.appendErrorMaxRetry&&(e.fatal=!0)}s.trigger(D.ERROR,e)}};i.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:s}=this,i=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(D.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?s.append(i(e.type),e.type):this.getSourceBufferTypes().forEach((t=>{s.append(i(t),t)}))}onFragParsed(t,e){const{frag:s,part:i}=e,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[V]?r.push("audiovideo"):(n[K]&&r.push("audio"),n[H]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.hls.trigger(D.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type})}),r)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce(((t,s)=>{const i=this.sourceBuffer[s];return!i||e.type&&e.type!==s||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${s} sourceBuffer now EOS`))),t&&!(i&&!i.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)}));const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||null===e)return;if(!this.getSourceBufferTypes().length)return;const i=t.config,r=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(b(a)&&a>0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}if(b(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){const t=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),e=Math.max(t,n),s=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(t,e,s){const{details:i,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((n=>{const a=r[n];if(a){const r=oi.getBuffered(a);if(r.length>0&&s>r.start(0)){if(this.hls.trigger(D.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=i&&i.live)this.hls.trigger(D.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(a.ended&&r.end(r.length-1)-t<2*e)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(D.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}}))}flushFrontBuffer(t,e,s){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach((r=>{const n=i[r];if(n){const i=oi.getBuffered(n),a=i.length;if(a<2)return;const o=i.start(a-1),l=i.end(a-1);if(s>o||t>=o&&t<=l)return;if(n.ended&&t-l<2*e)return void this.log(`Cannot flush ${r} front buffer while SourceBuffer is in ended state`);this.hls.trigger(D.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:r})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:s,mediaSource:i}=this,r=t.fragments[0].start+t.totalduration,n=s.duration,a=b(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(t)):(r>a&&r>n||!b(n))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(t){const e=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=e&&e.setLiveSeekableRange){const i=Math.max(0,s[0].start),r=Math.max(i,i+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${i}-${r}.`),e.setLiveSeekableRange(i,r)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&(!t||2===i||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(D.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{e.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const r in t)if(!e[r]){var i;const n=t[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let a=-1===(null==(i=n.levelCodec)?void 0:i.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===r.slice(0,5)&&(a=Se(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[r]=s.addSourceBuffer(o),i=r;this.addBufferListener(i,"updatestart",this._onSBUpdateStart),this.addBufferListener(i,"updateend",this._onSBUpdateEnd),this.addBufferListener(i,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(i,"bufferedchange",((t,e)=>{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger(D.BUFFER_FLUSHED,{type:r})})),this.tracks[r]={buffer:t,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:r,mimeType:o})}}}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const{operationQueue:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(i)}removeExecutor(t,e,s){const{media:i,mediaSource:r,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!i||!r||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const l=b(i.duration)?i.duration:1/0,h=b(r.duration)?r.duration:1/0,d=Math.max(0,e),c=Math.min(s,l,h);c>d&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${d},${c}] from the ${t} SourceBuffer`),o.remove(d,c)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.sourceBuffer[e];if(s)s.ended=!1,s.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:s}=this,i=e.map((t=>s.appendBlocker(t)));Promise.all(i).then((()=>{t(),e.forEach((t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||s.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,s){const i=this.sourceBuffer[t];if(!i)return;const r=s.bind(this,t);this.listeners[t].push({event:e,listener:r}),i.addEventListener(e,r)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach((t=>{e.removeEventListener(t.event,t.listener)}))}},capLevelController:Wn,errorController:class{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=F.log.bind(F,"[info]:"),this.warn=F.warn.bind(F,"[warning]:"),this.error=F.error.bind(F,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(D.ERROR,this.onError,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(D.ERROR,this.onError,this),t.off(D.ERROR,this.onErrorOut,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===$e?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var s,i;if(e.fatal)return;const r=this.hls,n=e.context;switch(e.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case _.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction={action:xs,flags:Os});case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ps);case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===$e?e.level:r.loadLevel;e.details===_.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=r.levels[r.loadLevel];if(t&&(n.type===Ue&&t.hasAudioGroup(n.groupId)||n.type===Be&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Ps,void(e.errorAction.flags=Ns)}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.levels[r.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?e.errorAction={action:Ps,flags:Us,hdcpLevel:s}:this.keySystemError(e)}return;case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(i=e.level)?i:r.loadLevel));case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:xs,flags:Os})}e.type===I.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const s=Rs(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(ks(s,i,As(t),t.response))return{action:Fs,flags:Os,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Rs(t.details.startsWith("key")?n:r,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(i){t.details!==_.FRAG_GAP&&i.fragmentError++;if(ks(a,o,As(t),t.response))return{action:Fs,flags:Os,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,e===_.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===Ge&&e===_.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===_.BUFFER_ADD_CODEC_ERROR||e===_.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:t})=>i.audioCodec!==t)),m="video"===t.sourceBufferName&&(e===_.BUFFER_ADD_CODEC_ERROR||e===_.BUFFER_APPEND_ERROR)&&h.some((({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e)),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(e===_.FRAG_GAP&&f===$e&&t.frag){const e=h[r].details;if(e){const s=Is(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===Ue&&s.hasAudioGroup(v)||p===Be&&s.hasSubtitleGroup(v))continue;if(f===Ge&&null!=(a=i.audioGroups)&&a.some((t=>s.hasAudioGroup(t)))||f===Ke&&null!=(o=i.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||g&&i.audioCodec===s.audioCodec||!g&&i.audioCodec!==s.audioCodec||m&&i.codecSet===s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ps,flags:Os,nextAutoLevel:l}}return{action:Ps,flags:Ns}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case xs:break;case Ps:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===_.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case Os:this.switchLevel(t,n);break;case Us:r&&(e.maxHdcpLevel=as[as.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,n)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(D.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;F.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(D.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ut,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Pa,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Oi{constructor(t,e,s){super(t,e,s,"[subtitle-stream-controller]",Ke),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.ERROR,this.onError,this),t.on(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(D.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(D.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.ERROR,this.onError,this),t.off(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(D.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(D.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=bi,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:i}=e;if(this.fragPrevious=s,this.state=bi,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let t=0;t=r[t].start&&a<=r[t].end){n=r[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let s=0;snew fs(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new fs(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ke),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,Es(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(fi(n,t),l=n.fragments[0].start):e&&(l=e.start,Es(n,l))}if(o.details=n,this.levelLastLoaded=o,a===i&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===bi)){Is(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch((t=>{throw r.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((s=>{const i=performance.now();r.trigger(D.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:i}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=bi}))}}doTick(){if(this.media){if(this.state===bi){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;const{config:i}=this,r=this.getLoadPosition(),n=oi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,$e),h=s.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const d=h.fragments,c=d.length,u=h.edge;let f=null;const g=this.fragPrevious;if(au-t?0:t;f=Is(g,d,Math.max(d[0].start,a),e),!f&&g&&g.startthis.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=ze(this.media.textTracks);for(let s=0;s-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.LEVEL_LOADING,this.onLevelLoading,this),t.on(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(D.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.LEVEL_LOADING,this.onLevelLoading,this),t.off(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(D.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);ze(this.media.textTracks).forEach((t=>{qe(t)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=qs(e,t);if(s>-1)r=t[s];else{const t=qs(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(D.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i),t}if(s)return null;{const s=qs(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const s=e.id,i=e.groupId;let r=e.url;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(D.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=ze(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter((t=>Wr(s,t)))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==i&&(t.mode="disabled")})),i){const t=this.subtitleDisplay?"showing":"hidden";i.mode!==t&&(i.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!b(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(D.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=i;this.hls.trigger(D.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(d)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(D.FRAG_LOADING,this.onFragLoading,this),t.on(D.FRAG_LOADED,this.onFragLoaded,this),t.on(D.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(D.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(D.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(D.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(D.FRAG_LOADING,this.onFragLoading,this),t.off(D.FRAG_LOADED,this.onFragLoaded,this),t.off(D.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(D.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(D.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(D.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new vn(this,"textTrack1"),e=new vn(this,"textTrack2"),s=new vn(this,"textTrack3"),i=new vn(this,"textTrack4");this.cea608Parser1=new gn(1,t,e),this.cea608Parser2=new gn(3,s,i)}}addCues(t,e,s,i,r){let n=!1;for(let t=r.length;t--;){const i=r[t],d=(a=i[0],o=i[1],l=e,h=s,Math.min(o,h)-Math.max(a,l));if(d>=0&&(i[0]=Math.min(i[0],e),i[1]=Math.max(i[1],s),n=!0,d/(s-e)>.5))return}var a,o,l,h;if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,s,i)}else{const r=this.Cues.newCue(null,e,s,i);this.hls.trigger(D.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:n}=this;"main"===s&&(this.initPTS[e.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach((t=>{this.onFragLoaded(D.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i{qe(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;tt.textCodec===Pn));if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Vr(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?ze(t.textTracks):null;if(this.tracks.forEach(((t,s)=>{let i;if(e){let s=null;for(let i=0;inull!==t)).map((t=>t.label));t.length&&F.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(D.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s=`textTrack${e[1]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===$e){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.type===Ke)if(i.byteLength){const t=s.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===Pn?this._parseIMSC1(s,i):this._parseVTTs(e)}}else this.hls.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;Nn(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),s.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{F.log(`Failed to parse IMSC1: ${e}`),s.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(t);const o=this.hls;xn(null!=(e=s.initSegment)&&e.data?Qt(s.initSegment.data,new Uint8Array(i)):i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(s,i),F.log(`Failed to parse VTT cue: ${e}`),r&&a>s.cc||o.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})}))}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||Nn(e,this.initPTS[t.cc],(()=>{s.textCodec=Pn,this._parseIMSC1(t,e)}),(()=>{s.textCodec="wvtt"}))}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach((t=>je(s,t)))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger(D.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===Ke&&this.onFragLoaded(D.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!s||!i)return;const{frag:r,samples:n}=e;if(r.type!==$e||"NONE"!==this.closedCaptionsForLevel(r))for(let t=0;tXe(t[i],e,s)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==i){const{textTracks:t}=this;Object.keys(t).forEach((s=>Xe(t[s],e,i)))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=bi):(this.loadedmetadata=!1,this.state=Ii),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case bi:this.doTickIdle();break;case Ii:{var t;const{levels:e,trackId:s}=this,i=null==e||null==(t=e[s])?void 0:t.details;if(i){if(this.waitForCdnTuneIn(i))break;this.state=Mi}break}case Di:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=bi}break}case Mi:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=ki;const t={frag:e,part:s,payload:i.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=oi.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);_s(s.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=bi}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=bi)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:s,trackId:i}=this,r=t.config;if(!s&&(this.startFragRequested||!r.startFragPrefetch)||null==e||!e[i])return;const n=e[i],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=Ii);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,K,Ge));const l=this.getFwdBufferInfo(o,Ge);if(null===l)return;const{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return t.trigger(D.BUFFER_EOS,{type:"audio"}),void(this.state=xi);const c=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,$e),u=l.len,f=this.getMaxBufferLength(null==c?void 0:c.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(d&&s){const t=this.getLoadPosition();h&&!Yr(d.attrs,h.attrs)&&(p=t),a.PTSKnown&&tm||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05)}if(u>=f&&!d&&pc.end+a.targetduration;if(E||(null==c||!c.len)&&l.len){const t=this.getAppendedFrag(v.start,$e);if(null===t)return;if(y||(y=!!t.gap||!!E&&0===c.len),E&&!y||y&&l.nextStart&&l.nextStartnew fs(t)))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=e,this.state=bi,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=Ri),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(D.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:i}=this,{details:r,id:n}=e;if(!i)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const a=i[n];let o=0;if(r.live||null!=(s=a.details)&&s.live){this.checkLiveUpdate(r);const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;var l;if(!a.details&&r.hasProgramDateTime&&t.hasProgramDateTime)fi(r,t),o=r.fragments[0].start;else o=this.alignPlaylists(r,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=r,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(this.mainDetails||r,o),this.state!==Ii||this.waitForCdnTuneIn(r)||(this.state=bi),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:i,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Hr(this.hls,Ge,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new li(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n);c.push(r,f,d,"",s,i,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ni,complete:!1};t.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=Mi}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===Ge)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==s.sn){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(D.AUDIO_TRACK_SWITCHED,S({},t)))}this.fragBufferedComplete(s,i)}else if(!this.loadedmetadata&&s.type===$e){const t=this.videoBuffer||this.media;if(t){oi.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var s;if(e.fatal)this.state=Pi;else switch(e.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ge,e);break;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ii||(null==(s=e.context)?void 0:s.type)!==Ue||(this.state=bi);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===_.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==H&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==H){this.flushing=!1,this.bufferFlushed=!0,this.state===xi&&(this.state=bi);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,Ge),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&d){if(this.state=_i,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,g.tracks,t,n),i.trigger(D.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}if(c){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[K]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(K,t,e,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=R({id:s,frag:o,details:d},f);i.trigger(D.FRAG_PARSING_METADATA,t)}if(u){const t=R({id:s,frag:o,details:d},u);i.trigger(D.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s,i){if(this.state!==_i)return;e.video&&delete e.video;const r=e.audio;if(!r)return;r.id="audio";const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(D.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(D.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.fragCurrent=t,this.switchingTrack||i===Zs||i===ei)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Mi;const s=this.mainDetails;s&&s.fragments[0].start!==e.details.fragments[0].start&&fi(e.details,s)}else this.startFragRequested=!0,super.loadFragment(t,e,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:s}=this,i=null==s?void 0:s.attrs,r=t.attrs;e&&i&&(i.CHANNELS!==r.CHANNELS||s.name!==t.name||s.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(D.AUDIO_TRACK_SWITCHED,S({},t))}},audioTrackController:class extends Bs{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.LEVEL_LOADING,this.onLevelLoading,this),t.on(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(D.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(D.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.LEVEL_LOADING,this.onLevelLoading,this),t.off(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(D.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(D.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=qs(e,t,zs);if(s>-1)r=t[s];else{const t=qs(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(D.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==Ue||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Xs(t,i,zs))return i;const r=qs(t,this.tracksInGroup,zs);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce(((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t}),{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Qs(e,i,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return qs(t,n,r)>-1}));return d>-1?d:Qs(e,i,(e=>{const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return qs(t,n,r)>-1}))}(t,e.levels,s,i,zs);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=qs(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t],r=i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger(D.AUDIO_TRACK_SWITCHING,S({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:zn.MANIFEST,su:!this.initialized})}catch(t){F.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,s=this.hls.levels[e.level],i=this.getObjectType(e),r={d:1e3*e.duration,ot:i};i!==zn.VIDEO&&i!==zn.AUDIO&&i!=zn.MUXED||(r.br=s.bitrate/1e3,r.tb=this.getTopBandwidth(i)/1e3,r.bl=this.getBufferLength(i)),this.apply(t,r)}catch(t){F.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)}))}}}(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHED,this.onMediaDetached,this),t.on(D.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHED,this.onMediaDetached,this),t.off(D.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,i;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer}createData(){var t;return{v:1,sf:Qn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){R(e,this.createData());const s=e.ot===zn.INIT||e.ot===zn.VIDEO||e.ot===zn.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce(((t,s)=>(i.includes(s)&&(t[s]=e[s]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),Sa(t.headers,e)):t.url=Aa(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?zn.TIMED_TEXT:"initSegment"===t.sn?zn.INIT:"audio"===e?zn.AUDIO:"main"===e?this.hls.audioTracks.length?zn.VIDEO:zn.MUXED:void 0}getTopBandwidth(t){let e,s=0;const i=this.hls;if(t===zn.AUDIO)e=i.audioTracks;else{const t=i.maxAutoLevel,s=t>-1?t+1:i.levels.length;e=i.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.hls.media,s=t===zn.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*oi.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}},contentSteeringController:class{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=F.log.bind(F,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Ps&&s.flags===Ns){const t=this.levels;let i=this.pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=t.reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),s.resolved||F.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${JSON.stringify(i)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this.pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach((t=>{i-s[t]>3e5&&delete s[t]}));for(let i=0;i0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Ls(e),this.hls.trigger(D.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new U(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=ba(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new fs({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(D.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,r);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}});function Fa(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Fa):Object.keys(t).reduce(((e,s)=>(e[s]=Fa(t[s]),e)),{}):t}function Oa(t){const e=t.loader;if(e!==Ia&&e!==ka)F.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=Ia,t.progressive=!0,t.enableSoftwareAES=!0,F.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let Na;class Ua extends Bs{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this),t.on(D.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this),t.off(D.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e,h;const d=t.attrs;let{audioCodec:c,videoCodec:u}=t;-1!==(null==(e=c)?void 0:e.indexOf("mp4a.40.34"))&&(Na||(Na=/chrome|firefox/i.test(navigator.userAgent)),Na&&(t.audioCodec=c=void 0)),c&&(t.audioCodec=c=Se(c,s)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}(u));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!c),null!=m&&m.length||c&&!ge(c,"audio",s)||u&&!ge(u,"video",s))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=d,L=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(r[L])if(r[L].uri===t.url||t.attrs["PATHWAY-ID"])r[L].addGroupId("audio",d.AUDIO),r[L].addGroupId("text",d.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=new fs(t);r[L]=s,i.push(s)}else{const e=new fs(t);r[L]=e,n[L]=1,i.push(e)}})),this.filterAndSortMediaOptions(i,e,a,o,l)}filterAndSortMediaOptions(t,e,s,i,r){let n=[],a=[],o=t;if((s||i)&&r&&(o=o.filter((({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&(!!(r=e)&&os.indexOf(r)>-1);var r}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}));if(e.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;n=e.audioTracks.filter((e=>!e.audioCodec||ge(e.audioCodec,"audio",t))),Ba(n)}e.subtitles&&(a=e.subtitles,Ba(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return os.indexOf(t.videoRange)-os.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=ve(t.videoCodec),i=ve(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=ye(t.codecSet),i=ye(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;ts&&s===Ma.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const c=r&&!i,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:!c&&n.some((t=>!!t.url))};this.hls.trigger(D.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const s=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(D.ERROR,{type:I.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&n.details&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(D.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===Ne&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===$e){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=this._levels[i];var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));i===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(i,e,n.details)):null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let i=s.uri;if(t)try{i=t.addDirectives(i)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${r?" Pathway "+r:""} ${i}`),this.clearTimer(),this.hls.trigger(D.LEVEL_LOADING,{url:i,level:e,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const s=this._levels.filter(((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));Ls(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(D.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(D.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Ba(t){const e={};t.forEach((t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++}))}class $a{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=_.KEY_LOAD_ERROR,s,i,r){return new yi({type:I.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=t;for(let t=0;t{r.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var s,i;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const s=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(i=a)&&i.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(r.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,s)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,i=new(0,s.loader)(s);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,s,i)=>{const{frag:a,keyInfo:o,url:l}=s;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,S({url:a.url,data:void 0},t)))},onTimeout:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,_.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,h)}))}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function Ga(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ka(){if(!ue())return!1;const t=Ga();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class Ha{constructor(t,e,s,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:s,media:i,stalled:r}=this;if(null===i)return;const{currentTime:n,seeking:a}=i,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==t){if(this.moved=!0,a||(this.nudgeRetry=0),null!==r){if(this.stallReported){const t=self.performance.now()-r;F.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(i.paused&&!a||i.ended||0===i.playbackRate||!oi.getBuffered(i).length)return void(this.nudgeRetry=0);const h=oi.bufferInfo(i,n,0),d=h.nextStart||0;if(a){const t=h.len>2,s=!d||e&&e.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;if(!(h.len>0)&&!d)return;const t=Math.max(d,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(c=e.details)?void 0:c.live)?2*e.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||r))return void(i.paused||this._trySkipBufferHole(r))}const u=self.performance.now();if(null===r)return void(this.stalled=u);const f=u-r;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=oi.bufferInfo(i,n,s.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:s,fragmentTracker:i,media:r}=this;if(null===r)return;const n=r.currentTime,a=i.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-n1e3*s.highBufferWatchdogPeriod&&(F.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);F.warn(i.message),e.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:s,media:i}=this;if(null===i)return 0;const r=i.currentTime,n=oi.bufferInfo(i,r,0),a=r0&&n.len<1&&i.readyState<3,h=a-r;if(h>0&&(o||l)){if(h>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===r){const t=e.getAppendedFrag(0,$e);t&&a1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=bi,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Ri}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Fi:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(i))break;this.state=bi;break}if(this.hls.nextLoadLevel!==this.level){this.state=bi;break}break}case Di:{var t;const e=self.performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,s=null==t?void 0:t[e];this.resetStartWhenNotLoaded(s||null),this.state=bi}}}this.state===bi&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=t.nextLoadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(D.BUFFER_EOS,t),void(this.state=xi)}t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===Fi||l.live&&this.levelLastLoaded!==n)return this.level=r,void(this.state=Fi);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==si){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?K:H,e=(t===H?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,$e)}u=this.getNextFragmentLoopLoading(u,l,a,$e,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);this.fragCurrent=t,i===Zs||i===ei?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,s)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,$e)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let s;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case wi:case ki:case Di:case _i:case Ci:this.state=bi}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new Ha(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;b(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(D.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(t,e){let s=!1,i=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&i&&!function(){var t;const e=Ga();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==bi)return;const i=s[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=Fi)}onLevelLoaded(t,e){var s;const{levels:i}=this,r=e.level,n=e.details,a=n.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=i[r],l=this.fragCurrent;!l||this.state!==ki&&this.state!==Di||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(s=o.details)&&s.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(D.LEVEL_UPDATED,{details:n,level:r}),this.state===Fi){if(this.waitForCdnTuneIn(n))return;this.state=bi}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:i,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Hr(this.hls,$e,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new li(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const s=this.altAudio;if(!!!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;s&&(t.trigger(D.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(D.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=e.id,i=!!this.hls.audioTracks[s].url;if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s&&s.type!==$e)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ci&&(this.state=bi));const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(t,e){var s;if(e.fatal)this.state=Pi;else switch(e.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError($e,e);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Fi||(null==(s=e.context)?void 0:s.type)!==Ne||(this.state=bi);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===_.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!oi.getBuffered(t).length){const t=this.state!==bi?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=bi,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==K||this.audioOnly&&!this.altAudio){const t=(e===H?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,$e),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e0&&(r{const{hls:i}=this;if(!s||this.fragContextChanged(t))return;e.fragmentError=0,this.state=bi,this.startFragRequested=!1,this.bitrateTest=!1;const r=t.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(D.FRAG_LOADED,s),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:d,text:c,id3:u,initSegment:f}=r,{details:g}=h,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=_i,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,f.tracks,t,n),i.trigger(D.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:f.tracks})}const t=f.initPTS,e=f.timescale;b(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},i.trigger(D.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:e}))}if(d&&g&&"initSegment"!==o.sn){const t=g.fragments[o.sn-1-g.startSN],e=o.sn===g.startSN,s=!t||o.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:i,startDTS:r,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:r,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,t,i,r,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,e||s)}else{if(!e&&!s)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=m;l&&(l.elementaryStreams[K]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(K,t,e,s,i),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(e=u.samples)&&e.length){const t={id:s,frag:o,details:g,samples:u.samples};i.trigger(D.FRAG_PARSING_METADATA,t)}if(g&&c){const t={id:s,frag:o,details:g,samples:c.samples};i.trigger(D.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,i){if(this.state!==_i)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:r,video:n,audiovideo:a}=e;if(r){let e=t.audioCodec;const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===s.indexOf("firefox")&&(e="mp4a.40.5")}e&&-1!==e.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==r.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),r.levelCodec=e,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${r.codec}]`)}n&&(n.levelCodec=t.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(D.BUFFER_CODECS,e),Object.keys(e).forEach((t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(D.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,$e)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=bi}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(oi.isBuffered(t,s)?e=this.getAppendedFrag(s):oi.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger(D.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(D.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,s=this.currentFrag;if(s&&b(e)&&b(s.programDateTime)){const t=s.programDateTime+1e3*(e-s.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Ya{static get version(){return"1.5.15"}static isMSESupported(){return Ka()}static isSupported(){return function(){if(!Ka())return!1;const t=ue();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(pe(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(pe(e,"audio")))))}()}static getMediaSource(){return ue()}static get Events(){return D}static get ErrorTypes(){return I}static get ErrorDetails(){return _}static get DefaultConfig(){return Ya.defaultConfig?Ya.defaultConfig:Ma}static set DefaultConfig(t){Ya.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Kr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){M(t,"debug","log","info","warn","error");try{P.log(`Debug logs enabled for "${e}" in hls.js version 1.5.15`)}catch(t){P=x}}else P=x}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Fa(t),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,n=void 0===e[r],a=[];i.forEach((i=>{const o=`${t}Loading${i}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=s[r].default;switch(e[r]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&F.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${r}": ${JSON.stringify(e[r])}`)})),S(S({},s),e)}(Ya.DefaultConfig,t);this.userConfig=t,e.progressive&&Oa(e);const{abrController:s,bufferController:i,capLevelController:r,errorController:n,fpsController:a}=e,o=new n(this),l=this.abrController=new s(this),h=this.bufferController=new i(this),d=this.capLevelController=new r(this),c=new a(this),u=new Ye(this),f=new rs(this),g=e.contentSteeringController,m=g?new g(this):null,p=this.levelController=new Ua(this,m),v=new ii(this),y=new $a(this.config),E=this.streamController=new Va(this,v,y);d.setStreamController(E),c.setStreamController(E);const T=[u,p,E];m&&T.splice(1,0,m),this.networkControllers=T;const L=[l,h,d,c,f,v];this.audioTrackController=this.createController(e.audioTrackController,T);const A=e.audioStreamController;A&&T.push(new A(this,v,y)),this.subtitleTrackController=this.createController(e.subtitleTrackController,T);const R=e.subtitleStreamController;R&&T.push(new R(this,v,y)),this.createController(e.timelineController,L),y.emeController=this.emeController=this.createController(e.emeController,L),this.cmcdController=this.createController(e.cmcdController,L),this.latencyController=this.createController(ns,L),this.coreComponents=L,T.push(o);const b=o.onErrorOut;"function"==typeof b&&this.on(D.ERROR,b,o)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(F.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===D.ERROR;this.trigger(D.ERROR,{type:I.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){F.log("destroy"),this.trigger(D.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){F.log("attachMedia"),this._media=t,this.trigger(D.MEDIA_ATTACHING,{media:t})}detachMedia(){F.log("detachMedia"),this.trigger(D.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,s=this.url,i=this.url=E.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,F.log(`loadSource:${i}`),e&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(D.MANIFEST_LOADING,{url:t})}startLoad(t=-1){F.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach((e=>{e.startLoad(t)}))}stopLoad(){F.log("stopLoad"),this.started=!1,this.networkControllers.forEach((t=>{t.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.stopLoad()}))}swapAudioCodec(){F.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){F.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){F.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){F.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){F.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){F.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){F.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(F.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return as.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let i=0;i=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=s)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}function Wa(t,e,s){window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.performAction.postMessage({instanceId:t,event:e,data:s})}Ya.defaultConfig=void 0,s.g.isJsCore=!1,s.g.btoa||(s.g.btoa=t.encode),s.g.atob||(s.g.atob=t.decode),"undefined"==typeof window&&(s.g.isJsCore=!0,s.g.navigator={userAgent:"Telegram"},s.g.now=function(){return _JsCorePolyfills.performanceNow()},s.g.window={},s.g.URL={},window.webkit={},window.webkit.messageHandlers={},window.webkit.messageHandlers.performAction={},window.webkit.messageHandlers.performAction.postMessage=function(t){_JsCorePolyfills.postMessage(t)},s.g.self.location={href:"http://127.0.0.1"},s.g.self.setTimeout=s.g.setTimeout,s.g.self.setInterval=s.g.setInterval,s.g.self.clearTimeout=s.g.clearTimeout,s.g.self.clearInterval=s.g.clearTimeout,s.g.self.URL=s.g.URL,s.g.self.Date=s.g.Date),window.bridgeObjectMap={},window.bridgeCallbackMap={},window.bridgeInvokeAsync=function(t,e,s,i){var r,n=new Promise((function(t,e){r=t}));const a=window.nextInternalId;return window.nextInternalId+=1,window.bridgeCallbackMap[a]=r,window.webkit.messageHandlers&&window.webkit.messageHandlers.performAction.postMessage({event:"bridgeInvoke",data:{bridgeId:t,className:e,methodName:s,params:i,callbackId:a}}),n},window.nextInternalId=0,window.mediaSourceMap={},"undefined"!=typeof window&&(window.MediaSource=d,window.ManagedMediaSource=d,window.SourceBuffer=h,window.XMLHttpRequest=c,URL.createObjectURL=function(t){const e="blob:mock-media-source:"+t.internalId;return window.mediaSourceMap[e]=t,e},URL.revokeObjectURL=function(t){},s.g.isJsCore&&(s.g.HTMLVideoElement=a,s.g.self.MediaSource=window.MediaSource,s.g.self.ManagedMediaSource=window.ManagedMediaSource,s.g.self.SourceBuffer=window.SourceBuffer,s.g.self.XMLHttpRequest=window.XMLHttpRequest,s.g.self.HTMLVideoElement=a));class ja{constructor(t){this.id=t,this.isManifestParsed=!1,this.currentTimeUpdateTimeout=null,this.notifySeekedOnNextStatusUpdate=!1,this.video=new a(this.id)}playerInitialize(t){this.video.addEventListener("playing",(()=>{this.refreshPlayerStatus()})),this.video.addEventListener("pause",(()=>{this.refreshPlayerStatus()})),this.video.addEventListener("seeking",(()=>{this.refreshPlayerStatus()})),this.video.addEventListener("waiting",(()=>{this.refreshPlayerStatus()})),this.hls=new Ya({startLevel:0,testBandwidth:!1,debug:t.debug||!0,autoStartLoad:!1,backBufferLength:30,maxBufferLength:60,maxMaxBufferLength:60,maxFragLookUpTolerance:.001,nudgeMaxRetry:1e4}),this.hls.on(Ya.Events.MANIFEST_PARSED,(()=>{this.isManifestParsed=!0,this.refreshPlayerStatus()})),this.hls.on(Ya.Events.LEVEL_SWITCHED,(()=>{this.refreshPlayerStatus()})),this.hls.on(Ya.Events.LEVELS_UPDATED,(()=>{this.refreshPlayerStatus()})),this.hls.loadSource(t.urlPrefix+"master.m3u8"),this.hls.attachMedia(this.video)}playerLoad(t){this.hls.startLevel=t,this.hls.startLoad(-1,!1)}playerPlay(){this.video.play()}playerPause(){this.video.pause()}playerSetBaseRate(t){this.video.playbackRate=t}playerSetLevel(t){this.hls.currentLevel=t>=0?t:-1}playerSetCapAutoLevel(t){t>=0?this.hls.autoLevelCapping=t:(this.hls.autoLevelCapping=-1,this.hls.currentLevel=-1)}playerSeek(t){this.video.currentTime=t}playerSetIsMuted(t){this.video.muted=t}getLevels(){for(var t=[],e=0;e2&&(t=!0),Wa(this.id,"playerStatus",{isReady:this.isManifestParsed,isPlaying:!this.video.paused,rate:t?this.video.playbackRate:0,defaultRate:this.video.playbackRate,levels:this.getLevels(),currentLevel:this.hls.currentLevel}),this.refreshPlayerCurrentTime(),t?null==this.currentTimeUpdateTimeout&&(this.currentTimeUpdateTimeout=setTimeout((()=>{this.refreshPlayerCurrentTime()}),200)):null!=this.currentTimeUpdateTimeout&&(clearTimeout(this.currentTimeUpdateTimeout),this.currentTimeUpdateTimeout=null),this.notifySeekedOnNextStatusUpdate&&(this.notifySeekedOnNextStatusUpdate=!1,this.video.notifySeeked())}playerNotifySeekedOnNextStatusUpdate(){this.notifySeekedOnNextStatusUpdate=!0}refreshPlayerCurrentTime(){Wa(this.id,"playerCurrentTime",{value:this.video.currentTime}),this.currentTimeUpdateTimeout=setTimeout((()=>{this.refreshPlayerCurrentTime()}),200)}}window.invokeOnLoad=function(){Wa(this.id,"windowOnLoad",{})},window.onload=()=>{window.invokeOnLoad()},window.hlsPlayer_instances={},window.hlsPlayer_makeInstance=function(t){window.hlsPlayer_instances[t]=new ja(t)},window.hlsPlayer_destroyInstance=function(t){const e=window.hlsPlayer_instances[t];e&&(delete window.hlsPlayer_instances[t],e.video.pause(),e.hls.destroy())},window.bridgeInvokeCallback=function(t,e){const s=window.bridgeCallbackMap[t];s&&s(e)},s.g.isJsCore&&window.onload()})()})(); \ No newline at end of file diff --git a/submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js.LICENSE.txt b/submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js.LICENSE.txt new file mode 100644 index 0000000000..fdc404b69a --- /dev/null +++ b/submodules/TelegramUniversalVideoContent/HlsBundle/index/index.bundle.js.LICENSE.txt @@ -0,0 +1 @@ +/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */ diff --git a/submodules/TelegramUniversalVideoContent/HlsBundle/index.html b/submodules/TelegramUniversalVideoContent/HlsBundle/index/index.html similarity index 100% rename from submodules/TelegramUniversalVideoContent/HlsBundle/index.html rename to submodules/TelegramUniversalVideoContent/HlsBundle/index/index.html diff --git a/submodules/TelegramUniversalVideoContent/PlayerSource/build.sh b/submodules/TelegramUniversalVideoContent/PlayerSource/build.sh index 0fbfb5b637..84a0c7a4bb 100644 --- a/submodules/TelegramUniversalVideoContent/PlayerSource/build.sh +++ b/submodules/TelegramUniversalVideoContent/PlayerSource/build.sh @@ -1,6 +1,7 @@ #!/bin/sh -rm -rf ../HlsBundle -mkdir ../HlsBundle +mkdir -p ../HlsBundle +rm -rf ../HlsBundle/index +mkdir ../HlsBundle/index npm run build-$1 -cp ./dist/* ../HlsBundle/ +cp ./dist/* ../HlsBundle/index/ diff --git a/submodules/TelegramUniversalVideoContent/PlayerSource/package-lock.json b/submodules/TelegramUniversalVideoContent/PlayerSource/package-lock.json index 6cb6a5f8b8..448fee9f39 100644 --- a/submodules/TelegramUniversalVideoContent/PlayerSource/package-lock.json +++ b/submodules/TelegramUniversalVideoContent/PlayerSource/package-lock.json @@ -9,6 +9,8 @@ "version": "1.0.0", "license": "MIT", "dependencies": { + "base-64": "^1.0.0", + "event-target-polyfill": "^0.0.4", "hls.js": "^1.5.15" }, "devDependencies": { @@ -657,6 +659,11 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, + "node_modules/base-64": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==" + }, "node_modules/batch": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", @@ -1453,6 +1460,11 @@ "node": ">= 0.6" } }, + "node_modules/event-target-polyfill": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/event-target-polyfill/-/event-target-polyfill-0.0.4.tgz", + "integrity": "sha512-Gs6RLjzlLRdT8X9ZipJdIZI/Y6/HhRLyq9RdDlCsnpxr/+Nn6bU2EFGuC94GjxqhM+Nmij2Vcq98yoHrU8uNFQ==" + }, "node_modules/eventemitter3": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", diff --git a/submodules/TelegramUniversalVideoContent/PlayerSource/package.json b/submodules/TelegramUniversalVideoContent/PlayerSource/package.json index 00b6d56091..7d90f1f3d1 100644 --- a/submodules/TelegramUniversalVideoContent/PlayerSource/package.json +++ b/submodules/TelegramUniversalVideoContent/PlayerSource/package.json @@ -25,6 +25,8 @@ "webpack-merge": "^6.0.1" }, "dependencies": { + "base-64": "^1.0.0", + "event-target-polyfill": "^0.0.4", "hls.js": "^1.5.15" } } diff --git a/submodules/TelegramUniversalVideoContent/PlayerSource/src/VideoElementStub.js b/submodules/TelegramUniversalVideoContent/PlayerSource/src/VideoElementStub.js index cd59430c34..acdd0d918d 100644 --- a/submodules/TelegramUniversalVideoContent/PlayerSource/src/VideoElementStub.js +++ b/submodules/TelegramUniversalVideoContent/PlayerSource/src/VideoElementStub.js @@ -109,8 +109,15 @@ export class VideoElementStub extends EventTarget { } querySelectorAll(name) { - const fragment = document.createDocumentFragment(); - return fragment.querySelectorAll('*'); + if (global.isJsCore) { + return []; + } else { + const fragment = document.createDocumentFragment(); + return fragment.querySelectorAll('*'); + } + } + + removeChild(child) { } updateBufferedFromMediaSource() { diff --git a/submodules/TelegramUniversalVideoContent/PlayerSource/src/index.js b/submodules/TelegramUniversalVideoContent/PlayerSource/src/index.js index 1df18a87b0..fdfe8ec524 100644 --- a/submodules/TelegramUniversalVideoContent/PlayerSource/src/index.js +++ b/submodules/TelegramUniversalVideoContent/PlayerSource/src/index.js @@ -1,8 +1,60 @@ -import Hls from "hls.js"; +import "event-target-polyfill"; +import {decode, encode} from "base-64"; + import { VideoElementStub } from "./VideoElementStub.js" import { MediaSourceStub, SourceBufferStub } from "./MediaSourceStub.js" import { XMLHttpRequestStub } from "./XMLHttpRequestStub.js" +global.isJsCore = false; + +if (!global.btoa) { + global.btoa = encode; +} + +if (!global.atob) { + global.atob = decode; +} + +if (typeof window === 'undefined') { + global.isJsCore = true; + + global.navigator = { + userAgent: "Telegram" + }; + + global.now = function() { + return _JsCorePolyfills.performanceNow(); + }; + + global.window = { + }; + + global.URL = { + }; + + window.webkit = { + }; + window.webkit.messageHandlers = { + }; + window.webkit.messageHandlers.performAction = { + }; + window.webkit.messageHandlers.performAction.postMessage = function(dict) { + _JsCorePolyfills.postMessage(dict); + }; + + global.self.location = { + href: "http://127.0.0.1" + }; + global.self.setTimeout = global.setTimeout; + global.self.setInterval = global.setInterval; + global.self.clearTimeout = global.clearTimeout; + global.self.clearInterval = global.clearTimeout; + global.self.URL = global.URL; + global.self.Date = global.Date; +} + +import Hls from "hls.js"; + window.bridgeObjectMap = {}; window.bridgeCallbackMap = {}; @@ -50,12 +102,25 @@ if (typeof window !== 'undefined') { window.ManagedMediaSource = MediaSourceStub; window.SourceBuffer = SourceBufferStub; window.XMLHttpRequest = XMLHttpRequestStub; - + URL.createObjectURL = function(ms) { const url = "blob:mock-media-source:" + ms.internalId; window.mediaSourceMap[url] = ms; return url; }; + + URL.revokeObjectURL = function(url) { + }; + + if (global.isJsCore) { + global.HTMLVideoElement = VideoElementStub; + + global.self.MediaSource = window.MediaSource; + global.self.ManagedMediaSource = window.ManagedMediaSource; + global.self.SourceBuffer = window.SourceBuffer; + global.self.XMLHttpRequest = window.XMLHttpRequest; + global.self.HTMLVideoElement = VideoElementStub; + } } function postPlayerEvent(id, eventName, eventData) { @@ -139,6 +204,15 @@ export class HlsPlayerInstance { } } + playerSetCapAutoLevel(level) { + if (level >= 0) { + this.hls.autoLevelCapping = level; + } else { + this.hls.autoLevelCapping = -1; + this.hls.currentLevel = -1; + } + } + playerSeek(value) { this.video.currentTime = value; } @@ -236,3 +310,7 @@ window.hlsPlayer_destroyInstance = function(id) { } window.bridgeInvokeCallback = bridgeInvokeCallback; + +if (global.isJsCore) { + window.onload(); +} diff --git a/submodules/TelegramUniversalVideoContent/PlayerSource/webpack.dev.js b/submodules/TelegramUniversalVideoContent/PlayerSource/webpack.dev.js index bf02fafa86..13920c0202 100644 --- a/submodules/TelegramUniversalVideoContent/PlayerSource/webpack.dev.js +++ b/submodules/TelegramUniversalVideoContent/PlayerSource/webpack.dev.js @@ -3,7 +3,7 @@ const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'development', - devtool: 'source-map', + devtool: 'inline-source-map', devServer: { static: './dist', }, diff --git a/submodules/TelegramUniversalVideoContent/Sources/HLSVideoContent.swift b/submodules/TelegramUniversalVideoContent/Sources/HLSVideoContent.swift index 27942f6050..ac8c82f501 100644 --- a/submodules/TelegramUniversalVideoContent/Sources/HLSVideoContent.swift +++ b/submodules/TelegramUniversalVideoContent/Sources/HLSVideoContent.swift @@ -188,7 +188,7 @@ public final class HLSVideoContent: UniversalVideoContent { } public let id: AnyHashable - public let nativeId: PlatformVideoContentId + public let nativeId: NativeVideoContentId let userLocation: MediaResourceUserLocation public let fileReference: FileMediaReference public let dimensions: CGSize @@ -199,7 +199,7 @@ public final class HLSVideoContent: UniversalVideoContent { let baseRate: Double let fetchAutomatically: Bool - public init(id: PlatformVideoContentId, userLocation: MediaResourceUserLocation, fileReference: FileMediaReference, streamVideo: Bool = false, loopVideo: Bool = false, enableSound: Bool = true, baseRate: Double = 1.0, fetchAutomatically: Bool = true) { + public init(id: NativeVideoContentId, userLocation: MediaResourceUserLocation, fileReference: FileMediaReference, streamVideo: Bool = false, loopVideo: Bool = false, enableSound: Bool = true, baseRate: Double = 1.0, fetchAutomatically: Bool = true) { self.id = id self.userLocation = userLocation self.nativeId = id @@ -218,9 +218,9 @@ public final class HLSVideoContent: UniversalVideoContent { } public func isEqual(to other: UniversalVideoContent) -> Bool { - if let other = other as? HLSVideoContent { - if case let .message(_, stableId, _) = self.nativeId { - if case .message(_, stableId, _) = other.nativeId { + if let other = other as? NativeVideoContent { + if case let .message(stableId, _) = self.nativeId { + if case .message(stableId, _) = other.nativeId { if self.fileReference.media.isInstantVideo { return true } diff --git a/submodules/TelegramUniversalVideoContent/Sources/HLSVideoJSNativeContentNode.swift b/submodules/TelegramUniversalVideoContent/Sources/HLSVideoJSNativeContentNode.swift index a665d5e984..96af569c31 100644 --- a/submodules/TelegramUniversalVideoContent/Sources/HLSVideoJSNativeContentNode.swift +++ b/submodules/TelegramUniversalVideoContent/Sources/HLSVideoJSNativeContentNode.swift @@ -4,7 +4,6 @@ import SwiftSignalKit import UniversalMediaPlayer import Postbox import TelegramCore -import WebKit import AsyncDisplayKit import AccountContext import TelegramAudio @@ -327,21 +326,11 @@ final class HLSJSServerSource: SharedHLSServer.Source { } } -private class WeakScriptMessageHandler: NSObject, WKScriptMessageHandler { - private let f: (WKScriptMessage) -> () - - init(_ f: @escaping (WKScriptMessage) -> ()) { - self.f = f - - super.init() - } - - func userContentController(_ controller: WKUserContentController, didReceive scriptMessage: WKScriptMessage) { - self.f(scriptMessage) - } +protocol HLSJSContext: AnyObject { + func evaluateJavaScript(_ string: String) } -private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { +private final class SharedHLSVideoJSContext: NSObject { private final class ContextReference { weak var contentNode: HLSVideoJSNativeContentNode? @@ -367,17 +356,17 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { } } - static let shared: SharedHLSVideoWebView = SharedHLSVideoWebView() + static let shared: SharedHLSVideoJSContext = SharedHLSVideoJSContext() private var contextReferences: [Int: ContextReference] = [:] - var webView: WKWebView? + var jsContext: HLSJSContext? var videoElements: [Int: VideoElement] = [:] var mediaSources: [Int: MediaSource] = [:] var sourceBuffers: [Int: SourceBuffer] = [:] - private var isWebViewReady: Bool = false + private var isJsContextReady: Bool = false private var pendingInitializeInstanceIds: [(id: Int, urlPrefix: String)] = [] private var tempTasks: [Int: URLSessionTask] = [:] @@ -392,64 +381,24 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { self.emptyTimer?.invalidate() } - private func createWebView() { - let config = WKWebViewConfiguration() - config.allowsInlineMediaPlayback = true - config.mediaTypesRequiringUserActionForPlayback = [] - config.allowsPictureInPictureMediaPlayback = true - - let userController = WKUserContentController() - - var handleScriptMessage: ((WKScriptMessage) -> Void)? - userController.add(WeakScriptMessageHandler { message in - handleScriptMessage?(message) - }, name: "performAction") - - let isDebug: Bool - #if DEBUG - isDebug = true - #else - isDebug = false - #endif - - config.userContentController = userController - - let webView = WKWebView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 100.0, height: 100.0)), configuration: config) - self.webView = webView - - webView.scrollView.isScrollEnabled = false - webView.allowsLinkPreview = false - webView.allowsBackForwardNavigationGestures = false - webView.accessibilityIgnoresInvertColors = true - webView.scrollView.contentInsetAdjustmentBehavior = .never - webView.alpha = 0.0 - - if #available(iOS 16.4, *) { - webView.isInspectable = isDebug - } - - webView.navigationDelegate = self - - handleScriptMessage = { [weak self] message in + private func createJsContext() { + let handleScriptMessage: ([String: Any]) -> Void = { [weak self] message in Queue.mainQueue().async { guard let self else { return } - guard let body = message.body as? [String: Any] else { - return - } - guard let eventName = body["event"] as? String else { + guard let eventName = message["event"] as? String else { return } switch eventName { case "windowOnLoad": - self.isWebViewReady = true + self.isJsContextReady = true self.initializePendingInstances() case "bridgeInvoke": - guard let eventData = body["data"] as? [String: Any] else { + guard let eventData = message["data"] as? [String: Any] else { return } guard let bridgeId = eventData["bridgeId"] as? Int else { @@ -478,31 +427,31 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { } let jsonResult = try! JSONSerialization.data(withJSONObject: result) let jsonResultString = String(data: jsonResult, encoding: .utf8)! - self.webView?.evaluateJavaScript("bridgeInvokeCallback(\(callbackId), \(jsonResultString));", completionHandler: nil) + self.jsContext?.evaluateJavaScript("window.bridgeInvokeCallback(\(callbackId), \(jsonResultString));") } ) case "playerStatus": - guard let instanceId = body["instanceId"] as? Int else { + guard let instanceId = message["instanceId"] as? Int else { return } guard let instance = self.contextReferences[instanceId]?.contentNode else { self.contextReferences.removeValue(forKey: instanceId) return } - guard let eventData = body["data"] as? [String: Any] else { + guard let eventData = message["data"] as? [String: Any] else { return } instance.onPlayerStatusUpdated(eventData: eventData) case "playerCurrentTime": - guard let instanceId = body["instanceId"] as? Int else { + guard let instanceId = message["instanceId"] as? Int else { return } guard let instance = self.contextReferences[instanceId]?.contentNode else { self.contextReferences.removeValue(forKey: instanceId) return } - guard let eventData = body["data"] as? [String: Any] else { + guard let eventData = message["data"] as? [String: Any] else { return } guard let value = eventData["value"] as? Double else { @@ -523,18 +472,20 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { } } - self.isWebViewReady = false + self.isJsContextReady = false - let bundle = Bundle(for: SharedHLSVideoWebView.self) - let bundlePath = bundle.bundlePath + "/HlsBundle.bundle" - webView.loadFileURL(URL(fileURLWithPath: bundlePath + "/index.html"), allowingReadAccessTo: URL(fileURLWithPath: bundlePath)) + /*#if DEBUG + self.jsContext = WebViewNativeJSContextImpl(handleScriptMessage: handleScriptMessage) + #else*/ + self.jsContext = WebViewHLSJSContextImpl(handleScriptMessage: handleScriptMessage) + //#endif } - private func disposeWebView() { - if let _ = self.webView { - self.webView = nil + private func disposeJsContext() { + if let _ = self.jsContext { + self.jsContext = nil } - self.isWebViewReady = false + self.isJsContextReady = false } private func bridgeInvoke( @@ -551,7 +502,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { return } let videoElement = VideoElement(instanceId: instanceId) - SharedHLSVideoWebView.shared.videoElements[bridgeId] = videoElement + SharedHLSVideoJSContext.shared.videoElements[bridgeId] = videoElement completion([:]) } else if (methodName == "setMediaSource") { guard let instanceId = params["instanceId"] as? Int else { @@ -562,7 +513,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { assertionFailure() return } - guard let (_, videoElement) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.instanceId == instanceId }) else { + guard let (_, videoElement) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.instanceId == instanceId }) else { return } videoElement.mediaSourceId = mediaSourceId @@ -622,14 +573,14 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { } else if (className == "MediaSource") { if (methodName == "constructor") { let mediaSource = MediaSource() - SharedHLSVideoWebView.shared.mediaSources[bridgeId] = mediaSource + SharedHLSVideoJSContext.shared.mediaSources[bridgeId] = mediaSource completion([:]) } else if (methodName == "setDuration") { guard let duration = params["duration"] as? Double else { assertionFailure() return } - guard let mediaSource = SharedHLSVideoWebView.shared.mediaSources[bridgeId] else { + guard let mediaSource = SharedHLSVideoJSContext.shared.mediaSources[bridgeId] else { assertionFailure() return } @@ -639,7 +590,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { durationUpdated = true } - guard let (_, videoElement) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.mediaSourceId == bridgeId }) else { + guard let (_, videoElement) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.mediaSourceId == bridgeId }) else { return } @@ -654,13 +605,13 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { assertionFailure() return } - guard let mediaSource = SharedHLSVideoWebView.shared.mediaSources[bridgeId] else { + guard let mediaSource = SharedHLSVideoJSContext.shared.mediaSources[bridgeId] else { assertionFailure() return } mediaSource.sourceBufferIds = ids - guard let (_, videoElement) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.mediaSourceId == bridgeId }) else { + guard let (_, videoElement) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.mediaSourceId == bridgeId }) else { return } @@ -679,7 +630,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { return } let sourceBuffer = SourceBuffer(mediaSourceId: mediaSourceId, mimeType: mimeType) - SharedHLSVideoWebView.shared.sourceBuffers[bridgeId] = sourceBuffer + SharedHLSVideoJSContext.shared.sourceBuffers[bridgeId] = sourceBuffer completion([:]) } else if (methodName == "appendBuffer") { @@ -691,7 +642,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { assertionFailure() return } - guard let sourceBuffer = SharedHLSVideoWebView.shared.sourceBuffers[bridgeId] else { + guard let sourceBuffer = SharedHLSVideoJSContext.shared.sourceBuffers[bridgeId] else { assertionFailure() return } @@ -703,7 +654,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { assertionFailure() return } - guard let sourceBuffer = SharedHLSVideoWebView.shared.sourceBuffers[bridgeId] else { + guard let sourceBuffer = SharedHLSVideoJSContext.shared.sourceBuffers[bridgeId] else { assertionFailure() return } @@ -711,7 +662,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { completion(["ranges": serializeRanges(bufferedRanges)]) }) } else if methodName == "abort" { - guard let sourceBuffer = SharedHLSVideoWebView.shared.sourceBuffers[bridgeId] else { + guard let sourceBuffer = SharedHLSVideoJSContext.shared.sourceBuffers[bridgeId] else { assertionFailure() return } @@ -766,51 +717,38 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { let filePath = String(requestPath[firstSlash.upperBound...]) if filePath == "master.m3u8" { let _ = (source.masterPlaylistData() - |> deliverOn(.mainQueue()) - |> take(1)).start(next: { [weak self] result in - guard let self else { - return - } - - self.sendResponseAndClose(id: id, data: result.data(using: .utf8)!, completion: completion) + |> take(1)).start(next: { result in + SharedHLSVideoJSContext.sendResponseAndClose(id: id, data: result.data(using: .utf8)!, completion: completion) }) } else if filePath.hasPrefix("hls_level_") && filePath.hasSuffix(".m3u8") { guard let levelIndex = Int(String(filePath[filePath.index(filePath.startIndex, offsetBy: "hls_level_".count) ..< filePath.index(filePath.endIndex, offsetBy: -".m3u8".count)])) else { - self.sendErrorAndClose(id: id, error: .notFound, completion: completion) + SharedHLSVideoJSContext.sendErrorAndClose(id: id, error: .notFound, completion: completion) return } let _ = (source.playlistData(quality: levelIndex) |> deliverOn(.mainQueue()) - |> take(1)).start(next: { [weak self] result in - guard let self else { - return - } - - self.sendResponseAndClose(id: id, data: result.data(using: .utf8)!, completion: completion) + |> take(1)).start(next: { result in + SharedHLSVideoJSContext.sendResponseAndClose(id: id, data: result.data(using: .utf8)!, completion: completion) }) } else if filePath.hasPrefix("partfile") && filePath.hasSuffix(".mp4") { let fileId = String(filePath[filePath.index(filePath.startIndex, offsetBy: "partfile".count) ..< filePath.index(filePath.endIndex, offsetBy: -".mp4".count)]) guard let fileIdValue = Int64(fileId) else { - self.sendErrorAndClose(id: id, error: .notFound, completion: completion) + SharedHLSVideoJSContext.sendErrorAndClose(id: id, error: .notFound, completion: completion) return } guard let requestRange else { - self.sendErrorAndClose(id: id, error: .badRequest, completion: completion) + SharedHLSVideoJSContext.sendErrorAndClose(id: id, error: .badRequest, completion: completion) return } let _ = (source.fileData(id: fileIdValue, range: requestRange.lowerBound ..< requestRange.upperBound + 1) |> deliverOn(.mainQueue()) //|> timeout(5.0, queue: self.queue, alternate: .single(nil)) - |> take(1)).start(next: { [weak self] result in - guard let self else { - return - } - + |> take(1)).start(next: { result in if let (tempFile, tempFileRange, totalSize) = result { - self.sendResponseFileAndClose(id: id, file: tempFile, fileRange: tempFileRange, range: requestRange, totalSize: totalSize, completion: completion) + SharedHLSVideoJSContext.sendResponseFileAndClose(id: id, file: tempFile, fileRange: tempFileRange, range: requestRange, totalSize: totalSize, completion: completion) } else { - self.sendErrorAndClose(id: id, error: .internalServerError, completion: completion) + SharedHLSVideoJSContext.sendErrorAndClose(id: id, error: .internalServerError, completion: completion) } }) } @@ -822,58 +760,6 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { if (!handlerFound) { completion(["error": 1]) } - - /*var request = URLRequest(url: URL(string: url)!) - for (key, value) in requestHeaders { - request.setValue(value, forHTTPHeaderField: key) - } - - let isCompleted = Atomic(value: false) - let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] data, response, error in - Queue.mainQueue().async { - guard let self else { - return - } - if isCompleted.swap(true) { - return - } - - self.tempTasks.removeValue(forKey: id) - - if let _ = error { - completion([ - "error": 1 - ]) - } else { - if let response = response as? HTTPURLResponse { - completion([ - "status": response.statusCode, - "statusText": "OK", - "responseData": data?.base64EncodedString() ?? "", - "responseHeaders": response.allHeaderFields as? [String: String] ?? [:] - ]) - - let _ = response - /*if let response = response as? HTTPURLResponse, let requestUrl { - if let updatedResponse = HTTPURLResponse( - url: requestUrl, - statusCode: response.statusCode, - httpVersion: "HTTP/1.1", - headerFields: response.allHeaderFields as? [String: String] ?? [:] - ) { - sourceTask.didReceive(updatedResponse) - } else { - sourceTask.didReceive(response) - } - } else { - sourceTask.didReceive(response) - }*/ - } - } - } - }) - self.tempTasks[id] = task - task.resume()*/ } else if methodName == "abort" { guard let id = params["id"] as? Int else { assertionFailure() @@ -889,7 +775,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { } } - private func sendErrorAndClose(id: Int, error: ResponseError, completion: @escaping ([String: Any]) -> Void) { + private static func sendErrorAndClose(id: Int, error: ResponseError, completion: @escaping ([String: Any]) -> Void) { let (code, status) = error.httpStatus completion([ "status": code, @@ -901,7 +787,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { ]) } - private func sendResponseAndClose(id: Int, data: Data, contentType: String = "application/octet-stream", completion: @escaping ([String: Any]) -> Void) { + private static func sendResponseAndClose(id: Int, data: Data, contentType: String = "application/octet-stream", completion: @escaping ([String: Any]) -> Void) { completion([ "status": 200, "statusText": "OK", @@ -913,20 +799,22 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { ]) } - private func sendResponseFileAndClose(id: Int, file: TempBoxFile, fileRange: Range, range: Range, totalSize: Int, completion: @escaping ([String: Any]) -> Void) { - if let data = try? Data(contentsOf: URL(fileURLWithPath: file.path), options: .mappedIfSafe).subdata(in: fileRange) { - completion([ - "status": 200, - "statusText": "OK", - "responseData": data.base64EncodedString(), - "responseHeaders": [ - "Content-Type": "application/octet-stream", - "Content-Range": "bytes \(range.lowerBound)-\(range.upperBound)/\(totalSize)", - "Content-Length": "\(fileRange.upperBound - fileRange.lowerBound)" - ] as [String: String] - ]) - } else { - self.sendErrorAndClose(id: id, error: .internalServerError, completion: completion) + private static func sendResponseFileAndClose(id: Int, file: TempBoxFile, fileRange: Range, range: Range, totalSize: Int, completion: @escaping ([String: Any]) -> Void) { + Queue.concurrentDefaultQueue().async { + if let data = try? Data(contentsOf: URL(fileURLWithPath: file.path), options: .mappedIfSafe).subdata(in: fileRange) { + completion([ + "status": 200, + "statusText": "OK", + "responseData": data.base64EncodedString(), + "responseHeaders": [ + "Content-Type": "application/octet-stream", + "Content-Range": "bytes \(range.lowerBound)-\(range.upperBound)/\(totalSize)", + "Content-Length": "\(fileRange.upperBound - fileRange.lowerBound)" + ] as [String: String] + ]) + } else { + SharedHLSVideoJSContext.sendErrorAndClose(id: id, error: .internalServerError, completion: completion) + } } } @@ -934,8 +822,8 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { let contextInstanceId = context.instanceId self.contextReferences[contextInstanceId] = ContextReference(contentNode: context) - if self.webView == nil { - self.createWebView() + if self.jsContext == nil { + self.createJsContext() } if let emptyTimer = self.emptyTimer { @@ -960,7 +848,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { } } - self.webView?.evaluateJavaScript("window.hlsPlayer_destroyInstance(\(contextInstanceId));") + self.jsContext?.evaluateJavaScript("window.hlsPlayer_destroyInstance(\(contextInstanceId));") if self.contextReferences.isEmpty { if self.emptyTimer == nil { @@ -972,7 +860,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { self.emptyTimer = nil } if self.contextReferences.isEmpty { - self.disposeWebView() + self.disposeJsContext() } }) } @@ -984,7 +872,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { func initializeWhenReady(context: HLSVideoJSNativeContentNode, urlPrefix: String) { self.pendingInitializeInstanceIds.append((context.instanceId, urlPrefix)) - if self.isWebViewReady { + if self.isJsContextReady { self.initializePendingInstances() } } @@ -1020,7 +908,7 @@ private final class SharedHLSVideoWebView: NSObject, WKNavigationDelegate { """) } - self.webView?.evaluateJavaScript(userScriptJs) + self.jsContext?.evaluateJavaScript(userScriptJs) } } @@ -1056,6 +944,8 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod private let fileReference: FileMediaReference private let approximateDuration: Double private let intrinsicDimensions: CGSize + + private var enableSound: Bool private let audioSessionManager: ManagedAudioSession private let audioSessionDisposable = MetaDisposable() @@ -1150,6 +1040,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod self.audioSessionManager = audioSessionManager self.userLocation = userLocation self.requestedBaseRate = baseRate + self.enableSound = enableSound if var dimensions = fileReference.media.dimensions { if let thumbnail = fileReference.media.previewRepresentations.first { @@ -1186,7 +1077,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod audioSessionManager: audioSessionManager, partsState: self.chunkPlayerPartsState.get(), video: true, - enableSound: true, + enableSound: self.enableSound, baseRate: baseRate, onSeeked: { onSeeked?() @@ -1198,7 +1089,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod super.init() - self.contextDisposable = SharedHLSVideoWebView.shared.register(context: self) + self.contextDisposable = SharedHLSVideoJSContext.shared.register(context: self) self.playerNode.frame = CGRect(origin: CGPoint(), size: self.intrinsicDimensions) @@ -1255,12 +1146,12 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod guard let self else { return } - SharedHLSVideoWebView.shared.webView?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerNotifySeekedOnNextStatusUpdate();", completionHandler: nil) + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerNotifySeekedOnNextStatusUpdate();") } } if let playerSource { - SharedHLSVideoWebView.shared.initializeWhenReady(context: self, urlPrefix: "http://server/\(playerSource.id)/") + SharedHLSVideoJSContext.shared.initializeWhenReady(context: self, urlPrefix: "http://server/\(playerSource.id)/") } } @@ -1380,13 +1271,21 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod selectedLevelIndex = self.playerAvailableLevels.sorted(by: { $0.value.height > $1.value.height }).first?.key } if let selectedLevelIndex { + var effectiveSelectedLevelIndex = selectedLevelIndex + if !self.enableSound { + effectiveSelectedLevelIndex = self.resolveCurrentLevelIndex() ?? -1 + } + self.hasRequestedPlayerLoad = true - SharedHLSVideoWebView.shared.webView?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerLoad(\(selectedLevelIndex));", completionHandler: nil) + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript(""" + window.hlsPlayer_instances[\(self.instanceId)].playerSetCapAutoLevel(\(self.resolveCurrentLevelIndex() ?? -1)); + window.hlsPlayer_instances[\(self.instanceId)].playerLoad(\(effectiveSelectedLevelIndex)); + """) } } } - SharedHLSVideoWebView.shared.webView?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerSetBaseRate(\(self.requestedBaseRate));", completionHandler: nil) + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerSetBaseRate(\(self.requestedBaseRate));") } self.updateStatus() @@ -1415,13 +1314,13 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod } fileprivate func onMediaSourceDurationUpdated() { - guard let (_, videoElement) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) else { + guard let (_, videoElement) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) else { return } - guard let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoWebView.shared.mediaSources[mediaSourceId] else { + guard let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoJSContext.shared.mediaSources[mediaSourceId] else { return } - guard let sourceBufferId = mediaSource.sourceBufferIds.first, let sourceBuffer = SharedHLSVideoWebView.shared.sourceBuffers[sourceBufferId] else { + guard let sourceBufferId = mediaSource.sourceBufferIds.first, let sourceBuffer = SharedHLSVideoJSContext.shared.sourceBuffers[sourceBufferId] else { return } @@ -1429,13 +1328,13 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod } fileprivate func onMediaSourceBuffersUpdated() { - guard let (_, videoElement) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) else { + guard let (_, videoElement) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) else { return } - guard let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoWebView.shared.mediaSources[mediaSourceId] else { + guard let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoJSContext.shared.mediaSources[mediaSourceId] else { return } - guard let sourceBufferId = mediaSource.sourceBufferIds.first, let sourceBuffer = SharedHLSVideoWebView.shared.sourceBuffers[sourceBufferId] else { + guard let sourceBufferId = mediaSource.sourceBufferIds.first, let sourceBuffer = SharedHLSVideoJSContext.shared.sourceBuffers[sourceBufferId] else { return } @@ -1446,7 +1345,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod guard let self, let sourceBuffer else { return } - guard let mediaSource = SharedHLSVideoWebView.shared.mediaSources[sourceBuffer.mediaSourceId] else { + guard let mediaSource = SharedHLSVideoJSContext.shared.mediaSources[sourceBuffer.mediaSourceId] else { return } self.chunkPlayerPartsState.set(.single(ChunkMediaPlayerPartsState(duration: mediaSource.duration, parts: sourceBuffer.items))) @@ -1459,7 +1358,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod private func updatePlayerStatus(status: MediaPlayerStatus) { self._status.set(status) - if let (bridgeId, _) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) { + if let (bridgeId, _) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) { var isPlaying: Bool = false var isBuffering = false switch status.status { @@ -1480,25 +1379,25 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod let jsonResult = try! JSONSerialization.data(withJSONObject: result) let jsonResultString = String(data: jsonResult, encoding: .utf8)! - SharedHLSVideoWebView.shared.webView?.evaluateJavaScript("window.bridgeObjectMap[\(bridgeId)].bridgeUpdateStatus(\(jsonResultString));", completionHandler: nil) + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript("window.bridgeObjectMap[\(bridgeId)].bridgeUpdateStatus(\(jsonResultString));") } } private func updateBuffered() { - guard let (_, videoElement) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) else { + guard let (_, videoElement) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) else { return } - guard let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoWebView.shared.mediaSources[mediaSourceId] else { + guard let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoJSContext.shared.mediaSources[mediaSourceId] else { return } - guard let sourceBufferId = mediaSource.sourceBufferIds.first, let sourceBuffer = SharedHLSVideoWebView.shared.sourceBuffers[sourceBufferId] else { + guard let sourceBufferId = mediaSource.sourceBufferIds.first, let sourceBuffer = SharedHLSVideoJSContext.shared.sourceBuffers[sourceBufferId] else { return } let bufferedRanges = sourceBuffer.ranges - if let (_, videoElement) = SharedHLSVideoWebView.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) { - if let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoWebView.shared.mediaSources[mediaSourceId] { + if let (_, videoElement) = SharedHLSVideoJSContext.shared.videoElements.first(where: { $0.value.instanceId == self.instanceId }) { + if let mediaSourceId = videoElement.mediaSourceId, let mediaSource = SharedHLSVideoJSContext.shared.mediaSources[mediaSourceId] { if let duration = mediaSource.duration { var mappedRanges = RangeSet() for range in bufferedRanges.ranges { @@ -1538,7 +1437,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod func play() { assert(Queue.mainQueue().isCurrent()) if !self.initializedStatus { - self._status.set(MediaPlayerStatus(generationTimestamp: 0.0, duration: Double(self.approximateDuration), dimensions: CGSize(), timestamp: 0.0, baseRate: self.requestedBaseRate, seekId: self.seekId, status: .buffering(initial: true, whilePlaying: true, progress: 0.0, display: true), soundEnabled: true)) + self._status.set(MediaPlayerStatus(generationTimestamp: 0.0, duration: Double(self.approximateDuration), dimensions: CGSize(), timestamp: 0.0, baseRate: self.requestedBaseRate, seekId: self.seekId, status: .buffering(initial: true, whilePlaying: true, progress: 0.0, display: true), soundEnabled: self.enableSound)) } self.player.play() } @@ -1555,10 +1454,14 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod func setSoundEnabled(_ value: Bool) { assert(Queue.mainQueue().isCurrent()) - if value { - self.player.playOnceWithSound(playAndRecord: false, seek: .none) - } else { - self.player.continuePlayingWithoutSound(seek: .none) + if self.enableSound != value { + self.enableSound = value + if value { + self.player.playOnceWithSound(playAndRecord: false, seek: .none) + } else { + self.player.continuePlayingWithoutSound(seek: .none) + } + self.updateInternalQualityLevel() } } @@ -1566,7 +1469,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod assert(Queue.mainQueue().isCurrent()) self.seekId += 1 - SharedHLSVideoWebView.shared.webView?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerSeek(\(timestamp));", completionHandler: nil) + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerSeek(\(timestamp));") } func playOnceWithSound(playAndRecord: Bool, seek: MediaPlayerSeek, actionAtEnd: MediaPlayerPlayOnceWithSoundActionAtEnd) { @@ -1576,6 +1479,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod self?.performActionAtEnd() } } + self.enableSound = true switch actionAtEnd { case .loop: self.player.actionAtEnd = .loop({}) @@ -1604,6 +1508,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod } self.player.playOnceWithSound(playAndRecord: playAndRecord, seek: seek) + self.updateInternalQualityLevel() } func setSoundMuted(soundMuted: Bool) { @@ -1626,6 +1531,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod self?.performActionAtEnd() } } + self.enableSound = false switch actionAtEnd { case .loop: self.player.actionAtEnd = .loop({}) @@ -1635,6 +1541,7 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod self.player.actionAtEnd = .action(action) } self.player.continuePlayingWithoutSound(seek: .none) + self.updateInternalQualityLevel() } func setContinuePlayingWithoutSoundOnLostAudioSession(_ value: Bool) { @@ -1644,15 +1551,41 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod func setBaseRate(_ baseRate: Double) { self.requestedBaseRate = baseRate if self.playerIsReady { - SharedHLSVideoWebView.shared.webView?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerSetBaseRate(\(self.requestedBaseRate));", completionHandler: nil) + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerSetBaseRate(\(self.requestedBaseRate));") } self.updateStatus() } + private func resolveCurrentLevelIndex() -> Int? { + if self.enableSound { + return self.requestedLevelIndex + } else { + var foundIndex: Int? + if let minQualityFile = HLSVideoContent.minimizedHLSQuality(file: self.fileReference)?.file, let dimensions = minQualityFile.media.dimensions { + for (index, level) in self.playerAvailableLevels { + if level.width == Int(dimensions.width) && level.height == Int(dimensions.height) { + foundIndex = index + break + } + } + } + return foundIndex + } + } + + private func updateInternalQualityLevel() { + if self.playerIsReady { + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript(""" + window.hlsPlayer_instances[\(self.instanceId)].playerSetCapAutoLevel(\(self.resolveCurrentLevelIndex() ?? -1)); + """) + } + } + func setVideoQuality(_ videoQuality: UniversalVideoContentVideoQuality) { self.preferredVideoQuality = videoQuality - switch videoQuality { + let resolvedVideoQuality = self.preferredVideoQuality + switch resolvedVideoQuality { case .auto: self.requestedLevelIndex = nil case let .quality(quality): @@ -1666,7 +1599,9 @@ final class HLSVideoJSNativeContentNode: ASDisplayNode, UniversalVideoContentNod self.updateVideoQualityState() if self.playerIsReady { - SharedHLSVideoWebView.shared.webView?.evaluateJavaScript("window.hlsPlayer_instances[\(self.instanceId)].playerSetLevel(\(self.requestedLevelIndex ?? -1));", completionHandler: nil) + SharedHLSVideoJSContext.shared.jsContext?.evaluateJavaScript(""" + window.hlsPlayer_instances[\(self.instanceId)].playerSetLevel(\(self.requestedLevelIndex ?? -1)); + """) } } diff --git a/submodules/TelegramUniversalVideoContent/Sources/WebViewHLSJSContextImpl.swift b/submodules/TelegramUniversalVideoContent/Sources/WebViewHLSJSContextImpl.swift new file mode 100644 index 0000000000..1b15c503ea --- /dev/null +++ b/submodules/TelegramUniversalVideoContent/Sources/WebViewHLSJSContextImpl.swift @@ -0,0 +1,76 @@ +import Foundation +import UIKit +@preconcurrency import WebKit +import SwiftSignalKit + +private class WeakScriptMessageHandler: NSObject, WKScriptMessageHandler { + private let f: (WKScriptMessage) -> () + + init(_ f: @escaping (WKScriptMessage) -> ()) { + self.f = f + + super.init() + } + + func userContentController(_ controller: WKUserContentController, didReceive scriptMessage: WKScriptMessage) { + self.f(scriptMessage) + } +} + +final class WebViewHLSJSContextImpl: HLSJSContext { + let webView: WKWebView + + init(handleScriptMessage: @escaping ([String: Any]) -> Void) { + let config = WKWebViewConfiguration() + config.allowsInlineMediaPlayback = true + config.mediaTypesRequiringUserActionForPlayback = [] + config.allowsPictureInPictureMediaPlayback = true + + let userController = WKUserContentController() + + var handleScriptMessageImpl: (([String: Any]) -> Void)? + userController.add(WeakScriptMessageHandler { message in + guard let body = message.body as? [String: Any] else { + return + } + handleScriptMessageImpl?(body) + }, name: "performAction") + + let isDebug: Bool + #if DEBUG + isDebug = true + #else + isDebug = false + #endif + + config.userContentController = userController + + let webView = WKWebView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 100.0, height: 100.0)), configuration: config) + self.webView = webView + + webView.scrollView.isScrollEnabled = false + webView.allowsLinkPreview = false + webView.allowsBackForwardNavigationGestures = false + webView.accessibilityIgnoresInvertColors = true + webView.scrollView.contentInsetAdjustmentBehavior = .never + webView.alpha = 0.0 + + if #available(iOS 16.4, *) { + webView.isInspectable = isDebug + } + + handleScriptMessageImpl = { message in + Queue.mainQueue().async { + handleScriptMessage(message) + } + } + + let bundle = Bundle(for: WebViewHLSJSContextImpl.self) + let bundlePath = bundle.bundlePath + "/HlsBundle.bundle" + webView.loadFileURL(URL(fileURLWithPath: bundlePath + "/index.html"), allowingReadAccessTo: URL(fileURLWithPath: bundlePath)) + } + + func evaluateJavaScript(_ string: String) { + self.webView.evaluateJavaScript(string, completionHandler: nil) + } +} diff --git a/submodules/TelegramUniversalVideoContent/Sources/WebViewNativeJSContextImpl.swift b/submodules/TelegramUniversalVideoContent/Sources/WebViewNativeJSContextImpl.swift new file mode 100644 index 0000000000..bc1ee29454 --- /dev/null +++ b/submodules/TelegramUniversalVideoContent/Sources/WebViewNativeJSContextImpl.swift @@ -0,0 +1,248 @@ +import Foundation +import UIKit +import JavaScriptCore +import TelegramCore +import SwiftSignalKit + +private var ObjCKey_ContextReference: Int? + +@objc private protocol JsCorePolyfillsExport: JSExport { + func postMessage(_ object: JSValue) + func consoleLog(_ object: JSValue) + func consoleLog(_ object: JSValue, _ arg1: JSValue) + func consoleLog(_ object: JSValue, _ arg1: JSValue, _ arg2: JSValue) + func performanceNow() -> Double +} + +@objc private final class JsCorePolyfills: NSObject, JsCorePolyfillsExport { + private let queue: Queue + private let context: WebViewNativeJSContextImpl.Reference + + init(queue: Queue, context: WebViewNativeJSContextImpl.Reference) { + self.queue = queue + self.context = context + + super.init() + } + + @objc func postMessage(_ object: JSValue) { + guard object.isObject else { + return + } + guard let message = object.toDictionary() as? [String: Any] else { + return + } + let context = self.context + self.queue.async { + guard let context = context.context else { + return + } + let handleScriptMessage = context.handleScriptMessage + + Queue.mainQueue().async { + handleScriptMessage(message) + } + } + } + + @objc func consoleLog(_ object: JSValue) { + #if DEBUG + print("\(object)") + #endif + } + + @objc func consoleLog(_ object: JSValue, _ arg1: JSValue) { + #if DEBUG + print("\(object) \(arg1)") + #endif + } + + @objc func consoleLog(_ object: JSValue, _ arg1: JSValue, _ arg2: JSValue) { + #if DEBUG + print("\(object) \(arg1) \(arg2)") + #endif + } + + @objc func performanceNow() -> Double { + return CFAbsoluteTimeGetCurrent() + } +} + +@objc private protocol TimerJSExport: JSExport { + func setTimeout(_ callback: JSValue, _ ms: Double) -> Int32 + func setInterval(_ callback: JSValue, _ ms: Double) -> Int32 + + func clearTimeout(_ id: Int32) +} + +@objc private class TimeoutPolyfill: NSObject, TimerJSExport { + private let queue: Queue + + private var timers: [Int32: SwiftSignalKit.Timer] = [:] + private var nextId: Int32 = 0 + + init(queue: Queue) { + self.queue = queue + } + + deinit { + for (_, timer) in self.timers { + timer.invalidate() + } + } + + func register(jsContext: JSContext) { + jsContext.evaluateScript(""" + function setTimeout(...args) { + if (args.length === 0) { + return -1; + } + + const [callback, delay = 0, ...callbackArgs] = args; + + return _timeoutPolyfill.setTimeout(() => { + callback(...callbackArgs); + }, delay); + } + + function setInterval(...args) { + if (args.length === 0) { + return -1; + } + + const [callback, delay = 0, ...callbackArgs] = args; + + return _timeoutPolyfill.setInterval(() => { + callback(...callbackArgs); + }, delay); + } + + function clearTimeout(indentifier) { + _timeoutPolyfill.clearTimeout(indentifier) + } + + function clearInterval(indentifier) { + _timeoutPolyfill.clearTimeout(indentifier) + } + """ + ) + } + + func clearTimeout(_ id: Int32) { + let timer = self.timers.removeValue(forKey: id) + timer?.invalidate() + } + + func setTimeout(_ callback: JSValue, _ ms: Double) -> Int32 { + return self.createTimer(callback: callback, ms: ms, repeats: false) + } + + func setInterval(_ callback: JSValue, _ ms: Double) -> Int32 { + return self.createTimer(callback: callback, ms: ms, repeats: true) + } + + func createTimer(callback: JSValue, ms: Double, repeats: Bool) -> Int32 { + let timeInterval = ms / 1000.0 + + let id = self.nextId + self.nextId += 1 + let timer = SwiftSignalKit.Timer(timeout: timeInterval, repeat: repeats, completion: { [weak self] in + guard let self else { + return + } + callback.call(withArguments: nil) + + if !repeats { + self.timers.removeValue(forKey: id) + } + }, queue: self.queue) + self.timers[id] = timer + timer.start() + + return id + } +} + +final class WebViewNativeJSContextImpl: HLSJSContext { + fileprivate final class Reference { + weak var context: WebViewNativeJSContextImpl.Impl? + + init(context: WebViewNativeJSContextImpl.Impl) { + self.context = context + } + } + + fileprivate final class Impl { + let queue: Queue + let context: JSContext + let handleScriptMessage: ([String: Any]) -> Void + + init(queue: Queue, handleScriptMessage: @escaping ([String: Any]) -> Void) { + self.queue = queue + self.context = JSContext() + self.handleScriptMessage = handleScriptMessage + + #if DEBUG + if #available(iOS 16.4, *) { + self.context.isInspectable = true + } + #endif + + self.context.exceptionHandler = { context, exception in + if let exception { + Logger.shared.log("WebViewNativeJSContextImpl", "JS exception: \(exception)") + #if DEBUG + print("JS exception: \(exception)") + #endif + } + } + + let timeoutPolyfill = TimeoutPolyfill(queue: self.queue) + self.context.setObject(timeoutPolyfill, forKeyedSubscript: "_timeoutPolyfill" as (NSCopying & NSObjectProtocol)) + timeoutPolyfill.register(jsContext: self.context) + + self.context.setObject(JsCorePolyfills(queue: self.queue, context: Reference(context: self)), forKeyedSubscript: "_JsCorePolyfills" as (NSCopying & NSObjectProtocol)) + + let bundle = Bundle(for: WebViewHLSJSContextImpl.self) + let bundlePath = bundle.bundlePath + "/HlsBundle.bundle" + if let indexJsString = try? String(contentsOf: URL(fileURLWithPath: bundlePath + "/headless_prologue.js"), encoding: .utf8) { + self.context.evaluateScript(indexJsString, withSourceURL: URL(fileURLWithPath: "index/index.bundle.js")) + } else { + assertionFailure() + } + + if let indexJsString = try? String(contentsOf: URL(fileURLWithPath: bundlePath + "/index.bundle.js"), encoding: .utf8) { + self.context.evaluateScript(indexJsString, withSourceURL: URL(fileURLWithPath: "index.bundle.js")) + } else { + assertionFailure() + } + } + + deinit { + print("WebViewNativeJSContextImpl.deinit") + } + + func evaluateJavaScript(_ string: String) { + self.context.evaluateScript(string) + } + } + + static let sharedQueue = Queue(name: "WebViewNativeJSContextImpl", qos: .default) + + private let queue: Queue + private let impl: QueueLocalObject + + init(handleScriptMessage: @escaping ([String: Any]) -> Void) { + let queue = WebViewNativeJSContextImpl.sharedQueue + self.queue = queue + self.impl = QueueLocalObject(queue: queue, generate: { + return Impl(queue: queue, handleScriptMessage: handleScriptMessage) + }) + } + + func evaluateJavaScript(_ string: String) { + self.impl.with { impl in + impl.evaluateJavaScript(string) + } + } +} diff --git a/submodules/WebSearchUI/Sources/WebSearchGalleryController.swift b/submodules/WebSearchUI/Sources/WebSearchGalleryController.swift index b9e7363af9..28452c546a 100644 --- a/submodules/WebSearchUI/Sources/WebSearchGalleryController.swift +++ b/submodules/WebSearchUI/Sources/WebSearchGalleryController.swift @@ -230,7 +230,7 @@ class WebSearchGalleryController: ViewController { }, controller: { [weak self] in return self }) - self.displayNode = GalleryControllerNode(controllerInteraction: controllerInteraction) + self.displayNode = GalleryControllerNode(context: self.context, controllerInteraction: controllerInteraction) self.displayNodeDidLoad() self.galleryNode.statusBar = self.statusBar