@cloudflare/realtimekit-ui 1.0.0-staging.8 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/cjs/{TextMessage-e9ca06aa.js → TextMessage-87c1e5a0.js} +1 -1
- package/dist/cjs/{chat-46e7e4fe.js → chat-6d305b71.js} +1 -1
- package/dist/cjs/{config-dba24e25.js → config-9632c81a.js} +4 -4
- package/dist/cjs/{index-daae8cee.js → index-49c92728.js} +1 -1
- package/dist/cjs/index.cjs.js +4 -5
- package/dist/cjs/loader.cjs.js +1 -1
- package/dist/cjs/{notification-1948ed2f.js → notification-6d70e3a8.js} +3 -8
- package/dist/cjs/realtimekit-ui.cjs.js +1 -1
- package/dist/cjs/rtk-ai-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-ai-transcriptions.cjs.entry.js +2 -2
- package/dist/cjs/rtk-ai.cjs.entry.js +2 -2
- package/dist/cjs/rtk-audio-grid.cjs.entry.js +2 -2
- package/dist/cjs/rtk-audio-tile.cjs.entry.js +2 -2
- package/dist/cjs/rtk-audio-visualizer_4.cjs.entry.js +3 -3
- package/dist/cjs/rtk-avatar_54.cjs.entry.js +53 -29
- package/dist/cjs/rtk-breakout-rooms-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-camera-selector_2.cjs.entry.js +4 -4
- package/dist/cjs/rtk-camera-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-caption-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-channel-selector-ui.cjs.entry.js +4 -4
- package/dist/cjs/rtk-chat-composer-ui.cjs.entry.js +3 -3
- package/dist/cjs/rtk-chat-selector-ui.cjs.entry.js +3 -3
- package/dist/cjs/rtk-chat-toggle.cjs.entry.js +3 -3
- package/dist/cjs/rtk-clock.cjs.entry.js +2 -2
- package/dist/cjs/rtk-controlbar-button.cjs.entry.js +3 -3
- package/dist/cjs/rtk-controlbar.cjs.entry.js +2 -2
- package/dist/cjs/rtk-debugger-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-ended-screen.cjs.entry.js +2 -2
- package/dist/cjs/rtk-file-dropzone.cjs.entry.js +2 -2
- package/dist/cjs/rtk-fullscreen-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-grid-pagination.cjs.entry.js +2 -2
- package/dist/cjs/rtk-grid.cjs.entry.js +2 -2
- package/dist/cjs/rtk-header.cjs.entry.js +2 -2
- package/dist/cjs/rtk-idle-screen.cjs.entry.js +2 -2
- package/dist/cjs/rtk-image-viewer.cjs.entry.js +2 -2
- package/dist/cjs/rtk-information-tooltip.cjs.entry.js +2 -2
- package/dist/cjs/rtk-leave-button.cjs.entry.js +2 -2
- package/dist/cjs/rtk-livestream-indicator_3.cjs.entry.js +2 -2
- package/dist/cjs/rtk-livestream-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-meeting-title.cjs.entry.js +2 -2
- package/dist/cjs/rtk-message-list-view.cjs.entry.js +2 -2
- package/dist/cjs/rtk-mic-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-mixed-grid.cjs.entry.js +2 -2
- package/dist/cjs/rtk-more-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-mute-all-button.cjs.entry.js +2 -2
- package/dist/cjs/rtk-name-tag.cjs.entry.js +2 -2
- package/dist/cjs/rtk-network-indicator.cjs.entry.js +2 -2
- package/dist/cjs/rtk-participant-count.cjs.entry.js +2 -2
- package/dist/cjs/rtk-participant-setup.cjs.entry.js +4 -4
- package/dist/cjs/rtk-participant_2.cjs.entry.js +4 -4
- package/dist/cjs/rtk-participants-audio.cjs.entry.js +6 -6
- package/dist/cjs/rtk-participants-stage-list_4.cjs.entry.js +6 -7
- package/dist/cjs/rtk-participants-toggle.cjs.entry.js +3 -3
- package/dist/cjs/rtk-participants.cjs.entry.js +2 -2
- package/dist/cjs/rtk-pip-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-plugin-main_2.cjs.entry.js +2 -2
- package/dist/cjs/rtk-plugins-toggle.cjs.entry.js +3 -3
- package/dist/cjs/rtk-plugins_2.cjs.entry.js +6 -6
- package/dist/cjs/rtk-poll_2.cjs.entry.js +5 -5
- package/dist/cjs/rtk-polls-toggle.cjs.entry.js +3 -3
- package/dist/cjs/rtk-recording-indicator.cjs.entry.js +3 -3
- package/dist/cjs/rtk-recording-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-screen-share-toggle.cjs.entry.js +3 -4
- package/dist/cjs/rtk-screenshare-view.cjs.entry.js +7 -7
- package/dist/cjs/rtk-settings-audio_2.cjs.entry.js +2 -2
- package/dist/cjs/rtk-settings-toggle.cjs.entry.js +3 -3
- package/dist/cjs/rtk-settings.cjs.entry.js +2 -2
- package/dist/cjs/rtk-setup-screen.cjs.entry.js +7 -6
- package/dist/cjs/rtk-sidebar-ui.cjs.entry.js +2 -2
- package/dist/cjs/rtk-sidebar.cjs.entry.js +3 -3
- package/dist/cjs/rtk-simple-grid.cjs.entry.js +3 -3
- package/dist/cjs/rtk-spotlight-grid.cjs.entry.js +4 -4
- package/dist/cjs/rtk-spotlight-indicator.cjs.entry.js +2 -2
- package/dist/cjs/rtk-stage-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-stage.cjs.entry.js +3 -3
- package/dist/cjs/rtk-transcript.cjs.entry.js +3 -3
- package/dist/cjs/rtk-transcripts.cjs.entry.js +2 -2
- package/dist/cjs/rtk-ui-provider.cjs.entry.js +8 -8
- package/dist/cjs/rtk-waiting-screen.cjs.entry.js +3 -3
- package/dist/cjs/{sidebar-a3c87828.js → sidebar-8256d60e.js} +1 -1
- package/dist/cjs/{ui-store-3ddce955.js → ui-store-7807fa2a.js} +4 -5
- package/dist/collection/components/rtk-ai/rtk-ai.js +1 -1
- package/dist/collection/components/rtk-ai-toggle/rtk-ai-toggle.js +1 -1
- package/dist/collection/components/rtk-ai-transcriptions/rtk-ai-transcriptions.js +1 -1
- package/dist/collection/components/rtk-audio-grid/rtk-audio-grid.js +1 -1
- package/dist/collection/components/rtk-audio-tile/rtk-audio-tile.js +1 -1
- package/dist/collection/components/rtk-audio-visualizer/rtk-audio-visualizer.js +1 -1
- package/dist/collection/components/rtk-avatar/rtk-avatar.js +1 -1
- package/dist/collection/components/rtk-breakout-room-manager/rtk-breakout-room-manager.js +1 -1
- package/dist/collection/components/rtk-breakout-room-participants/rtk-breakout-room-participants.js +1 -1
- package/dist/collection/components/rtk-breakout-room-toggle/rtk-breakout-rooms-toggle.js +2 -2
- package/dist/collection/components/rtk-breakout-rooms-manager/rtk-breakout-rooms-manager.js +2 -2
- package/dist/collection/components/rtk-broadcast-message-modal/rtk-broadcast-message-modal.js +1 -1
- package/dist/collection/components/rtk-camera-selector/rtk-camera-selector.js +1 -1
- package/dist/collection/components/rtk-camera-toggle/rtk-camera-toggle.js +1 -1
- package/dist/collection/components/rtk-caption-toggle/rtk-caption-toggle.js +1 -1
- package/dist/collection/components/rtk-channel-creator/rtk-channel-creator.js +1 -1
- package/dist/collection/components/rtk-channel-details/rtk-channel-details.js +1 -1
- package/dist/collection/components/rtk-channel-header/rtk-channel-header.js +1 -1
- package/dist/collection/components/rtk-channel-selector-ui/rtk-channel-selector-ui.js +1 -1
- package/dist/collection/components/rtk-channel-selector-view/rtk-channel-selector-view.js +1 -1
- package/dist/collection/components/rtk-chat/rtk-chat.js +1 -1
- package/dist/collection/components/rtk-chat-composer-ui/rtk-chat-composer-ui.js +1 -1
- package/dist/collection/components/rtk-chat-composer-view/rtk-chat-composer-view.js +1 -1
- package/dist/collection/components/rtk-chat-message/rtk-chat-message.js +1 -1
- package/dist/collection/components/rtk-chat-messages-ui/rtk-chat-messages-ui.js +1 -1
- package/dist/collection/components/rtk-chat-messages-ui-paginated/rtk-chat-messages-ui-paginated.js +1 -1
- package/dist/collection/components/rtk-chat-search-results/rtk-chat-search-results.js +1 -1
- package/dist/collection/components/rtk-chat-selector-ui/rtk-chat-selector-ui.js +1 -1
- package/dist/collection/components/rtk-chat-toggle/rtk-chat-toggle.js +1 -1
- package/dist/collection/components/rtk-confirmation-modal/rtk-confirmation-modal.css +1 -5
- package/dist/collection/components/rtk-confirmation-modal/rtk-confirmation-modal.js +2 -2
- package/dist/collection/components/rtk-controlbar/rtk-controlbar.js +1 -1
- package/dist/collection/components/rtk-controlbar-button/rtk-controlbar-button.css +1 -0
- package/dist/collection/components/rtk-counter/rtk-counter.js +1 -1
- package/dist/collection/components/rtk-debugger/rtk-debugger.js +1 -1
- package/dist/collection/components/rtk-debugger-audio/rtk-debugger-audio.js +1 -1
- package/dist/collection/components/rtk-debugger-screenshare/rtk-debugger-screenshare.js +1 -1
- package/dist/collection/components/rtk-debugger-system/rtk-debugger-system.js +1 -1
- package/dist/collection/components/rtk-debugger-toggle/rtk-debugger-toggle.js +1 -1
- package/dist/collection/components/rtk-debugger-video/rtk-debugger-video.js +1 -1
- package/dist/collection/components/rtk-dialog/rtk-dialog.css +12 -41
- package/dist/collection/components/rtk-dialog/rtk-dialog.js +17 -2
- package/dist/collection/components/rtk-dialog-manager/rtk-dialog-manager.js +1 -1
- package/dist/collection/components/rtk-draft-attachment-view/rtk-draft-attachment-view.js +1 -1
- package/dist/collection/components/rtk-emoji-picker/rtk-emoji-picker.js +1 -1
- package/dist/collection/components/rtk-emoji-picker-button/rtk-emoji-picker-button.js +1 -1
- package/dist/collection/components/rtk-ended-screen/rtk-ended-screen.js +1 -1
- package/dist/collection/components/rtk-file-dropzone/rtk-file-dropzone.js +1 -1
- package/dist/collection/components/rtk-file-message/rtk-file-message.js +1 -1
- package/dist/collection/components/rtk-file-picker-button/rtk-file-picker-button.js +1 -1
- package/dist/collection/components/rtk-fullscreen-toggle/rtk-fullscreen-toggle.js +1 -1
- package/dist/collection/components/rtk-grid/rtk-grid.js +1 -1
- package/dist/collection/components/rtk-grid-pagination/rtk-grid-pagination.js +1 -1
- package/dist/collection/components/rtk-header/rtk-header.js +1 -1
- package/dist/collection/components/rtk-idle-screen/rtk-idle-screen.js +1 -1
- package/dist/collection/components/rtk-image-message/rtk-image-message.js +1 -1
- package/dist/collection/components/rtk-image-message-view/rtk-image-message-view.js +1 -1
- package/dist/collection/components/rtk-image-viewer/rtk-image-viewer.js +1 -1
- package/dist/collection/components/rtk-join-stage/rtk-join-stage.js +1 -1
- package/dist/collection/components/rtk-leave-button/rtk-leave-button.js +1 -1
- package/dist/collection/components/rtk-leave-meeting/rtk-leave-meeting.js +1 -1
- package/dist/collection/components/rtk-livestream-indicator/rtk-livestream-indicator.js +1 -1
- package/dist/collection/components/rtk-livestream-player/rtk-livestream-player.js +1 -1
- package/dist/collection/components/rtk-livestream-toggle/rtk-livestream-toggle.js +1 -1
- package/dist/collection/components/rtk-logo/rtk-logo.js +1 -1
- package/dist/collection/components/rtk-meeting/rtk-meeting.js +6 -6
- package/dist/collection/components/rtk-meeting-title/rtk-meeting-title.js +1 -1
- package/dist/collection/components/rtk-menu/rtk-menu.js +1 -1
- package/dist/collection/components/rtk-menu-item/rtk-menu-item.js +1 -1
- package/dist/collection/components/rtk-menu-list/rtk-menu-list.js +1 -1
- package/dist/collection/components/rtk-mic-toggle/rtk-mic-toggle.js +1 -1
- package/dist/collection/components/rtk-microphone-selector/rtk-microphone-selector.js +1 -1
- package/dist/collection/components/rtk-mixed-grid/rtk-mixed-grid.js +1 -1
- package/dist/collection/components/rtk-more-toggle/rtk-more-toggle.js +1 -1
- package/dist/collection/components/rtk-mute-all-button/rtk-mute-all-button.js +1 -1
- package/dist/collection/components/rtk-mute-all-confirmation/rtk-mute-all-confirmation.js +1 -1
- package/dist/collection/components/rtk-name-tag/rtk-name-tag.js +1 -1
- package/dist/collection/components/rtk-network-indicator/rtk-network-indicator.js +1 -1
- package/dist/collection/components/rtk-notification/rtk-notification.css +26 -18
- package/dist/collection/components/rtk-notification/rtk-notification.js +35 -5
- package/dist/collection/components/rtk-notifications/rtk-notifications.js +5 -3
- package/dist/collection/components/rtk-overlay-modal/rtk-overlay-modal.js +2 -2
- package/dist/collection/components/rtk-paginated-list/rtk-paginated-list.js +1 -1
- package/dist/collection/components/rtk-participant/rtk-participant.js +1 -1
- package/dist/collection/components/rtk-participant-count/rtk-participant-count.js +1 -1
- package/dist/collection/components/rtk-participant-setup/rtk-participant-setup.js +3 -3
- package/dist/collection/components/rtk-participant-tile/rtk-participant-tile.js +3 -3
- package/dist/collection/components/rtk-participants/rtk-participants.js +1 -1
- package/dist/collection/components/rtk-participants-audio/rtk-participants-audio.js +2 -2
- package/dist/collection/components/rtk-participants-stage-list/rtk-participants-stage-list.js +2 -2
- package/dist/collection/components/rtk-participants-stage-queue/rtk-participants-stage-queue.js +4 -5
- package/dist/collection/components/rtk-participants-toggle/rtk-participants-toggle.js +1 -1
- package/dist/collection/components/rtk-participants-viewer-list/rtk-participants-viewer-list.js +1 -1
- package/dist/collection/components/rtk-participants-waiting-list/rtk-participants-waiting-list.js +1 -1
- package/dist/collection/components/rtk-permissions-message/rtk-permissions-message.js +2 -2
- package/dist/collection/components/rtk-pip-toggle/rtk-pip-toggle.js +1 -1
- package/dist/collection/components/rtk-plugin-main/rtk-plugin-main.js +1 -1
- package/dist/collection/components/rtk-plugins/rtk-plugins.js +2 -2
- package/dist/collection/components/rtk-plugins-toggle/rtk-plugins-toggle.js +1 -1
- package/dist/collection/components/rtk-poll/rtk-poll.js +2 -2
- package/dist/collection/components/rtk-poll-form/rtk-poll-form.js +3 -3
- package/dist/collection/components/rtk-polls/rtk-polls.js +4 -4
- package/dist/collection/components/rtk-polls-toggle/rtk-polls-toggle.js +1 -1
- package/dist/collection/components/rtk-recording-indicator/rtk-recording-indicator.js +2 -2
- package/dist/collection/components/rtk-recording-toggle/rtk-recording-toggle.js +1 -1
- package/dist/collection/components/rtk-screen-share-toggle/rtk-screen-share-toggle.js +2 -3
- package/dist/collection/components/rtk-screenshare-view/rtk-screenshare-view.js +6 -6
- package/dist/collection/components/rtk-settings/rtk-settings.js +1 -1
- package/dist/collection/components/rtk-settings-audio/rtk-settings-audio.js +1 -1
- package/dist/collection/components/rtk-settings-toggle/rtk-settings-toggle.js +2 -2
- package/dist/collection/components/rtk-settings-video/rtk-settings-video.js +1 -1
- package/dist/collection/components/rtk-setup-screen/rtk-setup-screen.css +33 -22
- package/dist/collection/components/rtk-setup-screen/rtk-setup-screen.js +7 -6
- package/dist/collection/components/rtk-sidebar/rtk-sidebar.js +1 -1
- package/dist/collection/components/rtk-sidebar-ui/rtk-sidebar-ui.js +1 -1
- package/dist/collection/components/rtk-simple-grid/rtk-simple-grid.js +2 -2
- package/dist/collection/components/rtk-speaker-selector/rtk-speaker-selector.js +1 -1
- package/dist/collection/components/rtk-spinner/rtk-spinner.js +1 -1
- package/dist/collection/components/rtk-spotlight-grid/rtk-spotlight-grid.js +3 -3
- package/dist/collection/components/rtk-spotlight-indicator/rtk-spotlight-indicator.js +1 -1
- package/dist/collection/components/rtk-stage/rtk-stage.js +2 -2
- package/dist/collection/components/rtk-stage-toggle/rtk-stage-toggle.js +1 -1
- package/dist/collection/components/rtk-switch/rtk-switch.js +2 -2
- package/dist/collection/components/rtk-tab-bar/rtk-tab-bar.js +1 -1
- package/dist/collection/components/rtk-text-composer-view/rtk-text-composer-view.js +2 -2
- package/dist/collection/components/rtk-text-message/rtk-text-message.js +3 -3
- package/dist/collection/components/rtk-text-message-view/rtk-text-message-view.js +1 -1
- package/dist/collection/components/rtk-transcript/rtk-transcript.js +2 -2
- package/dist/collection/components/rtk-transcripts/rtk-transcripts.js +1 -1
- package/dist/collection/components/rtk-ui-provider/rtk-ui-provider.js +7 -7
- package/dist/collection/components/rtk-viewer-count/rtk-viewer-count.js +1 -1
- package/dist/collection/components/rtk-virtualized-list/rtk-virtualized-participant-list.js +2 -2
- package/dist/collection/components/rtk-waiting-screen/rtk-waiting-screen.js +2 -2
- package/dist/collection/lib/audio.js +3 -3
- package/dist/collection/lib/default-ui-config.js +3 -3
- package/dist/collection/lib/lang/default-language.js +1 -2
- package/dist/collection/lib/notification.js +2 -7
- package/dist/collection/utils/config.js +3 -3
- package/dist/components/index.js +5 -5
- package/dist/components/{p-0a9d8224.js → p-01788fc5.js} +4 -4
- package/dist/components/{p-619a7896.js → p-0daa472f.js} +6 -6
- package/dist/components/{p-00b13124.js → p-1174d3f4.js} +14 -14
- package/dist/components/{p-3dbc09e4.js → p-14c496c6.js} +5 -5
- package/dist/components/{p-0ea515b2.js → p-153e1ac6.js} +4 -4
- package/dist/components/{p-eeea40dd.js → p-1590eea9.js} +5 -5
- package/dist/components/{p-db1e56e8.js → p-1633eae1.js} +10 -10
- package/dist/components/{p-3d845f44.js → p-1cc409c6.js} +3 -3
- package/dist/components/{p-4ba64e96.js → p-1d7f3c99.js} +14 -14
- package/dist/components/{p-a24309fd.js → p-1f6e5501.js} +4 -4
- package/dist/components/{p-10182034.js → p-20c74379.js} +2 -2
- package/dist/components/{p-1947c106.js → p-23d64784.js} +4 -4
- package/dist/components/{p-4cc0e9a5.js → p-2507c6c8.js} +1 -1
- package/dist/components/{p-f682505d.js → p-25738f7b.js} +12 -12
- package/dist/components/{p-2f7c0530.js → p-25f625c5.js} +53 -53
- package/dist/components/{p-965a4bd9.js → p-273196ec.js} +4 -4
- package/dist/components/{p-8ca0d44f.js → p-287eadbd.js} +6 -6
- package/dist/components/{p-99b862b5.js → p-2cc196a8.js} +6 -6
- package/dist/components/{p-c7dcb441.js → p-2df5f773.js} +2 -2
- package/dist/components/{p-4a436e2d.js → p-31f1e8e5.js} +4 -4
- package/dist/components/{p-594ed925.js → p-3d5214b4.js} +5 -5
- package/dist/components/{p-7d26c3e0.js → p-40a18d12.js} +5 -5
- package/dist/components/{p-b12e5011.js → p-519e8701.js} +5 -5
- package/dist/components/{p-e4376670.js → p-5597fe9f.js} +8 -8
- package/dist/components/{p-0c81aa9c.js → p-5e5c9b53.js} +9 -9
- package/dist/components/{p-32d788e7.js → p-60b29ed0.js} +3 -3
- package/dist/components/{p-dc23e204.js → p-65da3d17.js} +5 -5
- package/dist/components/{p-fe278fba.js → p-65e9c741.js} +3 -3
- package/dist/components/{p-10759cad.js → p-6631e984.js} +2 -2
- package/dist/components/{p-2ce92a24.js → p-70053efe.js} +7 -7
- package/dist/components/{p-664f872d.js → p-77338347.js} +4 -4
- package/dist/components/{p-935b5e0f.js → p-778197ec.js} +5 -5
- package/dist/components/{p-5ffcbba3.js → p-7916d083.js} +2 -2
- package/dist/components/{p-8ceedb7f.js → p-79534847.js} +4 -4
- package/dist/components/{p-c11b2f37.js → p-7a1b0433.js} +1 -1
- package/dist/components/{p-24ffce5a.js → p-7afb8f24.js} +2 -2
- package/dist/components/p-7b5f7b56.js +107 -0
- package/dist/components/{p-a478e070.js → p-7d76715d.js} +3 -3
- package/dist/components/{p-0eab3933.js → p-7dcce90b.js} +3 -3
- package/dist/components/{p-1bf54ab3.js → p-828a11f4.js} +10 -10
- package/dist/components/{p-d262b31f.js → p-83a87193.js} +8 -8
- package/dist/components/{p-b39c779d.js → p-85665c03.js} +4 -4
- package/dist/components/{p-260b86da.js → p-8750e2de.js} +6 -6
- package/dist/components/{p-46690510.js → p-8804314e.js} +2 -2
- package/dist/components/{p-0e13b6ee.js → p-8eea1b4d.js} +5 -5
- package/dist/components/{p-a41e1b94.js → p-9007d4aa.js} +3 -3
- package/dist/components/{p-c00de10a.js → p-9140d5c1.js} +10 -11
- package/dist/components/{p-4221b28d.js → p-94e8d526.js} +7 -7
- package/dist/components/{p-d5791958.js → p-989a34c9.js} +1 -1
- package/dist/components/{p-91cb38a3.js → p-98d49c8e.js} +4 -4
- package/dist/components/{p-35d6211b.js → p-9b7dc3b2.js} +4 -4
- package/dist/components/{p-2973e211.js → p-9e5b47ea.js} +2 -2
- package/dist/components/{p-caf8596c.js → p-9f29a2f1.js} +10 -8
- package/dist/components/{p-168b17a0.js → p-a09473cb.js} +1 -1
- package/dist/components/{p-50ecaaf1.js → p-a575deb5.js} +3 -8
- package/dist/components/{p-62a6b783.js → p-a59e060b.js} +2 -2
- package/dist/components/{p-e99f574d.js → p-a5d2ac22.js} +25 -25
- package/dist/components/{p-2f2fb96d.js → p-a73161da.js} +1 -1
- package/dist/components/{p-4608147b.js → p-abdd2a8a.js} +5 -5
- package/dist/components/{p-4cedc9e8.js → p-af7aea98.js} +2 -2
- package/dist/components/{p-ef376a73.js → p-afc2ce7b.js} +3 -3
- package/dist/components/{p-ae239151.js → p-b1030316.js} +2 -2
- package/dist/components/{p-8227dcd2.js → p-b1161cb8.js} +3 -3
- package/dist/components/{p-87f1e5db.js → p-b5dc3971.js} +6 -6
- package/dist/components/{p-d3ca55ba.js → p-ba8208ac.js} +5 -5
- package/dist/components/{p-54c8b684.js → p-be584d57.js} +14 -14
- package/dist/components/{p-56586bc8.js → p-c173a513.js} +10 -10
- package/dist/components/{p-8ca1fe4c.js → p-c226934a.js} +12 -12
- package/dist/components/{p-14aafb1d.js → p-c86a0f9e.js} +5 -5
- package/dist/components/{p-175b365f.js → p-cac807c5.js} +5 -5
- package/dist/components/{p-7373cc7e.js → p-cbc8e449.js} +4 -4
- package/dist/components/{p-e2b78972.js → p-cfbb9bd9.js} +4 -4
- package/dist/components/{p-e3b59650.js → p-de2175ca.js} +1 -1
- package/dist/components/{p-66ff4a1a.js → p-de567bdf.js} +5 -5
- package/dist/components/{p-d71db36f.js → p-e9c999f4.js} +5 -5
- package/dist/components/{p-4c4025de.js → p-eaa808b7.js} +8 -8
- package/dist/components/{p-bd9a0ef8.js → p-ebb19a87.js} +21 -6
- package/dist/components/{p-59ea0ce1.js → p-efda30dd.js} +4 -4
- package/dist/components/{p-cd66e89b.js → p-f0df8c15.js} +4 -4
- package/dist/components/{p-31ce3b90.js → p-f4158e29.js} +2 -2
- package/dist/components/{p-135d5d2f.js → p-f634f020.js} +3 -3
- package/dist/components/{p-13bf25de.js → p-f77fe02e.js} +6 -6
- package/dist/components/{p-0f937441.js → p-fab54b49.js} +4 -4
- package/dist/components/{p-00649ab8.js → p-fb31f34b.js} +8 -8
- package/dist/components/{p-e6d09c50.js → p-fc4484ae.js} +4 -5
- package/dist/components/{p-78444f97.js → p-ff13d28d.js} +7 -7
- package/dist/components/{p-b3537ccc.js → p-ff6d9602.js} +4 -4
- package/dist/components/rtk-ai-toggle.js +5 -5
- package/dist/components/rtk-ai-transcriptions.js +1 -1
- package/dist/components/rtk-ai.js +5 -5
- package/dist/components/rtk-audio-grid.js +2 -2
- package/dist/components/rtk-audio-tile.js +6 -6
- package/dist/components/rtk-audio-visualizer.js +1 -1
- package/dist/components/rtk-avatar.js +1 -1
- package/dist/components/rtk-breakout-room-manager.js +1 -1
- package/dist/components/rtk-breakout-room-participants.js +1 -1
- package/dist/components/rtk-breakout-rooms-manager.js +1 -1
- package/dist/components/rtk-breakout-rooms-toggle.js +5 -5
- package/dist/components/rtk-broadcast-message-modal.js +1 -1
- package/dist/components/rtk-button.js +1 -1
- package/dist/components/rtk-camera-selector.js +1 -1
- package/dist/components/rtk-camera-toggle.js +6 -6
- package/dist/components/rtk-caption-toggle.js +5 -5
- package/dist/components/rtk-channel-creator.js +1 -1
- package/dist/components/rtk-channel-details.js +1 -1
- package/dist/components/rtk-channel-header.js +1 -1
- package/dist/components/rtk-channel-selector-ui.js +6 -6
- package/dist/components/rtk-channel-selector-view.js +1 -1
- package/dist/components/rtk-chat-composer-ui.js +8 -8
- package/dist/components/rtk-chat-composer-view.js +1 -1
- package/dist/components/rtk-chat-message.js +1 -1
- package/dist/components/rtk-chat-messages-ui-paginated.js +1 -1
- package/dist/components/rtk-chat-messages-ui.js +1 -1
- package/dist/components/rtk-chat-search-results.js +1 -1
- package/dist/components/rtk-chat-selector-ui.js +3 -3
- package/dist/components/rtk-chat-toggle.js +6 -6
- package/dist/components/rtk-chat.js +1 -1
- package/dist/components/rtk-clock.js +3 -3
- package/dist/components/rtk-confirmation-modal.js +1 -1
- package/dist/components/rtk-controlbar-button.js +1 -1
- package/dist/components/rtk-controlbar.js +2 -2
- package/dist/components/rtk-counter.js +1 -1
- package/dist/components/rtk-debugger-audio.js +1 -1
- package/dist/components/rtk-debugger-screenshare.js +1 -1
- package/dist/components/rtk-debugger-system.js +1 -1
- package/dist/components/rtk-debugger-toggle.js +5 -5
- package/dist/components/rtk-debugger-video.js +1 -1
- package/dist/components/rtk-debugger.js +1 -1
- package/dist/components/rtk-dialog-manager.js +1 -1
- package/dist/components/rtk-dialog.js +1 -1
- package/dist/components/rtk-draft-attachment-view.js +1 -1
- package/dist/components/rtk-emoji-picker-button.js +1 -1
- package/dist/components/rtk-emoji-picker.js +1 -1
- package/dist/components/rtk-ended-screen.js +4 -4
- package/dist/components/rtk-file-dropzone.js +3 -3
- package/dist/components/rtk-file-message-view.js +1 -1
- package/dist/components/rtk-file-message.js +1 -1
- package/dist/components/rtk-file-picker-button.js +1 -1
- package/dist/components/rtk-fullscreen-toggle.js +1 -1
- package/dist/components/rtk-grid-pagination.js +5 -5
- package/dist/components/rtk-grid.js +10 -10
- package/dist/components/rtk-header.js +2 -2
- package/dist/components/rtk-icon.js +1 -1
- package/dist/components/rtk-idle-screen.js +5 -5
- package/dist/components/rtk-image-message-view.js +1 -1
- package/dist/components/rtk-image-message.js +1 -1
- package/dist/components/rtk-image-viewer.js +4 -4
- package/dist/components/rtk-information-tooltip.js +3 -3
- package/dist/components/rtk-join-stage.js +1 -1
- package/dist/components/rtk-leave-button.js +5 -5
- package/dist/components/rtk-leave-meeting.js +1 -1
- package/dist/components/rtk-livestream-indicator.js +1 -1
- package/dist/components/rtk-livestream-player.js +1 -1
- package/dist/components/rtk-livestream-toggle.js +5 -5
- package/dist/components/rtk-logo.js +1 -1
- package/dist/components/rtk-meeting-title.js +3 -3
- package/dist/components/rtk-meeting.js +60 -60
- package/dist/components/rtk-menu-item.js +1 -1
- package/dist/components/rtk-menu-list.js +1 -1
- package/dist/components/rtk-menu.js +1 -1
- package/dist/components/rtk-message-list-view.js +4 -4
- package/dist/components/rtk-message-view.js +1 -1
- package/dist/components/rtk-mic-toggle.js +6 -6
- package/dist/components/rtk-microphone-selector.js +1 -1
- package/dist/components/rtk-mixed-grid.js +8 -8
- package/dist/components/rtk-more-toggle.js +5 -5
- package/dist/components/rtk-mute-all-button.js +6 -6
- package/dist/components/rtk-mute-all-confirmation.js +1 -1
- package/dist/components/rtk-name-tag.js +1 -1
- package/dist/components/rtk-network-indicator.js +3 -3
- package/dist/components/rtk-notification.js +1 -1
- package/dist/components/rtk-notifications.js +1 -1
- package/dist/components/rtk-overlay-modal.js +1 -1
- package/dist/components/rtk-paginated-list.js +1 -1
- package/dist/components/rtk-participant-count.js +3 -3
- package/dist/components/rtk-participant-setup.js +4 -4
- package/dist/components/rtk-participant-tile.js +1 -1
- package/dist/components/rtk-participant.js +1 -1
- package/dist/components/rtk-participants-audio.js +9 -9
- package/dist/components/rtk-participants-stage-list.js +1 -1
- package/dist/components/rtk-participants-stage-queue.js +1 -1
- package/dist/components/rtk-participants-toggle.js +6 -6
- package/dist/components/rtk-participants-viewer-list.js +1 -1
- package/dist/components/rtk-participants-waiting-list.js +1 -1
- package/dist/components/rtk-participants.js +16 -16
- package/dist/components/rtk-permissions-message.js +1 -1
- package/dist/components/rtk-pip-toggle.js +5 -5
- package/dist/components/rtk-plugin-main.js +1 -1
- package/dist/components/rtk-plugins-toggle.js +6 -6
- package/dist/components/rtk-plugins.js +1 -1
- package/dist/components/rtk-poll-form.js +1 -1
- package/dist/components/rtk-poll.js +1 -1
- package/dist/components/rtk-polls-toggle.js +6 -6
- package/dist/components/rtk-polls.js +1 -1
- package/dist/components/rtk-recording-indicator.js +4 -4
- package/dist/components/rtk-recording-toggle.js +5 -5
- package/dist/components/rtk-screen-share-toggle.js +7 -8
- package/dist/components/rtk-screenshare-view.js +10 -10
- package/dist/components/rtk-settings-audio.js +1 -1
- package/dist/components/rtk-settings-toggle.js +6 -6
- package/dist/components/rtk-settings-video.js +1 -1
- package/dist/components/rtk-settings.js +12 -12
- package/dist/components/rtk-setup-screen.js +14 -13
- package/dist/components/rtk-sidebar-ui.js +1 -1
- package/dist/components/rtk-sidebar.js +11 -11
- package/dist/components/rtk-simple-grid.js +3 -3
- package/dist/components/rtk-speaker-selector.js +1 -1
- package/dist/components/rtk-spinner.js +1 -1
- package/dist/components/rtk-spotlight-grid.js +4 -4
- package/dist/components/rtk-spotlight-indicator.js +1 -1
- package/dist/components/rtk-stage-toggle.js +6 -6
- package/dist/components/rtk-stage.js +3 -3
- package/dist/components/rtk-switch.js +1 -1
- package/dist/components/rtk-tab-bar.js +1 -1
- package/dist/components/rtk-text-composer-view.js +1 -1
- package/dist/components/rtk-text-message-view.js +1 -1
- package/dist/components/rtk-text-message.js +1 -1
- package/dist/components/rtk-tooltip.js +1 -1
- package/dist/components/rtk-transcript.js +1 -1
- package/dist/components/rtk-transcripts.js +3 -3
- package/dist/components/rtk-ui-provider.js +8 -8
- package/dist/components/rtk-viewer-count.js +1 -1
- package/dist/components/rtk-virtualized-participant-list.js +1 -1
- package/dist/components/rtk-waiting-screen.js +4 -4
- package/dist/docs/docs-components.json +278 -755
- package/dist/docs/docs-vscode.json +4 -0
- package/dist/esm/{TextMessage-efd224db.js → TextMessage-3e08c5e1.js} +1 -1
- package/dist/esm/{chat-c25836b0.js → chat-927074dc.js} +1 -1
- package/dist/esm/{config-1ca1ba30.js → config-407ad80b.js} +4 -4
- package/dist/esm/{index-6aaa85ca.js → index-3481d5b2.js} +1 -1
- package/dist/esm/index.js +6 -7
- package/dist/esm/loader.js +105 -86
- package/dist/esm/{notification-800f2bcd.js → notification-2ab22a76.js} +3 -8
- package/dist/esm/realtimekit-ui.js +1 -1
- package/dist/esm/rtk-ai-toggle.entry.js +2 -2
- package/dist/esm/rtk-ai-transcriptions.entry.js +2 -2
- package/dist/esm/rtk-ai.entry.js +2 -2
- package/dist/esm/rtk-audio-grid.entry.js +2 -2
- package/dist/esm/rtk-audio-tile.entry.js +2 -2
- package/dist/esm/rtk-audio-visualizer_4.entry.js +3 -3
- package/dist/esm/rtk-avatar_54.entry.js +53 -29
- package/dist/esm/rtk-breakout-rooms-toggle.entry.js +2 -2
- package/dist/esm/rtk-camera-selector_2.entry.js +4 -4
- package/dist/esm/rtk-camera-toggle.entry.js +2 -2
- package/dist/esm/rtk-caption-toggle.entry.js +2 -2
- package/dist/esm/rtk-channel-selector-ui.entry.js +4 -4
- package/dist/esm/rtk-chat-composer-ui.entry.js +3 -3
- package/dist/esm/rtk-chat-selector-ui.entry.js +3 -3
- package/dist/esm/rtk-chat-toggle.entry.js +3 -3
- package/dist/esm/rtk-clock.entry.js +2 -2
- package/dist/esm/rtk-controlbar-button.entry.js +3 -3
- package/dist/esm/rtk-controlbar.entry.js +2 -2
- package/dist/esm/rtk-debugger-toggle.entry.js +2 -2
- package/dist/esm/rtk-ended-screen.entry.js +2 -2
- package/dist/esm/rtk-file-dropzone.entry.js +2 -2
- package/dist/esm/rtk-fullscreen-toggle.entry.js +2 -2
- package/dist/esm/rtk-grid-pagination.entry.js +2 -2
- package/dist/esm/rtk-grid.entry.js +2 -2
- package/dist/esm/rtk-header.entry.js +2 -2
- package/dist/esm/rtk-idle-screen.entry.js +2 -2
- package/dist/esm/rtk-image-viewer.entry.js +2 -2
- package/dist/esm/rtk-information-tooltip.entry.js +2 -2
- package/dist/esm/rtk-leave-button.entry.js +2 -2
- package/dist/esm/rtk-livestream-indicator_3.entry.js +2 -2
- package/dist/esm/rtk-livestream-toggle.entry.js +2 -2
- package/dist/esm/rtk-meeting-title.entry.js +2 -2
- package/dist/esm/rtk-message-list-view.entry.js +2 -2
- package/dist/esm/rtk-mic-toggle.entry.js +2 -2
- package/dist/esm/rtk-mixed-grid.entry.js +2 -2
- package/dist/esm/rtk-more-toggle.entry.js +2 -2
- package/dist/esm/rtk-mute-all-button.entry.js +2 -2
- package/dist/esm/rtk-name-tag.entry.js +2 -2
- package/dist/esm/rtk-network-indicator.entry.js +2 -2
- package/dist/esm/rtk-participant-count.entry.js +2 -2
- package/dist/esm/rtk-participant-setup.entry.js +4 -4
- package/dist/esm/rtk-participant_2.entry.js +4 -4
- package/dist/esm/rtk-participants-audio.entry.js +6 -6
- package/dist/esm/rtk-participants-stage-list_4.entry.js +6 -7
- package/dist/esm/rtk-participants-toggle.entry.js +3 -3
- package/dist/esm/rtk-participants.entry.js +2 -2
- package/dist/esm/rtk-pip-toggle.entry.js +2 -2
- package/dist/esm/rtk-plugin-main_2.entry.js +2 -2
- package/dist/esm/rtk-plugins-toggle.entry.js +3 -3
- package/dist/esm/rtk-plugins_2.entry.js +6 -6
- package/dist/esm/rtk-poll_2.entry.js +5 -5
- package/dist/esm/rtk-polls-toggle.entry.js +3 -3
- package/dist/esm/rtk-recording-indicator.entry.js +3 -3
- package/dist/esm/rtk-recording-toggle.entry.js +2 -2
- package/dist/esm/rtk-screen-share-toggle.entry.js +3 -4
- package/dist/esm/rtk-screenshare-view.entry.js +7 -7
- package/dist/esm/rtk-settings-audio_2.entry.js +2 -2
- package/dist/esm/rtk-settings-toggle.entry.js +3 -3
- package/dist/esm/rtk-settings.entry.js +2 -2
- package/dist/esm/rtk-setup-screen.entry.js +8 -7
- package/dist/esm/rtk-sidebar-ui.entry.js +2 -2
- package/dist/esm/rtk-sidebar.entry.js +3 -3
- package/dist/esm/rtk-simple-grid.entry.js +3 -3
- package/dist/esm/rtk-spotlight-grid.entry.js +4 -4
- package/dist/esm/rtk-spotlight-indicator.entry.js +2 -2
- package/dist/esm/rtk-stage-toggle.entry.js +2 -2
- package/dist/esm/rtk-stage.entry.js +3 -3
- package/dist/esm/rtk-transcript.entry.js +3 -3
- package/dist/esm/rtk-transcripts.entry.js +2 -2
- package/dist/esm/rtk-ui-provider.entry.js +8 -8
- package/dist/esm/rtk-waiting-screen.entry.js +3 -3
- package/dist/esm/{sidebar-cafaa8d3.js → sidebar-50d89918.js} +1 -1
- package/dist/esm/{ui-store-b453cdf2.js → ui-store-1b477153.js} +4 -5
- package/dist/realtimekit-ui/index.esm.js +1 -1
- package/dist/realtimekit-ui/{p-9946b484.entry.js → p-0215809e.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-9ff45356.entry.js → p-076d6fb1.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-6c238609.entry.js → p-0787a8a4.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-8fe6b03c.entry.js → p-0b8b849b.entry.js} +1 -1
- package/dist/realtimekit-ui/p-0df0bc3b.entry.js +1 -0
- package/dist/realtimekit-ui/{p-0d4db84d.entry.js → p-0f91e886.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-3611c234.entry.js → p-11a81411.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-560c3d93.entry.js → p-14284891.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-dbb95589.entry.js → p-15e0e0fc.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-6be9be47.entry.js → p-17588509.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-bc17c582.entry.js → p-19ffa2e9.entry.js} +1 -1
- package/dist/realtimekit-ui/p-221efc53.entry.js +1 -0
- package/dist/realtimekit-ui/{p-139da463.entry.js → p-293547d1.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-9435f236.entry.js → p-3e54f3e8.entry.js} +1 -1
- package/dist/realtimekit-ui/p-4023c083.js +1 -0
- package/dist/realtimekit-ui/{p-affaaf1a.entry.js → p-44c22bd9.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-b62f9abb.entry.js → p-49602b35.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-b14563cb.entry.js → p-4bace64f.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-0a1d9e02.entry.js → p-4bcf9db7.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-01f5aba6.entry.js → p-5444d39b.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-679bd218.entry.js → p-546ff22a.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-42a64cbb.entry.js → p-5b277ae0.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-457a0412.entry.js → p-629258de.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-5b15e3cf.entry.js → p-63064c88.entry.js} +1 -1
- package/dist/realtimekit-ui/p-64514c63.entry.js +1 -0
- package/dist/realtimekit-ui/{p-d9217d24.entry.js → p-67dcfbf3.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-050f0b1f.entry.js → p-6f487b93.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-7dbd2a25.entry.js → p-6f56ad30.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-03a04390.entry.js → p-6fd65de6.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-d075d673.entry.js → p-7597f3ea.entry.js} +1 -1
- package/dist/realtimekit-ui/p-7965a765.entry.js +1 -0
- package/dist/realtimekit-ui/{p-dd9b1b30.entry.js → p-7ade6183.entry.js} +1 -1
- package/dist/realtimekit-ui/p-7d0ad5a8.entry.js +1 -0
- package/dist/realtimekit-ui/{p-93f881e2.entry.js → p-7e96fb7b.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-85ff4a34.entry.js → p-86afa8c3.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-a5d22edf.entry.js → p-8819f726.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-4d8ab9a5.entry.js → p-89543b39.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-f5ad8c8f.entry.js → p-8e869d13.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-d77f7f22.entry.js → p-9274e173.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-3fd79328.entry.js → p-9a2536ed.entry.js} +1 -1
- package/dist/realtimekit-ui/p-9d038c16.entry.js +1 -0
- package/dist/realtimekit-ui/p-9d8e8a27.entry.js +1 -0
- package/dist/realtimekit-ui/{p-4ff47eb0.entry.js → p-9de3f942.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-80a02bba.entry.js → p-a42c0e83.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-6ededa68.js → p-a4922241.js} +1 -1
- package/dist/realtimekit-ui/{p-25c7522f.entry.js → p-a845c29f.entry.js} +1 -1
- package/dist/realtimekit-ui/p-a8b7c6a2.entry.js +1 -0
- package/dist/realtimekit-ui/p-ac8a0151.entry.js +1 -0
- package/dist/realtimekit-ui/{p-e171b1c4.entry.js → p-acd86770.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-94b739b4.entry.js → p-b15377a2.entry.js} +1 -1
- package/dist/realtimekit-ui/p-b5af8a86.entry.js +1 -0
- package/dist/realtimekit-ui/p-b60b229e.entry.js +1 -0
- package/dist/realtimekit-ui/{p-238a19f8.entry.js → p-b965ac1d.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-b16cee89.js → p-bf5ecc7c.js} +1 -1
- package/dist/realtimekit-ui/{p-917f2951.entry.js → p-c1db5ef9.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-4b882b41.js → p-c203aff3.js} +1 -1
- package/dist/realtimekit-ui/{p-4dc84daa.entry.js → p-c39a8005.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-0d071b0c.entry.js → p-c4fc57c1.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-55503b00.entry.js → p-c6837853.entry.js} +1 -1
- package/dist/realtimekit-ui/p-c6eb9963.entry.js +1 -0
- package/dist/realtimekit-ui/p-d3bf4348.js +1 -0
- package/dist/realtimekit-ui/p-d560f5c8.entry.js +1 -0
- package/dist/realtimekit-ui/{p-7af0573f.entry.js → p-d8c2b553.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-807dd186.entry.js → p-d9138a0d.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-5584d146.entry.js → p-da56f340.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-aaba206b.js → p-da59b75c.js} +1 -1
- package/dist/realtimekit-ui/p-dac97779.js +1 -0
- package/dist/realtimekit-ui/{p-373ea59c.entry.js → p-dd6d2ca9.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-44915a3b.entry.js → p-e0450660.entry.js} +1 -1
- package/dist/realtimekit-ui/p-e0a80608.entry.js +1 -0
- package/dist/realtimekit-ui/p-ea1736c3.entry.js +1 -0
- package/dist/realtimekit-ui/{p-7536cb87.entry.js → p-eb4025c0.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-556db3a1.entry.js → p-ed87ad1f.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-bf56688f.entry.js → p-efbe07a6.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-d013442a.entry.js → p-f2ba56ec.entry.js} +1 -1
- package/dist/realtimekit-ui/p-f3d02201.entry.js +1 -0
- package/dist/realtimekit-ui/{p-e13b5128.entry.js → p-f78cecba.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-fb67b669.entry.js → p-fa03ab98.entry.js} +1 -1
- package/dist/realtimekit-ui/realtimekit-ui.esm.js +1 -1
- package/dist/types/components/rtk-dialog/rtk-dialog.d.ts +2 -0
- package/dist/types/components/rtk-notification/rtk-notification.d.ts +4 -0
- package/dist/types/components/rtk-notifications/rtk-notifications.d.ts +1 -0
- package/dist/types/components.d.ts +8 -0
- package/dist/types/lib/audio.d.ts +1 -0
- package/dist/types/lib/lang/default-language.d.ts +0 -1
- package/package.json +3 -2
- package/dist/cjs/logger-3df9c75d.js +0 -5
- package/dist/collection/utils/logger.js +0 -1
- package/dist/components/p-20354866.js +0 -96
- package/dist/components/p-5605a420.js +0 -3
- package/dist/esm/logger-31448943.js +0 -3
- package/dist/realtimekit-ui/p-050469f0.entry.js +0 -1
- package/dist/realtimekit-ui/p-131b1e94.entry.js +0 -1
- package/dist/realtimekit-ui/p-29802710.entry.js +0 -1
- package/dist/realtimekit-ui/p-2aa242f4.js +0 -1
- package/dist/realtimekit-ui/p-3d312beb.entry.js +0 -1
- package/dist/realtimekit-ui/p-3ed1c004.entry.js +0 -1
- package/dist/realtimekit-ui/p-4211ad5e.entry.js +0 -1
- package/dist/realtimekit-ui/p-4f45e362.entry.js +0 -1
- package/dist/realtimekit-ui/p-5605a420.js +0 -1
- package/dist/realtimekit-ui/p-89f6a08a.entry.js +0 -1
- package/dist/realtimekit-ui/p-9bbe1d7c.entry.js +0 -1
- package/dist/realtimekit-ui/p-9ca13287.entry.js +0 -1
- package/dist/realtimekit-ui/p-a6f03681.entry.js +0 -1
- package/dist/realtimekit-ui/p-a738a7b3.entry.js +0 -1
- package/dist/realtimekit-ui/p-c7f14fd0.entry.js +0 -1
- package/dist/realtimekit-ui/p-d1e6d6c4.entry.js +0 -1
- package/dist/realtimekit-ui/p-e1091812.entry.js +0 -1
- package/dist/realtimekit-ui/p-ee167b96.js +0 -1
- package/dist/realtimekit-ui/p-fc36f92c.js +0 -1
- package/dist/realtimekit-ui/p-fc704ef3.entry.js +0 -1
- package/dist/types/utils/logger.d.ts +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as t,h as i,H as s,c as e,a as n}from"./p-0ee570cd.js";import{c as r,a as h,s as o,P as a,t as l}from"./p-ee167b96.js";import{S as c}from"./p-2aa242f4.js";var u=function(t,i,s,e){var n,r=arguments.length,h=r<3?i:null===e?e=Object.getOwnPropertyDescriptor(i,s):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)h=Reflect.decorate(t,i,s,e);else for(var o=t.length-1;o>=0;o--)(n=t[o])&&(h=(r<3?n(h):r>3?n(i,s,h):n(i,s))||h);return r>3&&h&&Object.defineProperty(i,s,h),h};const d=class{constructor(i){t(this,i),this.t=r(),this.iconPack=h,this.setIsLivestreaming=t=>{this.isLivestreaming="LIVESTREAMING"===t}}connectedCallback(){this.meetingChanged(this.meeting)}disconnectedCallback(){var t,i;null===(i=null===(t=this.meeting)||void 0===t?void 0:t.livestream)||void 0===i||i.removeListener("livestreamUpdate",this.setIsLivestreaming)}meetingChanged(t){var i,s;null!=t&&(this.setIsLivestreaming(null===(i=this.meeting.livestream)||void 0===i?void 0:i.state),null===(s=this.meeting.livestream)||void 0===s||s.on("livestreamUpdate",this.setIsLivestreaming))}render(){return o(this.meeting)&&this.isLivestreaming?i(s,null,i("div",{class:"indicator","aria-label":this.t("livestream.indicator"),part:"indicator"},i("rtk-icon",{icon:this.iconPack.start_livestream,size:this.size}),i("span",null,this.t("LIVE")))):i(s,{"data-hidden":!0})}static get watchers(){return{meeting:["meetingChanged"]}}};function f(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}u([c()],d.prototype,"meeting",void 0),u([c()],d.prototype,"size",void 0),u([c()],d.prototype,"t",void 0),u([c()],d.prototype,"iconPack",void 0),d.style=":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{margin-left:var(--rtk-space-2, 8px);margin-right:var(--rtk-space-2, 8px);display:flex}:host([data-hidden]){display:none}:host[size='sm']{margin-left:var(--rtk-space-1, 4px);margin-right:var(--rtk-space-1, 4px)}.indicator{display:flex;flex-direction:row;align-items:center;font-size:14px;--tw-text-opacity:1;color:rgba(var(--rtk-colors-danger, 255 45 45) / var(--tw-text-opacity))}rtk-icon{margin-right:var(--rtk-space-1, 4px);height:var(--rtk-space-5, 20px);width:var(--rtk-space-5, 20px);animation:blink 4s linear infinite}:host([size='sm']) rtk-icon{height:var(--rtk-space-4, 16px);width:var(--rtk-space-4, 16px)}:host([size='sm']) .indicator span{display:none}@keyframes blink{0%,10%{opacity:0}11%,100%{opacity:1}}";var v,p,g,m,y;v=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,p=/^(?=([^\/?#]*))\1([^]*)$/,g=/(?:\/|^)\.(?=\/)/g,m=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;var w={exports:{}}.exports=y={buildAbsoluteURL:function(t,i,s){if(s=s||{},t=t.trim(),!(i=i.trim())){if(!s.alwaysNormalize)return t;var e=y.parseURL(t);if(!e)throw new Error("Error trying to parse base URL.");return e.path=y.normalizePath(e.path),y.buildURLFromParts(e)}var n=y.parseURL(i);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=y.normalizePath(n.path),y.buildURLFromParts(n)):i;var r=y.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");if(!r.netLoc&&r.path&&"/"!==r.path[0]){var h=p.exec(r.path);r.netLoc=h[1],r.path=h[2]}r.netLoc&&!r.path&&(r.path="/");var o={scheme:r.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(o.netLoc=r.netLoc,"/"!==n.path[0]))if(n.path){var a=r.path,l=a.substring(0,a.lastIndexOf("/")+1)+n.path;o.path=y.normalizePath(l)}else o.path=r.path,n.params||(o.params=r.params,n.query||(o.query=r.query));return null===o.path&&(o.path=s.alwaysNormalize?y.normalizePath(n.path):n.path),y.buildURLFromParts(o)},parseURL:function(t){var i=v.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(g,"");t.length!==(t=t.replace(m,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};function b(t,i){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var e=Object.getOwnPropertySymbols(t);i&&(e=e.filter((function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable}))),s.push.apply(s,e)}return s}function k(t){for(var i=1;i<arguments.length;i++){var s=null!=arguments[i]?arguments[i]:{};i%2?b(Object(s),!0).forEach((function(i){var e,n,r;e=t,r=s[i],(n=function(t){var i=function(t,i){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var e=s.call(t,i||"default");if("object"!=typeof e)return e;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===i?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:String(i)}(n=i))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):b(Object(s)).forEach((function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(s,i))}))}return t}function S(){return S=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var s=arguments[i];for(var e in s)Object.prototype.hasOwnProperty.call(s,e)&&(t[e]=s[e])}return t},S.apply(this,arguments)}const T=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},$=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=E},E=Number.MAX_SAFE_INTEGER||9007199254740991;let A=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),M=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),L=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const x=function(){},D={trace:x,debug:x,log:x,warn:x,info:x,error:x};let C=D;const I=C,R=/^(\d+)x(\d+)$/,P=/(.+?)=(".*?"|.*?)(?:,|$)/g;class O{constructor(t){"string"==typeof t&&(t=O.parseAttrList(t)),S(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const i=parseInt(this[t],10);return i>Number.MAX_SAFE_INTEGER?1/0:i}hexadecimalInteger(t){if(this[t]){let i=(this[t]||"0x").slice(2);i=(1&i.length?"0":"")+i;const s=new Uint8Array(i.length/2);for(let t=0;t<i.length/2;t++)s[t]=parseInt(i.slice(2*t,2*t+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const i=parseInt(this[t],16);return i>Number.MAX_SAFE_INTEGER?1/0:i}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,i){const s=this[t];return s?parseFloat(s):i}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const i=R.exec(this[t]);if(null!==i)return{width:parseInt(i[1],10),height:parseInt(i[2],10)}}static parseAttrList(t){let i;const s={};for(P.lastIndex=0;null!==(i=P.exec(t));){let t=i[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1)),s[i[1].trim()]=t}return s}}function N(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class U{constructor(t,i){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,i){const s=i.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==s[i]){I.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=S(new O({}),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"]);T(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(T(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&&T(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class F{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 B="audio",j="video",_="audiovideo";class G{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[B]:null,[j]:null,[_]:null},this.baseurl=t}setByteRange(t,i){const s=t.split("@",2);let e;e=1===s.length?(null==i?void 0:i.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[e,parseInt(s[0])+e]}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=w.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class H extends G{constructor(t,i){super(i),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 F,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(!T(this.programDateTime))return null;const t=T(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),i=t.length;if(i>1||1===i&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const i=this.levelkeys[t];i&&!this._decryptdata&&(this._decryptdata=i.getDecryptData(this.sn))}}abortRequests(){var t,i;null==(t=this.loader)||t.abort(),null==(i=this.keyLoader)||i.abort()}setElementaryStreamInfo(t,i,s,e,n,r=!1){const{elementaryStreams:h}=this,o=h[t];o?(o.startPTS=Math.min(o.startPTS,i),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,e),o.endDTS=Math.max(o.endDTS,n)):h[t]={startPTS:i,endPTS:s,startDTS:e,endDTS:n,partial:r}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[B]=null,t[j]=null,t[_]=null}}class K extends G{constructor(t,i,s,e,n){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 F,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=i,this.index=e;const r=t.enumeratedString("BYTERANGE");r&&this.setByteRange(r,n),n&&(this.fragOffset=n.fragOffset+n.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 V{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 i=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!i||!this.live,this.advanced=this.endSN>t.endSN||i>0||0===i&&s>0,this.misses=this.updated||this.advanced?Math.floor(.6*t.misses):t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&T(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t: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 z(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function W(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const X="undefined"!=typeof self?self:void 0;var q={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Y="org.w3.clearkey",J="com.apple.streamingkeydelivery",Q="com.microsoft.playready",Z="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function tt(t){switch(t){case J:return q.FAIRPLAY;case Q:return q.PLAYREADY;case Z:return q.WIDEVINE;case Y:return q.CLEARKEY}}function it(t){return"edef8ba979d64acea3c827dcd51d21ed"===t?q.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===t?q.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===t||"e2719d58a985b3c9781ab030af78d30e"===t?q.CLEARKEY:void 0}function st(t){switch(t){case q.FAIRPLAY:return J;case q.PLAYREADY:return Q;case q.WIDEVINE:return Z;case q.CLEARKEY:return Y}}function et(t){const{drmSystems:i,widevineLicenseUrl:s}=t,e=i?[q.FAIRPLAY,q.WIDEVINE,q.PLAYREADY,q.CLEARKEY].filter((t=>!!i[t])):[];return!e[q.WIDEVINE]&&s&&e.push(q.WIDEVINE),e}const nt=null!=X&&null!=(rt=X.navigator)&&rt.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var rt;function ht(t){const i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),s=String.fromCharCode.apply(null,Array.from(i)),e=s.substring(s.indexOf("<"),s.length),n=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const i=z(t).subarray(0,16);return function(t){const i=function(t,i,s){const e=t[i];t[i]=t[s],t[s]=e};i(t,0,3),i(t,1,2),i(t,4,5),i(t,6,7)}(i),i}}return null}function ot(t,i,s){return Uint8Array.prototype.slice?t.slice(i,s):new Uint8Array(Array.prototype.slice.call(t,i,s))}const at=(t,i)=>i+10<=t.length&&73===t[i]&&68===t[i+1]&&51===t[i+2]&&t[i+3]<255&&t[i+4]<255&&t[i+6]<128&&t[i+7]<128&&t[i+8]<128&&t[i+9]<128,lt=(t,i)=>i+10<=t.length&&51===t[i]&&68===t[i+1]&&73===t[i+2]&&t[i+3]<255&&t[i+4]<255&&t[i+6]<128&&t[i+7]<128&&t[i+8]<128&&t[i+9]<128,ct=(t,i)=>{const s=i;let e=0;for(;at(t,i);)e+=10,e+=ut(t,i+6),lt(t,i+10)&&(e+=10),i+=e;if(e>0)return t.subarray(s,s+e)},ut=(t,i)=>{let s=0;return s=(127&t[i])<<21,s|=(127&t[i+1])<<14,s|=(127&t[i+2])<<7,s|=127&t[i+3],s},dt=(t,i)=>at(t,i)&&ut(t,i+6)+10<=t.length-i,ft=t=>{const i=gt(t);for(let t=0;t<i.length;t++){const s=i[t];if(vt(s))return kt(s)}},vt=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,pt=t=>{const i=String.fromCharCode(t[0],t[1],t[2],t[3]),s=ut(t,4);return{type:i,size:s,data:t.subarray(10,10+s)}},gt=t=>{let i=0;const s=[];for(;at(t,i);){const e=ut(t,i+6);i+=10;const n=i+e;for(;i+8<n;){const e=pt(t.subarray(i)),n=mt(e);n&&s.push(n),i+=e.size+10}lt(t,i)&&(i+=10)}return s},mt=t=>"PRIV"===t.type?yt(t):"W"===t.type[0]?bt(t):wt(t),yt=t=>{if(t.size<2)return;const i=St(t.data,!0),s=new Uint8Array(t.data.subarray(i.length+1));return{key:t.type,info:i,data:s.buffer}},wt=t=>{if(t.size<2)return;if("TXXX"===t.type){let i=1;const s=St(t.data.subarray(i),!0);i+=s.length+1;const e=St(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=St(t.data.subarray(1));return{key:t.type,data:i}},bt=t=>{if("WXXX"===t.type){if(t.size<2)return;let i=1;const s=St(t.data.subarray(i),!0);i+=s.length+1;const e=St(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=St(t.data);return{key:t.type,data:i}},kt=t=>{if(8===t.data.byteLength){const i=new Uint8Array(t.data);let s=(i[4]<<23)+(i[5]<<15)+(i[6]<<7)+i[7];return s/=45,1&i[3]&&(s+=47721858.84),Math.round(s)}},St=(t,i=!1)=>{const s=$t();if(s){const e=s.decode(t);if(i){const t=e.indexOf("\0");return-1!==t?e.substring(0,t):e}return e.replace(/\0/g,"")}const e=t.length;let n,r,h,o="",a=0;for(;a<e;){if(n=t[a++],0===n&&i)return o;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(n);break;case 12:case 13:r=t[a++],o+=String.fromCharCode((31&n)<<6|63&r);break;case 14:r=t[a++],h=t[a++],o+=String.fromCharCode((15&n)<<12|(63&r)<<6|63&h)}}return o};let Tt;function $t(){if(!navigator.userAgent.includes("PlayStation 4"))return Tt||void 0===self.TextDecoder||(Tt=new self.TextDecoder("utf-8")),Tt}const Et=function(t){let i="";for(let s=0;s<t.length;s++){let e=t[s].toString(16);e.length<2&&(e="0"+e),i+=e}return i},At=Math.pow(2,32)-1,Mt=[].push,Lt={video:1,audio:2,id3:3,text:4};function xt(t){return String.fromCharCode.apply(null,t)}function Dt(t,i){const s=t[i]<<8|t[i+1];return s<0?65536+s:s}function Ct(t,i){const s=Rt(t,i);return s<0?4294967296+s:s}function It(t,i){let s=Ct(t,i);return s*=Math.pow(2,32),s+=Ct(t,i+4),s}function Rt(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function Pt(t,i,s){t[i]=s>>24,t[i+1]=s>>16&255,t[i+2]=s>>8&255,t[i+3]=255&s}function Ot(t,i){const s=[];if(!i.length)return s;const e=t.byteLength;for(let n=0;n<e;){const r=Ct(t,n),h=r>1?n+r:e;if(xt(t.subarray(n+4,n+8))===i[0])if(1===i.length)s.push(t.subarray(n+8,h));else{const e=Ot(t.subarray(n+8,h),i.slice(1));e.length&&Mt.apply(s,e)}n=h}return s}function Nt(t){const i=[],s=t[0];let e=8;const n=Ct(t,e);e+=4;let r=0,h=0;0===s?(r=Ct(t,e),h=Ct(t,e+4),e+=8):(r=It(t,e),h=It(t,e+8),e+=16),e+=2;let o=t.length+h;const a=Dt(t,e);e+=2;for(let s=0;s<a;s++){let s=e;const r=Ct(t,s);s+=4;const h=2147483647&r;if(1==(2147483648&r)>>>31)return I.warn("SIDX has hierarchical references (not supported)"),null;const a=Ct(t,s);s+=4,i.push({referenceSize:h,subsegmentDuration:a,info:{duration:a/n,start:o,end:o+h-1}}),o+=h,s+=4,e=s}return{earliestPresentationTime:r,timescale:n,version:s,referencesCount:a,references:i}}function Ut(t){const i=[],s=Ot(t,["moov","trak"]);for(let t=0;t<s.length;t++){const e=s[t],n=Ot(e,["tkhd"])[0];if(n){let t=n[0];const s=Ct(n,0===t?12:20),r=Ot(e,["mdia","mdhd"])[0];if(r){t=r[0];const n=Ct(r,0===t?12:20),h=Ot(e,["mdia","hdlr"])[0];if(h){const t=xt(h.subarray(8,12)),r={soun:B,vide:j}[t];if(r){const t=Ft(Ot(e,["mdia","minf","stbl","stsd"])[0]);i[s]={timescale:n,type:r},i[r]=k({timescale:n,id:s},t)}}}}}return Ot(t,["moov","mvex","trex"]).forEach((t=>{const s=Ct(t,4),e=i[s];e&&(e.default={duration:Ct(t,12),flags:Ct(t,20)})})),i}function Ft(t){const i=t.subarray(8),s=i.subarray(86),e=xt(i.subarray(4,8));let n=e;const r="enca"===e||"encv"===e;if(r){const t=Ot(i,[e])[0];Ot(t.subarray("enca"===e?28:78),["sinf"]).forEach((t=>{const i=Ot(t,["schm"])[0];if(i){const s=xt(i.subarray(4,8));if("cbcs"===s||"cenc"===s){const i=Ot(t,["frma"])[0];i&&(n=xt(i))}}}))}switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Ot(s,["avcC"])[0];n+="."+jt(t[1])+jt(t[2])+jt(t[3]);break}case"mp4a":{const t=Ot(i,[e])[0],s=Ot(t.subarray(28),["esds"])[0];if(s&&s.length>12){let t=4;if(3!==s[t++])break;t=Bt(s,t),t+=2;const i=s[t++];if(128&i&&(t+=2),64&i&&(t+=s[t++]),4!==s[t++])break;t=Bt(s,t);const e=s[t++];if(64!==e)break;if(n+="."+jt(e),t+=12,5!==s[t++])break;t=Bt(s,t);const r=s[t++];let h=(248&r)>>3;31===h&&(h+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+h}break}case"hvc1":case"hev1":{const t=Ot(s,["hvcC"])[0],i=t[1],e=["","A","B","C"][i>>6],r=31&i,h=Ct(t,2),o=(32&i)>>5?"H":"L",a=t[12],l=t.subarray(6,12);n+="."+e+r,n+="."+h.toString(16).toUpperCase(),n+="."+o+a;let c="";for(let t=l.length;t--;){const i=l[t];(i||c)&&(c="."+i.toString(16).toUpperCase()+c)}n+=c;break}case"dvh1":case"dvhe":{const t=Ot(s,["dvcC"])[0],i=t[2]<<5&32|t[3]>>3&31;n+="."+_t(t[2]>>1&127)+"."+_t(i);break}case"vp09":{const t=Ot(s,["vpcC"])[0],i=t[5],e=t[6]>>4&15;n+="."+_t(t[4])+"."+_t(i)+"."+_t(e);break}case"av01":{const t=Ot(s,["av1C"])[0],i=t[1]>>>5,e=t[2]>>>7?"H":"M",r=(64&t[2])>>6,h=2===i&&r?(32&t[2])>>5?12:10:r?10:8,o=(16&t[2])>>4,a=(8&t[2])>>3,l=(4&t[2])>>2,c=3&t[2],u=1,d=1,f=1,v=0;n+="."+i+"."+_t(31&t[1])+e+"."+_t(h)+"."+o+"."+a+l+c+"."+_t(u)+"."+_t(d)+"."+_t(f)+"."+v;break}}return{codec:n,encrypted:r}}function Bt(t,i){const s=i+5;for(;128&t[i++]&&i<s;);return i}function jt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function _t(t){return(t<10?"0":"")+t}function Gt(t){const i=Ot(t,["schm"])[0];if(i){const s=xt(i.subarray(4,8));if("cbcs"===s||"cenc"===s)return Ot(t,["schi","tenc"])[0]}return null}function Ht(t){const i=Ct(t,0);let s=8;1&i&&(s+=4),4&i&&(s+=4);let e=0;const n=Ct(t,4);for(let r=0;r<n;r++)256&i&&(e+=Ct(t,s),s+=4),512&i&&(s+=4),1024&i&&(s+=4),2048&i&&(s+=4);return e}function Kt(t,i){const s=new Uint8Array(t.length+i.length);return s.set(t),s.set(i,t.length),s}function Vt(t,i){const s=[],e=i.samples,n=i.timescale,r=i.id;let h=!1;return Ot(e,["moof"]).map((o=>{const a=o.byteOffset-8;Ot(o,["traf"]).map((o=>{const l=Ot(o,["tfdt"]).map((t=>{const i=t[0];let s=Ct(t,4);return 1===i&&(s*=Math.pow(2,32),s+=Ct(t,8)),s/n}))[0];return void 0!==l&&(t=l),Ot(o,["tfhd"]).map((l=>{const c=Ct(l,4),u=16777215&Ct(l,0);let d=0;const f=!!(16&u);let v=0;const p=!!(32&u);let g=8;c===r&&(!!(1&u)&&(g+=8),!!(2&u)&&(g+=4),!!(8&u)&&(d=Ct(l,g),g+=4),f&&(v=Ct(l,g),g+=4),p&&(g+=4),"video"===i.type&&(h=function(t){if(!t)return!1;const i=t.indexOf("."),s=i<0?t:t.substring(0,i);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(i.codec)),Ot(o,["trun"]).map((r=>{const o=r[0],l=16777215&Ct(r,0),c=!!(1&l);let u=0;const f=!!(4&l),p=!!(256&l);let g=0;const m=!!(512&l);let y=0;const w=!!(1024&l),b=!!(2048&l);let k=0;const S=Ct(r,4);let T=8;c&&(u=Ct(r,T),T+=4),f&&(T+=4);let $=u+a;for(let a=0;a<S;a++){if(p?(g=Ct(r,T),T+=4):g=d,m?(y=Ct(r,T),T+=4):y=v,w&&(T+=4),b&&(k=0===o?Ct(r,T):Rt(r,T),T+=4),i.type===j){let i=0;for(;i<y;){const r=Ct(e,$);$+=4,zt(h,e[$])&&Wt(e.subarray($,$+r),h?2:1,t+k/n,s),$+=r,i+=r+4}}t+=g/n}})))}))}))})),s}function zt(t,i){if(t){const t=i>>1&63;return 39===t||40===t}return 6==(31&i)}function Wt(t,i,s,e){const n=Xt(t);let r=0;r+=i;let h=0,o=0,a=0;for(;r<n.length;){h=0;do{if(r>=n.length)break;a=n[r++],h+=a}while(255===a);o=0;do{if(r>=n.length)break;a=n[r++],o+=a}while(255===a);const t=n.length-r;let i=r;if(o<t)r+=o;else if(o>t){I.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===h){if(181===n[i++]){const t=Dt(n,i);if(i+=2,49===t){const t=Ct(n,i);if(i+=4,1195456820===t){const t=n[i++];if(3===t){const r=n[i++],o=64&r,a=o?2+3*(31&r):0,l=new Uint8Array(a);if(o){l[0]=r;for(let t=1;t<a;t++)l[t]=n[i++]}e.push({type:t,payloadType:h,pts:s,bytes:l})}}}}}else if(5===h&&o>16){const t=[];for(let s=0;s<16;s++){const e=n[i++].toString(16);t.push(1==e.length?"0"+e:e),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const r=o-16,a=new Uint8Array(r);for(let t=0;t<r;t++)a[t]=n[i++];e.push({payloadType:h,pts:s,uuid:t.join(""),userData:St(a),userDataBytes:a})}}}function Xt(t){const i=t.byteLength,s=[];let e=1;for(;e<i-2;)0===t[e]&&0===t[e+1]&&3===t[e+2]?(s.push(e+2),e+=2):e++;if(0===s.length)return t;const n=i-s.length,r=new Uint8Array(n);let h=0;for(e=0;e<n;h++,e++)h===s[0]&&(h++,s.shift()),r[e]=t[h];return r}function qt(t){const i=t.getUint32(0),s=t.byteOffset,e=t.byteLength;if(e<i)return{offset:s,size:e};if(1886614376!==t.getUint32(4))return{offset:s,size:i};const n=t.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:s,size:i};const r=t.buffer,h=Et(new Uint8Array(r,s+12,16)),o=t.getUint32(28);let a=null,l=null;if(0===n){if(i-32<o||o<22)return{offset:s,size:i};l=new Uint8Array(r,s+32,o)}else if(1===n){if(!o||e<s+32+16*o+16)return{offset:s,size:i};a=[];for(let t=0;t<o;t++)a.push(new Uint8Array(r,s+32+16*t,16))}return{version:n,systemId:h,kids:a,data:l,offset:s,size:i}}let Yt={};class Jt{static clearKeyUriToKeyIdMap(){Yt={}}constructor(t,i,s,e=[1],n=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=i,this.keyFormat=s,this.keyFormatVersions=e,this.iv=n,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case J:case Z:case Q:case Y:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||I.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const i=function(t){const i=new Uint8Array(16);for(let s=12;s<16;s++)i[s]=t>>8*(15-s)&255;return i}(t);return new Jt(this.method,this.uri,"identity",this.keyFormatVersions,i)}const i=function(t){const i=t.split(":");let s=null;if("data"===i[0]&&2===i.length){const t=i[1].split(";"),e=t[t.length-1].split(",");if(2===e.length){const i=e[1];"base64"===e[0]?(t.splice(-1,1),s=z(i)):s=function(t){const i=W(t).subarray(0,16),s=new Uint8Array(16);return s.set(i,16-i.length),s}(i)}}return s}(this.uri);if(i)switch(this.keyFormat){case Z:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case Q:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(t,i,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let e,n,r;if(i){e=1,n=new Uint8Array(16*i.length);for(let t=0;t<i.length;t++){const s=i[t];if(16!==s.byteLength)throw new RangeError("Invalid key");n.set(s,16*t)}}else e=0,n=new Uint8Array;e>0?(r=new Uint8Array(4),i.length>0&&new DataView(r.buffer).setUint32(0,i.length,!1)):r=new Uint8Array;const h=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(h.buffer).setUint32(0,s.byteLength,!1),function(t,...i){const s=i.length;let e=8,n=s;for(;n--;)e+=i[n].byteLength;const r=new Uint8Array(e);for(r[0]=e>>24&255,r[1]=e>>16&255,r[2]=e>>8&255,r[3]=255&e,r.set(t,4),n=0,e=8;n<s;n++)r.set(i[n],e),e+=i[n].byteLength;return r}([112,115,115,104],new Uint8Array([e,0,0,0]),t,r,n,h,s||new Uint8Array)}(t,null,i),this.keyId=ht(i);break}default:{let t=i.subarray(0,16);if(16!==t.length){const i=new Uint8Array(16);i.set(t,16-t.length),t=i}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=Yt[this.uri];if(!t){const i=Object.keys(Yt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16),new DataView(t.buffer,12,4).setUint32(0,i),Yt[this.uri]=t}this.keyId=t}return this}}const Qt=/\{\$([a-zA-Z0-9-_]+)\}/g;function Zt(t){return Qt.test(t)}function ti(t,i,s){if(null!==t.variableList||t.hasVariableRefs)for(let e=s.length;e--;){const n=s[e],r=i[n];r&&(i[n]=ii(t,r))}}function ii(t,i){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return i.replace(Qt,(i=>{const e=i.substring(2,i.length-1),n=null==s?void 0:s[e];return void 0===n?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${e}"`)),i):n}))}return i}function si(t,i,s){let e,n,r=t.variableList;if(r||(t.variableList=r={}),"QUERYPARAM"in i){e=i.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(e))throw new Error(`"${e}" does not match any query parameter in URI: "${s}"`);n=t.get(e)}catch(i){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${i.message}`))}}else e=i.NAME,n=i.VALUE;e in r?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${e}"`)):r[e]=n||""}function ei(t,i,s){const e=i.IMPORT;if(s&&e in s){let i=t.variableList;i||(t.variableList=i={}),i[e]=s[e]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${e}"`))}function ni(t=!0){if("undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const ri={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 hi(t,i,s=!0){return!t.split(",").some((t=>!oi(t,i,s)))}function oi(t,i,s=!0){var e;const n=ni(s);return null!=(e=null==n?void 0:n.isTypeSupported(ai(t,i)))&&e}function ai(t,i){return`${i}/mp4;codecs="${t}"`}function li(t){if(t){const i=t.substring(0,4);return ri.video[i]}return 2}function ci(t){return t.split(",").reduce(((t,i)=>{const s=ri.video[i];return s?(2*s+t)/(t?3:2):(ri.audio[i]+t)/(t?2:1)}),0)}const ui={},di=/flac|opus/i;function fi(t,i=!0){return t.replace(di,(t=>function(t,i=!0){if(ui[t])return ui[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let e=0;e<s.length;e++)if(oi(s[e],"audio",i))return ui[t]=s[e],s[e];return t}(t.toLowerCase(),i)))}function vi(t,i){return t&&"mp4a"!==t?t:i?i.split(",")[0]:i}const pi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,gi=/#EXT-X-MEDIA:(.*)/g,mi=/^#EXT(?:INF|-X-TARGETDURATION):/m,yi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),wi=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class bi{static findGroup(t,i){for(let s=0;s<t.length;s++){const e=t[s];if(e.id===i)return e}}static resolve(t,i){return w.buildAbsoluteURL(i,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return mi.test(t)}static parseMasterPlaylist(t,i){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Zt(t)},e=[];let n;for(pi.lastIndex=0;null!=(n=pi.exec(t));)if(n[1]){var r;const t=new O(n[1]);ti(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const h=ii(s,n[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:bi.resolve(h,i)},a=t.decimalResolution("RESOLUTION");a&&(o.width=a.width,o.height=a.height),Ti(t.CODECS,o),null!=(r=o.unknownCodecs)&&r.length||e.push(o),s.levels.push(o)}else if(n[3]){const t=n[4];switch(n[3]){case"SESSION-DATA":{const i=new O(t);ti(s,i,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=i["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=i);break}case"SESSION-KEY":{const e=ki(t,i,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):I.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${t}"`);break}case"DEFINE":{const e=new O(t);ti(s,e,["NAME","VALUE","QUERYPARAM"]),si(s,e,i)}break;case"CONTENT-STEERING":{const e=new O(t);ti(s,e,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:bi.resolve(e["SERVER-URI"],i),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Si(t)}}return s.levels=e.length>0&&e.length<s.levels.length?e:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,i,s){let e;const n={},r=s.levels,h={AUDIO:r.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:r.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(gi.lastIndex=0;null!==(e=gi.exec(t));){const t=new O(e[1]),r=t.TYPE;if(r){const e=h[r],a=n[r]||[];n[r]=a,ti(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const l=t.LANGUAGE,c=t["ASSOC-LANGUAGE"],u=t.CHANNELS,d=t.CHARACTERISTICS,f=t["INSTREAM-ID"],v={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:r,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?bi.resolve(t.URI,i):""};if(c&&(v.assocLang=c),u&&(v.channels=u),d&&(v.characteristics=d),f&&(v.instreamId=f),null!=e&&e.length){const t=bi.findGroup(e,v.groupId)||e[0];$i(v,t,"audioCodec"),$i(v,t,"textCodec")}a.push(v)}}return n}static parseLevelPlaylist(t,i,s,e,n,r){const h=new V(i),o=h.fragments;let a,l,c,u=null,d=0,f=0,v=0,p=0,g=null,m=new H(e,i),y=-1,w=!1,b=null;for(yi.lastIndex=0,h.m3u8=t,h.hasVariableRefs=Zt(t);null!==(a=yi.exec(t));){w&&(w=!1,m=new H(e,i),m.start=v,m.sn=d,m.cc=p,m.level=s,u&&(m.initSegment=u,m.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,b&&(m.setByteRange(b),b=null)));const t=a[1];if(t){m.duration=parseFloat(t);const i=(" "+a[2]).slice(1);m.title=i||null,m.tagList.push(i?["INF",t,i]:["INF",t])}else if(a[3]){if(T(m.duration)){m.start=v,c&&Mi(m,c,h),m.sn=d,m.level=s,m.cc=p,o.push(m);const t=(" "+a[3]).slice(1);m.relurl=ii(h,t),Ei(m,g),g=m,v+=m.duration,d++,f=0,w=!0}}else if(a[4]){const t=(" "+a[4]).slice(1);g?m.setByteRange(t,g):m.setByteRange(t)}else if(a[5])m.rawProgramDateTime=(" "+a[5]).slice(1),m.tagList.push(["PROGRAM-DATE-TIME",m.rawProgramDateTime]),-1===y&&(y=o.length);else{if(a=a[0].match(wi),!a){I.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<a.length&&void 0===a[l];l++);const t=(" "+a[l]).slice(1),n=(" "+a[l+1]).slice(1),v=a[l+2]?(" "+a[l+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":h.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":d=h.startSN=parseInt(n);break;case"SKIP":{const t=new O(n);ti(h,t,["RECENTLY-REMOVED-DATERANGES"]);const i=t.decimalInteger("SKIPPED-SEGMENTS");if(T(i)){h.skippedSegments=i;for(let t=i;t--;)o.unshift(null);d+=i}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(h.recentlyRemovedDateranges=s.split("\t"));break}case"TARGETDURATION":h.targetduration=Math.max(parseInt(n),1);break;case"VERSION":h.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":h.live=!1;break;case"#":(n||v)&&m.tagList.push(v?[n,v]:[n]);break;case"DISCONTINUITY":p++,m.tagList.push(["DIS"]);break;case"GAP":m.gap=!0,m.tagList.push([t]);break;case"BITRATE":m.tagList.push([t,n]);break;case"DATERANGE":{const t=new O(n);ti(h,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),ti(h,t,t.clientAttrs);const i=new U(t,h.dateRanges[t.ID]);i.isValid||h.skippedSegments?h.dateRanges[i.id]=i:I.warn(`Ignoring invalid DATERANGE tag: "${n}"`),m.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new O(n);ti(h,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?ei(h,t,r):si(h,t,i)}break;case"DISCONTINUITY-SEQUENCE":p=parseInt(n);break;case"KEY":{const t=ki(n,i,h);if(t.isSupported()){if("NONE"===t.method){c=void 0;break}c||(c={}),c[t.keyFormat]&&(c=S({},c)),c[t.keyFormat]=t}else I.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${n}"`);break}case"START":h.startTimeOffset=Si(n);break;case"MAP":{const t=new O(n);if(ti(h,t,["BYTERANGE","URI"]),m.duration){const n=new H(e,i);Ai(n,t,s,c),u=n,m.initSegment=u,u.rawProgramDateTime&&!m.rawProgramDateTime&&(m.rawProgramDateTime=u.rawProgramDateTime)}else{const i=m.byteRangeEndOffset;if(i){const t=m.byteRangeStartOffset;b=`${i-t}@${t}`}else b=null;Ai(m,t,s,c),u=m,w=!0}break}case"SERVER-CONTROL":{const t=new O(n);h.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),h.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new O(n);h.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=h.partList;t||(t=h.partList=[]);const s=f>0?t[t.length-1]:void 0,e=f++,r=new O(n);ti(h,r,["BYTERANGE","URI"]);const o=new K(r,m,i,e,s);t.push(o),m.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new O(n);ti(h,t,["URI"]),h.preloadHint=t;break}case"RENDITION-REPORT":{const t=new O(n);ti(h,t,["URI"]),h.renditionReports=h.renditionReports||[],h.renditionReports.push(t);break}default:I.warn(`line parsed but not handled: ${a}`)}}}g&&!g.relurl?(o.pop(),v-=g.duration,h.partList&&(h.fragmentHint=g)):h.partList&&(Ei(m,g),m.cc=p,h.fragmentHint=m,c&&Mi(m,c,h));const k=o.length,$=o[0],E=o[k-1];if(v+=h.skippedSegments*h.targetduration,v>0&&k&&E){h.averagetargetduration=v/k;const t=E.sn;h.endSN="initSegment"!==t?t:0,h.live||(E.endList=!0),$&&(h.startCC=$.cc)}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(v+=h.fragmentHint.duration),h.totalduration=v,h.endCC=p,y>0&&function(t,i){let s=t[i];for(let e=i;e--;){const i=t[e];if(!i)return;i.programDateTime=s.programDateTime-1e3*i.duration,s=i}}(o,y),h}}function ki(t,i,s){var e,n;const r=new O(t);ti(s,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const h=null!=(e=r.METHOD)?e:"",o=r.URI,a=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,c=null!=(n=r.KEYFORMAT)?n:"identity";o&&r.IV&&!a&&I.error(`Invalid IV: ${r.IV}`);const u=o?bi.resolve(o,i):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Jt(h,u,c,d,a)}function Si(t){const i=new O(t).decimalFloatingPoint("TIME-OFFSET");return T(i)?i:null}function Ti(t,i){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const e=s.filter((i=>function(t,i){const s=ri[i];return!!s&&!!s[t.slice(0,4)]}(i,t)));e.length&&(i[`${t}Codec`]=e.join(","),s=s.filter((t=>-1===e.indexOf(t))))})),i.unknownCodecs=s}function $i(t,i,s){const e=i[s];e&&(t[s]=e)}function Ei(t,i){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=i&&i.programDateTime&&(t.programDateTime=i.endProgramDateTime),T(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Ai(t,i,s,e){t.relurl=i.URI,i.BYTERANGE&&t.setByteRange(i.BYTERANGE),t.level=s,t.sn="initSegment",e&&(t.levelkeys=e),t.initSegment=null}function Mi(t,i,s){t.levelkeys=i;const{encryptedFragments:e}=s;e.length&&e[e.length-1].levelkeys===i||!Object.keys(i).some((t=>i[t].isCommonEncryption))||e.push(t)}var Li="manifest",xi="level",Di="audioTrack",Ci="subtitleTrack",Ii="main",Ri="audio",Pi="subtitle";function Oi(t){const{type:i}=t;switch(i){case Di:return Ri;case Ci:return Pi;default:return Ii}}function Ni(t,i){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=i.url),s}class Ui{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(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(A.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.LEVEL_LOADING,this.onLevelLoading,this),t.off(A.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(A.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const i=this.hls.config,s=new(i.pLoader||i.loader)(i);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const i=this.loaders[t];i&&i.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,i){const{url:s}=i;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Li,url:s,deliveryDirectives:null})}onLevelLoading(t,i){const{id:s,level:e,pathwayId:n,url:r,deliveryDirectives:h}=i;this.load({id:s,level:e,pathwayId:n,responseType:"text",type:xi,url:r,deliveryDirectives:h})}onAudioTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:Di,url:n,deliveryDirectives:r})}onSubtitleTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:Ci,url:n,deliveryDirectives:r})}load(t){var i;const s=this.hls.config;let e,n=this.getInternalLoader(t);if(n){const i=n.context;if(i&&i.url===t.url&&i.level===t.level)return void I.trace("[playlist-loader]: playlist request ongoing");I.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(e=t.type===Li?s.manifestLoadPolicy.default:S({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),T(null==(i=t.deliveryDirectives)?void 0:i.part)){let i;if(t.type===xi&&null!==t.level?i=this.hls.levels[t.level].details:t.type===Di&&null!==t.id?i=this.hls.audioTracks[t.id].details:t.type===Ci&&null!==t.id&&(i=this.hls.subtitleTracks[t.id].details),i){const t=i.partTarget,s=i.targetduration;if(t&&s){const i=1e3*Math.max(3*t,.8*s);e=S({},e,{maxTimeToFirstByteMs:Math.min(i,e.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(i,e.maxTimeToFirstByteMs)})}}}const r=e.errorRetry||e.timeoutRetry||{},h={onSuccess:(t,i,s,e)=>{const n=this.getInternalLoader(s);this.resetInternalLoader(s.type);const r=t.data;0===r.indexOf("#EXTM3U")?(i.parsing.start=performance.now(),bi.isMediaPlaylist(r)?this.handleTrackOrLevelPlaylist(t,i,s,e||null,n):this.handleMasterPlaylist(t,i,s,e)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),e||null,i)},onError:(t,i,s,e)=>{this.handleNetworkError(i,s,!1,t,e)},onTimeout:(t,i,s)=>{this.handleNetworkError(i,s,!0,void 0,t)}};n.load(t,{loadPolicy:e,timeout:e.maxLoadTimeMs,maxRetry:r.maxNumRetry||0,retryDelay:r.retryDelayMs||0,maxRetryDelay:r.maxRetryDelayMs||0},h)}handleMasterPlaylist(t,i,s,e){const n=this.hls,r=t.data,h=Ni(t,s),o=bi.parseMasterPlaylist(r,h);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,e,i);const{contentSteering:a,levels:l,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f}=o;this.variableList=f;const{AUDIO:v=[],SUBTITLES:p,"CLOSED-CAPTIONS":g}=bi.parseMasterPlaylistMedia(r,h,o);v.length&&(v.some((t=>!t.url))||!l[0].audioCodec||l[0].attrs.AUDIO||(I.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new O({}),bitrate:0,url:""}))),n.trigger(A.MANIFEST_LOADED,{levels:l,audioTracks:v,subtitles:p,captions:g,contentSteering:a,url:h,stats:i,networkDetails:e,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,i,s,e,n){const r=this.hls,{id:h,level:o,type:a}=s,l=Ni(t,s),c=T(o)?o:T(h)?h:0,u=Oi(s),d=bi.parseLevelPlaylist(t.data,l,c,u,0,this.variableList);if(a===Li){const t={attrs:new O({}),bitrate:0,details:d,name:"",url:l};r.trigger(A.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:l,stats:i,networkDetails:e,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=d,this.handlePlaylistLoaded(d,t,i,s,e,n)}handleManifestParsingError(t,i,s,e,n){this.hls.trigger(A.ERROR,{type:M.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:i.type===Li,url:t.url,err:s,error:s,reason:s.message,response:t,context:i,networkDetails:e,stats:n})}handleNetworkError(t,i,s=!1,e,n){let r=`A network ${s?"timeout":"error"+(e?" (status "+e.code+")":"")} occurred while loading ${t.type}`;t.type===xi?r+=`: ${t.level} id: ${t.id}`:t.type!==Di&&t.type!==Ci||(r+=` id: ${t.id} group-id: "${t.groupId}"`);const h=new Error(r);I.warn(`[playlist-loader]: ${r}`);let o=L.UNKNOWN,a=!1;const l=this.getInternalLoader(t);switch(t.type){case Li:o=s?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,a=!0;break;case xi:o=s?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,a=!1;break;case Di:o=s?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,a=!1;break;case Ci:o=s?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,a=!1}l&&this.resetInternalLoader(t.type);const c={type:M.NETWORK_ERROR,details:o,fatal:a,url:t.url,loader:l,context:t,error:h,networkDetails:i,stats:n};e&&(c.response=k({url:(null==i?void 0:i.url)||t.url,data:void 0},e)),this.hls.trigger(A.ERROR,c)}handlePlaylistLoaded(t,i,s,e,n,r){const h=this.hls,{type:o,level:a,id:l,groupId:c,deliveryDirectives:u}=e,d=Ni(i,e),f=Oi(e),v="number"==typeof e.level&&f===Ii?a:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void h.trigger(A.ERROR,{type:M.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:t,reason:t.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const p=t.playlistParsingError;if(p)h.trigger(A.ERROR,{type:M.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:p,reason:p.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s});else switch(t.live&&r&&(r.getCacheAge&&(t.ageHeader=r.getCacheAge()||0),r.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Li:case xi:h.trigger(A.LEVEL_LOADED,{details:t,level:v||0,id:l||0,stats:s,networkDetails:n,deliveryDirectives:u});break;case Di:h.trigger(A.AUDIO_TRACK_LOADED,{details:t,id:l||0,groupId:c||"",stats:s,networkDetails:n,deliveryDirectives:u});break;case Ci:h.trigger(A.SUBTITLE_TRACK_LOADED,{details:t,id:l||0,groupId:c||"",stats:s,networkDetails:n,deliveryDirectives:u})}}}function Fi(t,i){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,i.dispatchEvent(s)}function Bi(t,i){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(i.id))try{if(t.addCue(i),!t.cues.getCueById(i.id))throw new Error(`addCue is failed for: ${i}`)}catch(s){I.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(i.startTime,i.endTime,i.text);s.id=i.id,t.addCue(s)}catch(t){I.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function ji(t){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function _i(t,i,s,e){const n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0){const n=function(t,i,s){const e=[],n=function(t,i){if(i<t[0].startTime)return 0;const s=t.length-1;if(i>t[s].endTime)return-1;let e=0,n=s;for(;e<=n;){const r=Math.floor((n+e)/2);if(i<t[r].startTime)n=r-1;else{if(!(i>t[r].startTime&&e<s))return r;e=r+1}}return t[e].startTime-i<i-t[n].startTime?e:n}(t,i);if(n>-1)for(let r=n,h=t.length;r<h;r++){const n=t[r];if(n.startTime>=i&&n.endTime<=s)e.push(n);else if(n.startTime>s)return e}return e}(t.cues,i,s);for(let i=0;i<n.length;i++)e&&!e(n[i])||t.removeCue(n[i])}"disabled"===n&&(t.mode=n)}function Gi(t){const i=[];for(let s=0;s<t.length;s++){const e=t[s];"subtitles"!==e.kind&&"captions"!==e.kind||!e.label||i.push(t[s])}return i}var Hi="org.id3",Ki="https://aomedia.org/emsg/ID3";function Vi(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function zi(t,i,s,e,n){let r=new t(i,s,"");try{r.value=e,n&&(r.type=n)}catch(h){r=new t(i,s,JSON.stringify(n?k({type:n},e):e))}return r}const Wi=(()=>{const t=Vi();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Xi(t,i){return t.getTime()/1e3-i}class qi{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(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,i){this.media=i.media}onMediaDetaching(){this.id3Track&&(ji(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const i=this.getID3Track(t.textTracks);return i.mode="hidden",i}getID3Track(t){if(this.media){for(let i=0;i<t.length;i++){const s=t[i];if("metadata"===s.kind&&"id3"===s.label)return Fi(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,i){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:e}}}=this;if(!s&&!e)return;const{samples:n}=i;this.id3Track||(this.id3Track=this.createTrack(this.media));const r=Vi();if(r)for(let t=0;t<n.length;t++){const i=n[t].type;if(i===Ki&&!s||!e)continue;const h=gt(n[t].data);if(h){const s=n[t].pts;let e=s+n[t].duration;e>Wi&&(e=Wi),e-s<=0&&(e=s+.25);for(let t=0;t<h.length;t++){const n=h[t];if(!vt(n)){this.updateId3CueEnds(s,i);const t=zi(r,s,e,n,i);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,i){var s;const e=null==(s=this.id3Track)?void 0:s.cues;if(e)for(let s=e.length;s--;){const n=e[s];n.type===i&&n.startTime<t&&n.endTime===Wi&&(n.endTime=t)}}onBufferFlushing(t,{startOffset:i,endOffset:s,type:e}){const{id3Track:n,hls:r}=this;if(!r)return;const{config:{enableEmsgMetadataCues:h,enableID3MetadataCues:o}}=r;if(n&&(h||o)){let t;t="audio"===e?t=>t.type===Hi&&o:"video"===e?t=>t.type===Ki&&h:t=>t.type===Hi&&o||t.type===Ki&&h,_i(n,i,s,t)}}onLevelUpdated(t,{details:i}){if(!this.media||!i.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:e}=this,{dateRanges:n}=i,r=Object.keys(n);if(e){const t=Object.keys(s).filter((t=>!r.includes(t)));for(let i=t.length;i--;){const n=t[i];Object.keys(s[n].cues).forEach((t=>{e.removeCue(s[n].cues[t])})),delete s[n]}}const h=i.fragments[i.fragments.length-1];if(0===r.length||!T(null==h?void 0:h.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=h.programDateTime/1e3-h.start,a=Vi();for(let t=0;t<r.length;t++){const i=r[t],e=n[i],h=Xi(e.startDate,o),c=s[i],u=(null==c?void 0:c.cues)||{};let d=(null==c?void 0:c.durationKnown)||!1,f=Wi;const v=e.endDate;if(v)f=Xi(v,o),d=!0;else if(e.endOnNext&&!d){const t=r.reduce(((t,i)=>{if(i!==e.id){const s=n[i];if(s.class===e.class&&s.startDate>e.startDate&&(!t||e.startDate<t.startDate))return s}return t}),null);t&&(f=Xi(t.startDate,o),d=!0)}const p=Object.keys(e.attr);for(let t=0;t<p.length;t++){const s=p[t];if("ID"===(l=s)||"CLASS"===l||"START-DATE"===l||"DURATION"===l||"END-DATE"===l||"END-ON-NEXT"===l)continue;const n=u[s];if(n)d&&!c.durationKnown&&(n.endTime=f);else if(a){let t=e.attr[s];N(s)&&(t=Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const n=zi(a,h,f,{key:s,data:t},"com.apple.quicktime.HLS");n&&(n.id=i,this.id3Track.addCue(n),u[s]=n)}}s[i]={cues:u,dateRange:e,durationKnown:d}}var l}}class Yi{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:i}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:i,partHoldBack:s,targetduration:e}=t,{liveSyncDuration:n,liveSyncDurationCount:r,lowLatencyMode:h}=this.config,o=this.hls.userConfig;let a=h&&s||i;return(o.liveSyncDuration||o.liveSyncDurationCount||0===a)&&(a=void 0!==n?n:r*e),a+Math.min(1*this.stallCount,e)}get liveSyncPosition(){const t=this.estimateLiveEdge(),i=this.targetLatency,s=this.levelDetails;if(null===t||null===i||null===s)return null;const e=s.edge,n=e-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(e-s.totalduration,t-i-this.edgeStalled),n)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;return null===t?0:Math.max(t.age-3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration),0)}get forwardBufferLength(){const{media:t,levelDetails:i}=this;if(!t||!i)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):i.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(A.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(A.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(A.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(A.ERROR,this.onError,this)}onMediaAttached(t,i){this.media=i.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:i}){this.levelDetails=i,i.advanced&&this.timeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,i){var s;i.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&I.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:i}=this;if(!t||!i)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:e,maxLiveSyncPlaybackRate:n}=this.config;if(!e||1===n||!i.live)return;const r=this.targetLatency;if(null===r)return;const h=s-r;if(h<Math.min(this.maxLatency,r+i.targetduration)&&h>.05&&this.forwardBufferLength>1){const i=Math.min(2,Math.max(1,n)),s=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20;t.playbackRate=Math.min(i,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 Ji=["NONE","TYPE-0","TYPE-1",null],Qi=["SDR","PQ","HLG"];function Zi(t){const{canSkipUntil:i,canSkipDateRanges:s,age:e}=t;return i&&e<i/2?s?"v2":"YES":""}class ts{constructor(t,i,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=i,this.skip=s}addDirectives(t){const i=new self.URL(t);return void 0!==this.msn&&i.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&i.searchParams.set("_HLS_part",this.part.toString()),this.skip&&i.searchParams.set("_HLS_skip",this.skip),i.href}}class is{constructor(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!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,i){if(i)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(i)&&t.push(i)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(i)&&t.push(i)}}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,i){return!(!i||!t)&&-1!==t.indexOf(i)}function es(t,i){const s=i.startPTS;if(T(s)){let e,n=0;i.sn>t.sn?(n=s-t.start,e=t):(n=t.start-s,e=i),e.duration!==n&&(e.duration=n)}else i.start=i.sn>t.sn?t.cc===i.cc&&t.minEndPTS?t.start+(t.minEndPTS-t.start):t.start+t.duration:Math.max(t.start-i.duration,0)}function ns(t,i,s,e,n,r){e-s<=0&&(I.warn("Fragment should have a positive duration",i),e=s+i.duration,r=n+i.duration);let h=s,o=e;const a=i.startPTS,l=i.endPTS;if(T(a)){const t=Math.abs(a-s);i.deltaPTS=T(i.deltaPTS)?Math.max(t,i.deltaPTS):t,h=Math.max(s,a),s=Math.min(s,a),n=Math.min(n,i.startDTS),o=Math.min(e,l),e=Math.max(e,l),r=Math.max(r,i.endDTS)}const c=s-i.start;0!==i.start&&(i.start=s),i.duration=e-i.start,i.startPTS=s,i.maxStartPTS=h,i.startDTS=n,i.endPTS=e,i.minEndPTS=o,i.endDTS=r;const u=i.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let d;const f=u-t.startSN,v=t.fragments;for(v[f]=i,d=f;d>0;d--)es(v[d],v[d-1]);for(d=f;d<v.length-1;d++)es(v[d],v[d+1]);return t.fragmentHint&&es(v[v.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function rs(t,i){const s=i.startSN+i.skippedSegments-t.startSN,e=t.fragments;s<0||s>=e.length||hs(i,e[s].start)}function hs(t,i){if(i){const s=t.fragments;for(let e=t.skippedSegments;e<s.length;e++)s[e].start+=i;t.fragmentHint&&(t.fragmentHint.start+=i)}}function os(t,i,s){var e;return null!=t&&t.details?as(null==(e=t.details)?void 0:e.partList,i,s):null}function as(t,i,s){if(t)for(let e=t.length;e--;){const n=t[e];if(n.index===s&&n.fragment.sn===i)return n}return null}function ls(t){t.forEach(((t,i)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach((t=>{t.level=i}))}))}function cs(t){switch(t.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function us(t,i){const s=cs(i);return t.default[(s?"timeout":"error")+"Retry"]}function ds(t,i){const s="linear"===t.backoff?1:Math.pow(2,i);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function fs(t){return k(k({},t),{errorRetry:null,timeoutRetry:null})}function vs(t,i,s,e){if(!t)return!1;const n=i<t.maxNumRetry&&(0===(r=null==e?void 0:e.code)&&!1===navigator.onLine||!!r&&(r<400||r>499)||!!s);var r;return t.shouldRetry?t.shouldRetry(t,i,s,e,n):n}const ps=function(t,i){let s=0,e=t.length-1,n=null,r=null;for(;s<=e;){n=(s+e)/2|0,r=t[n];const h=i(r);if(h>0)s=n+1;else{if(!(h<0))return r;e=n-1}}return null};function gs(t,i,s=0,e=0,n=.005){let r=null;if(t){r=i[t.sn-i[0].sn+1]||null;const e=t.endDTS-s;e>0&&e<15e-7&&(s+=15e-7)}else 0===s&&0===i[0].start&&(r=i[0]);if(r&&((!t||t.level===r.level)&&0===ms(s,e,r)||function(t,i,s){if(i&&0===i.start&&i.level<t.level&&(i.endPTS||0)>0){const e=i.tagList.reduce(((t,i)=>("INF"===i[0]&&(t+=parseFloat(i[1])),t)),s);return t.start<=e}return!1}(r,t,Math.min(n,e))))return r;const h=ps(i,ms.bind(null,s,e));return!h||h===t&&r?r:h}function ms(t=0,i=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const e=Math.min(i,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-e<=t?1:s.start-e>t&&s.start?-1:0}function ys(t,i,s){const e=1e3*Math.min(i,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-e>t}class ws{constructor(t,i){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=I.log.bind(I,`${i}:`),this.warn=I.warn.bind(I,`${i}:`),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,i,s){const e=null==i?void 0:i.renditionReports;if(e){let n=-1;for(let s=0;s<e.length;s++){const r=e[s];let h;try{h=new self.URL(r.URI,i.url).href}catch(t){I.warn(`Could not construct new URL for Rendition Report: ${t}`),h=r.URI||""}if(h===t){n=s;break}h===t.substring(0,h.length)&&(n=s)}if(-1!==n){const t=e[n],r=parseInt(t["LAST-MSN"])||(null==i?void 0:i.lastPartSn);let h=parseInt(t["LAST-PART"])||(null==i?void 0:i.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(i.age-i.partTarget,i.targetduration);h>=0&&t>i.partTarget&&(h+=1)}const o=s&&Zi(s);return new ts(r,h>=0?h: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,i,s){const{details:e,stats:n}=i,r=self.performance.now(),h=n.loading.first?Math.max(0,r-n.loading.first):0;if(e.advancedDateTime=Date.now()-h,e.live||null!=s&&s.live){if(e.reloaded(s),s&&this.log(`live playlist ${t} ${e.advanced?"REFRESHED "+e.lastPartSn+"-"+e.lastPartIndex:e.updated?"UPDATED":"MISSED"}`),s&&e.fragments.length>0&&function(t,i){let s=null;const e=t.fragments;for(let t=e.length-1;t>=0;t--){const i=e[t].initSegment;if(i){s=i;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,i,s){const e=i.skippedSegments,n=Math.max(t.startSN,i.startSN)-i.startSN,r=(t.fragmentHint?1:0)+(e?i.endSN:Math.min(t.endSN,i.endSN))-i.startSN,h=i.startSN-t.startSN,o=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments,a=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=n;t<=r;t++){const n=a[h+t];let r=o[t];e&&!r&&t<e&&(r=i.fragments[t]=n),n&&r&&s(n,r,t,o)}}(t,i,((t,e,r,h)=>{if(i.skippedSegments&&e.cc!==t.cc){const i=t.cc-e.cc;for(let t=r;t<h.length;t++)h[t].cc+=i}T(t.startPTS)&&T(t.endPTS)&&(e.start=e.startPTS=t.startPTS,e.startDTS=t.startDTS,e.maxStartPTS=t.maxStartPTS,e.endPTS=t.endPTS,e.endDTS=t.endDTS,e.minEndPTS=t.minEndPTS,e.duration=t.endPTS-t.startPTS,e.duration&&(n=e),i.PTSKnown=i.alignedSliding=!0),e.elementaryStreams=t.elementaryStreams,e.loader=t.loader,e.stats=t.stats,t.initSegment&&(e.initSegment=t.initSegment,s=t.initSegment)}));const r=i.fragments;if(s&&(i.fragmentHint?r.concat(i.fragmentHint):r).forEach((t=>{var i;!t||t.initSegment&&t.initSegment.relurl!==(null==(i=s)?void 0:i.relurl)||(t.initSegment=s)})),i.skippedSegments){if(i.deltaUpdateFailed=r.some((t=>!t)),i.deltaUpdateFailed){I.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=i.skippedSegments;t--;)r.shift();i.startSN=r[0].sn}else i.canSkipDateRanges&&(i.dateRanges=function(t,i,s){const e=S({},t);return s&&s.forEach((t=>{delete e[t]})),Object.keys(i).forEach((t=>{const s=new U(i[t].attr,e[t]);s.isValid?e[t]=s:I.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(i[t].attr)}"`)})),e}(t.dateRanges,i.dateRanges,i.recentlyRemovedDateranges));i.startCC=i.fragments[0].cc,i.endCC=r[r.length-1].cc}!function(t,i,s){if(t&&i){let e=0;for(let n=0,r=t.length;n<=r;n++){const r=t[n],h=i[n+e];r&&h&&r.index===h.index&&r.fragment.sn===h.fragment.sn?s(r,h):e--}}}(t.partList,i.partList,((t,i)=>{i.elementaryStreams=t.elementaryStreams,i.stats=t.stats})),n?ns(i,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):rs(t,i),r.length&&(i.totalduration=i.edge-r[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const h=i.advancedDateTime;if(i.advanced&&h){const t=i.edge;i.driftStart||(i.driftStartTime=h,i.driftStart=t),i.driftEndTime=h,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime}(s,e),!this.canLoad||!e.live)return;let h,o,a;if(e.canBlockReload&&e.endSN&&e.advanced){const t=this.hls.config.lowLatencyMode,n=e.lastPartSn,r=e.endSN,l=e.lastPartIndex,c=n===r;-1!==l?(o=c?r+1:n,a=c?t?0:l:l+1):o=r+1;const u=e.age;let d=Math.min(u+e.ageHeader-e.partTarget,1.5*e.targetduration);if(d>0){if(s&&d>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${d} with playlist age: ${e.age}`),d=0;else{const t=Math.floor(d/e.targetduration);o+=t,void 0!==a&&(a+=Math.round(d%e.targetduration/e.partTarget)),this.log(`CDN Tune-in age: ${e.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${d} skip sn ${t} to part ${a}`)}e.tuneInGoal=d}if(h=this.getDeliveryDirectives(e,i.deliveryDirectives,o,a),t||!c)return void this.loadPlaylist(h)}else(e.canBlockReload||e.canSkipUntil)&&(h=this.getDeliveryDirectives(e,i.deliveryDirectives,o,a));const l=this.hls.mainForwardBufferInfo,c=function(t,i=1/0){let s=1e3*t.targetduration;if(t.updated){const e=t.fragments;if(e.length&&4*s>i){const t=1e3*e[e.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}(e,1e3*(e.edge-(l?l.end-l.len:0)));e.updated&&r>this.requestScheduled+c&&(this.requestScheduled=n.loading.start),void 0!==o&&e.canBlockReload?this.requestScheduled=n.loading.first+c-(1e3*e.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+c<r?this.requestScheduled=r:this.requestScheduled-r<=0&&(this.requestScheduled+=c);let u=this.requestScheduled-r;u=Math.max(0,u),this.log(`reload live playlist ${t} in ${Math.round(u)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(h)),u)}else this.clearTimer()}getDeliveryDirectives(t,i,s,e){let n=Zi(t);return null!=i&&i.skip&&t.deltaUpdateFailed&&(s=i.msn,e=i.part,n=""),new ts(s,e,n)}checkRetry(t){const i=t.details,s=cs(t),e=t.errorAction,{action:n,retryCount:r=0,retryConfig:h}=e||{},o=!!e&&!!h&&(5===n||!e.resolved&&2===n);if(o){var a;if(this.requestScheduled=-1,r>=h.maxNumRetry)return!1;if(s&&null!=(a=t.context)&&a.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${h.maxNumRetry} after "${i}" without delivery-directives`),this.loadPlaylist();else{const t=ds(h,r);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${r+1}/${h.maxNumRetry} after "${i}" in ${t}ms`)}t.levelRetry=!0,e.resolved=!0}return o}}class bs{constructor(t,i=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_=i,this.totalWeight_=s}sample(t,i){const s=Math.pow(this.alpha_,t);this.estimate_=i*(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 ks{constructor(t,i,s,e=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 bs(t),this.fast_=new bs(i),this.defaultTTFB_=e,this.ttfb_=new bs(t)}update(t,i){const{slow_:s,fast_:e,ttfb_:n}=this;s.halfLife!==t&&(this.slow_=new bs(t,s.getEstimate(),s.getTotalWeight())),e.halfLife!==i&&(this.fast_=new bs(i,e.getEstimate(),e.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new bs(t,n.getEstimate(),n.getTotalWeight()))}sample(t,i){const s=(t=Math.max(t,this.minDelayMs_))/1e3,e=8*i/s;this.fast_.sample(s,e),this.slow_.sample(s,e)}sampleTTFB(t){const i=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(i,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 Ss={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Ts={};function $s(t,i,s,e,n,r){const h=t.audioCodec?t.audioGroups:null,o=null==r?void 0:r.audioCodec,a=null==r?void 0:r.channels,l=a?parseInt(a):o?1/0:2;let c=null;if(null!=h&&h.length)try{c=1===h.length&&h[0]?i.groups[h[0]].channels:h.reduce(((t,s)=>{if(s){const e=i.groups[s];if(!e)throw new Error(`Audio track group ${s} not found`);Object.keys(e.channels).forEach((i=>{t[i]=(t[i]||0)+e.channels[i]}))}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(e,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(n,8e6))||!!c&&T(l)&&Object.keys(c).some((t=>parseInt(t)>l))}function Es(t,i,s){const e=t.videoCodec,n=t.audioCodec;if(!e||!n||!s)return Promise.resolve(Ss);const r={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},h=t.videoRange;"SDR"!==h&&(r.transferFunction=h.toLowerCase());const o=e.split(",").map((t=>({type:"media-source",video:k(k({},r),{},{contentType:ai(t,"video")})})));return n&&t.audioGroups&&t.audioGroups.forEach((t=>{var s;t&&(null==(s=i.groups[t])||s.tracks.forEach((i=>{if(i.groupId===t){const t=parseFloat(i.channels||"");T(t)&&t>2&&o.push.apply(o,n.split(",").map((i=>({type:"media-source",audio:{contentType:ai(i,"audio"),channels:""+t}}))))}})))})),Promise.all(o.map((t=>{const i=function(t){const{audio:i,video:s}=t,e=s||i;if(e){const t=e.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(i)return`c${i.channels}${i.spatialRendering?"s":"n"}_${t}`}return""}(t);return Ts[i]||(Ts[i]=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 As(t,i){I.log(`[abr] start candidates with "${t}" ignored because ${i}`)}function Ms(t,i,s){if("attrs"in t){const s=i.indexOf(t);if(-1!==s)return s}for(let e=0;e<i.length;e++)if(Ls(t,i[e],s))return e;return-1}function Ls(t,i,s){const{groupId:e,name:n,lang:r,assocLang:h,default:o}=t,a=t.forced;return(void 0===e||i.groupId===e)&&(void 0===n||i.name===n)&&(void 0===r||i.lang===r)&&(void 0===r||i.assocLang===h)&&(void 0===o||i.default===o)&&(void 0===a||i.forced===a)&&(!("characteristics"in t)||function(t,i=""){const s=t.split(","),e=i.split(",");return s.length===e.length&&!s.some((t=>-1===e.indexOf(t)))}(t.characteristics||"",i.characteristics))&&(void 0===s||s(t,i))}function xs(t,i){const{audioCodec:s,channels:e}=t;return!(void 0!==s&&(i.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==e&&e!==(i.channels||"2"))}function Ds(t,i,s){for(let e=i;e>-1;e--)if(s(t[e]))return e;for(let e=i+1;e<t.length;e++)if(s(t[e]))return e;return-1}class Cs{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var Is="NOT_LOADED",Rs="APPENDING",Ps="PARTIAL",Os="OK";class Ns{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(A.BUFFER_APPENDED,this.onBufferAppended,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this),t.on(A.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.BUFFER_APPENDED,this.onBufferAppended,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this),t.off(A.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,i){const s=this.activePartLists[i];if(s)for(let i=s.length;i--;){const e=s[i];if(!e)break;const n=e.end;if(e.start<=t&&null!==n&&t<=n)return e}return this.getBufferedFrag(t,i)}getBufferedFrag(t,i){const{fragments:s}=this,e=Object.keys(s);for(let n=e.length;n--;){const r=s[e[n]];if((null==r?void 0:r.body.type)===i&&r.buffered){const i=r.body;if(i.start<=t&&t<=i.end)return i}}return null}detectEvictedFragments(t,i,s,e){this.timeRanges&&(this.timeRanges[t]=i);const n=(null==e?void 0:e.fragment.sn)||-1;Object.keys(this.fragments).forEach((e=>{const r=this.fragments[e];if(!r)return;if(n>=r.body.sn)return;if(!r.buffered&&!r.loaded)return void(r.body.type===s&&this.removeFragment(r.body));const h=r.range[t];h&&h.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,i);return s&&this.removeFragment(r.body),s}))}))}detectPartialFragments(t){const i=this.timeRanges,{frag:s,part:e}=t;if(!i||"initSegment"===s.sn)return;const n=Fs(s),r=this.fragments[n];if(!r||r.buffered&&s.gap)return;const h=!s.relurl;Object.keys(i).forEach((t=>{const n=s.elementaryStreams[t];n&&(r.range[t]=this.getBufferedTimes(s,e,h||!0===n.partial,i[t]))})),r.loaded=null,Object.keys(r.range).length?(r.buffered=!0,(r.body.endList=s.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),Us(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}removeParts(t,i){const s=this.activePartLists[i];s&&(this.activePartLists[i]=s.filter((i=>i.fragment.sn>=t)))}fragBuffered(t,i){const s=Fs(t);let e=this.fragments[s];!e&&i&&(e=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),e&&(e.loaded=null,e.buffered=!0)}getBufferedTimes(t,i,s,e){const n={time:[],partial:s},r=t.start,h=t.end,o=t.minEndPTS||h,a=t.maxStartPTS||r;for(let t=0;t<e.length;t++){const i=e.start(t)-this.bufferPadding,s=e.end(t)+this.bufferPadding;if(a>=i&&o<=s){n.time.push({startPTS:Math.max(r,e.start(t)),endPTS:Math.min(h,e.end(t))});break}if(r<s&&h>i){const i=Math.max(r,e.start(t)),s=Math.min(h,e.end(t));s>i&&(n.partial=!0,n.time.push({startPTS:i,endPTS:s}))}else if(h<=i)break}return n}getPartialFragment(t){let i,s,e,n=null,r=0;const{bufferPadding:h,fragments:o}=this;return Object.keys(o).forEach((a=>{const l=o[a];l&&Us(l)&&(s=l.body.start-h,e=l.body.end+h,t>=s&&t<=e&&(i=Math.min(t-s,e-t),r<=i&&(n=l.body,r=i)))})),n}isEndListAppended(t){const i=this.endListFragments[t];return void 0!==i&&(i.buffered||Us(i))}getState(t){const i=Fs(t),s=this.fragments[i];return s?s.buffered?Us(s)?Ps:Os:Rs:Is}isTimeBuffered(t,i,s){let e,n;for(let r=0;r<s.length;r++){if(e=s.start(r)-this.bufferPadding,n=s.end(r)+this.bufferPadding,t>=e&&i<=n)return!0;if(i<=e)return!1}return!1}onFragLoaded(t,i){const{frag:s,part:e}=i;if("initSegment"===s.sn||s.bitrateTest)return;const n=e?null:i,r=Fs(s);this.fragments[r]={body:s,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(t,i){const{frag:s,part:e,timeRanges:n}=i;if("initSegment"===s.sn)return;const r=s.type;if(e){let t=this.activePartLists[r];t||(this.activePartLists[r]=t=[]),t.push(e)}this.timeRanges=n,Object.keys(n).forEach((t=>{this.detectEvictedFragments(t,n[t],r,e)}))}onFragBuffered(t,i){this.detectPartialFragments(i)}hasFragment(t){const i=Fs(t);return!!this.fragments[i]}hasParts(t){var i;return!(null==(i=this.activePartLists[t])||!i.length)}removeFragmentsInRange(t,i,s,e,n){e&&!this.hasGaps||Object.keys(this.fragments).forEach((r=>{const h=this.fragments[r];if(!h)return;const o=h.body;o.type!==s||e&&!o.gap||o.start<i&&o.end>t&&(h.buffered||n)&&this.removeFragment(o)}))}removeFragment(t){const i=Fs(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const i=t.sn;this.activePartLists[t.type]=s.filter((t=>t.fragment.sn!==i))}delete this.fragments[i],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 Us(t){var i,s,e;return t.buffered&&(t.body.gap||(null==(i=t.range.video)?void 0:i.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(e=t.range.audiovideo)?void 0:e.partial))}function Fs(t){return`${t.type}_${t.level}_${t.sn}`}const Bs={length:0,start:()=>0,end:()=>0};class js{static isBuffered(t,i){try{if(t){const s=js.getBuffered(t);for(let t=0;t<s.length;t++)if(i>=s.start(t)&&i<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,i,s){try{if(t){const e=js.getBuffered(t),n=[];let r;for(r=0;r<e.length;r++)n.push({start:e.start(r),end:e.end(r)});return this.bufferedInfo(n,i,s)}}catch(t){}return{len:0,start:i,end:i,nextStart:void 0}}static bufferedInfo(t,i,s){i=Math.max(0,i),t.sort((function(t,i){return t.start-i.start||i.end-t.end}));let e=[];if(s)for(let i=0;i<t.length;i++){const n=e.length;if(n){const r=e[n-1].end;t[i].start-r<s?t[i].end>r&&(e[n-1].end=t[i].end):e.push(t[i])}else e.push(t[i])}else e=t;let n,r=0,h=i,o=i;for(let t=0;t<e.length;t++){const a=e[t].start,l=e[t].end;if(i+s>=a&&i<l)h=a,o=l,r=o-i;else if(i+s<a){n=a;break}}return{len:r,start:h||0,end:o||0,nextStart:n}}static getBuffered(t){try{return t.buffered}catch(t){return I.log("failed to get media.buffered",t),Bs}}}class _s{constructor(t,i,s,e=0,n=-1,r=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=i,this.id=s,this.size=e,this.part=n,this.partial=r}}function Gs(t,i){for(let e=0,n=t.length;e<n;e++){var s;if((null==(s=t[e])?void 0:s.cc)===i)return t[e]}return null}function Hs(t,i){if(t){const s=t.start+i;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Ks(t,i){const s=i.fragments;for(let i=0,e=s.length;i<e;i++)Hs(s[i],t);i.fragmentHint&&Hs(i.fragmentHint,t),i.alignedSliding=!0}function Vs(t,i){if(!t.hasProgramDateTime||!i.hasProgramDateTime)return;const s=t.fragments,e=i.fragments;if(!s.length||!e.length)return;let n,r;const h=Math.min(i.endCC,t.endCC);i.startCC<h&&t.startCC<h&&(n=Gs(e,h),r=Gs(s,h)),n&&r||(n=e[Math.floor(e.length/2)],r=Gs(s,n.cc)||s[Math.floor(s.length/2)]);const o=n.programDateTime,a=r.programDateTime;o&&a&&Ks((a-o)/1e3-(r.start-n.start),t)}const zs=Math.pow(2,17);class Ws{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,i){const s=t.url;if(!s)return Promise.reject(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const e=this.config,n=e.fLoader,r=e.loader;return new Promise(((h,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(qs(t));t.gap=!1}const a=this.loader=t.loader=n?new n(e):new r(e),l=Xs(t),c=fs(e.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:zs};t.stats=a.stats,a.load(l,u,{onSuccess:(i,s,e,n)=>{this.resetLoader(t,a);let r=i.data;e.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(r.slice(0,16)),r=r.slice(16)),h({frag:t,part:null,payload:r,networkDetails:n})},onError:(i,e,n,r)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:k({url:s,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:n,stats:r}))},onAbort:(i,s,e)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:e,stats:i}))},onTimeout:(i,s,e)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:e,stats:i}))},onProgress:(s,e,n,r)=>{i&&i({frag:t,part:null,payload:n,networkDetails:r})}})}))}loadPart(t,i,s){this.abort();const e=this.config,n=e.fLoader,r=e.loader;return new Promise(((h,o)=>{if(this.loader&&this.loader.destroy(),t.gap||i.gap)return void o(qs(t,i));const a=this.loader=t.loader=n?new n(e):new r(e),l=Xs(t,i),c=fs(e.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zs};i.stats=a.stats,a.load(l,u,{onSuccess:(e,n,r,o)=>{this.resetLoader(t,a),this.updateStatsFromPart(t,i);const l={frag:t,part:i,payload:e.data,networkDetails:o};s(l),h(l)},onError:(s,e,n,r)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:i,response:k({url:l.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:n,stats:r}))},onAbort:(s,e,n)=>{t.stats.aborted=i.stats.aborted,this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:t,part:i,error:new Error("Aborted"),networkDetails:n,stats:s}))},onTimeout:(s,e,n)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:i,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:n,stats:s}))}})}))}updateStatsFromPart(t,i){const s=t.stats,e=i.stats,n=e.total;if(s.loaded+=e.loaded,n){const e=Math.round(t.duration/i.duration),r=Math.min(Math.round(s.loaded/n),e),h=(e-r)*Math.round(s.loaded/r);s.total=s.loaded+h}else s.total=Math.max(s.loaded,s.total);const r=s.loading,h=e.loading;r.start?r.first+=h.first-h.start:(r.start=h.start,r.first=h.first),r.end=h.end}resetLoader(t,i){t.loader=null,this.loader===i&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),i.destroy()}}function Xs(t,i=null){const s=i||t,e={frag:t,part:i,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=s.byteRangeStartOffset,r=s.byteRangeEndOffset;if(T(n)&&T(r)){var h;let i=n,s=r;if("initSegment"===t.sn&&"AES-128"===(null==(h=t.decryptdata)?void 0:h.method)){const t=r-n;t%16&&(s=r+(16-t%16)),0!==n&&(e.resetIV=!0,i=n-16)}e.rangeStart=i,e.rangeEnd=s}return e}function qs(t,i){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),e={type:M.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return i&&(e.part=i),(i||t).stats.aborted=!0,new Ys(e)}class Ys extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Js{constructor(t,i){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=i}decrypt(t,i){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},i,t)}}class Qs{constructor(t,i){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=i}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Zs{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 i=new DataView(t),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=i.getUint32(4*t);return s}initTable(){const t=this.sBox,i=this.invSBox,s=this.subMix,e=s[0],n=s[1],r=s[2],h=s[3],o=this.invSubMix,a=o[0],l=o[1],c=o[2],u=o[3],d=new Uint32Array(256);let f=0,v=0,p=0;for(p=0;p<256;p++)d[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let s=v^v<<1^v<<2^v<<3^v<<4;s=s>>>8^255&s^99,t[f]=s,i[s]=f;const o=d[f],p=d[o],g=d[p];let m=257*d[s]^16843008*s;e[f]=m<<24|m>>>8,n[f]=m<<16|m>>>16,r[f]=m<<8|m>>>24,h[f]=m,m=16843009*g^65537*p^257*o^16843008*f,a[s]=m<<24|m>>>8,l[s]=m<<16|m>>>16,c[s]=m<<8|m>>>24,u[s]=m,f?(f=o^d[d[d[g^o]]],v^=d[d[v]]):f=v=1}}expandKey(t){const i=this.uint8ArrayToUint32Array_(t);let s=!0,e=0;for(;e<i.length&&s;)s=i[e]===this.key[e],e++;if(s)return;this.key=i;const n=this.keySize=i.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);const r=this.ksRows=4*(n+6+1);let h,o;const a=this.keySchedule=new Uint32Array(r),l=this.invKeySchedule=new Uint32Array(r),c=this.sBox,u=this.rcon,d=this.invSubMix,f=d[0],v=d[1],p=d[2],g=d[3];let m,y;for(h=0;h<r;h++)h<n?m=a[h]=i[h]:(y=m,h%n==0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=u[h/n|0]<<24):n>6&&h%n==4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),a[h]=m=(a[h-n]^y)>>>0);for(o=0;o<r;o++)h=r-o,y=3&o?a[h]:a[h-4],l[o]=o<4||h<=4?y:f[c[y>>>24]]^v[c[y>>>16&255]]^p[c[y>>>8&255]]^g[c[255&y]],l[o]=l[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,i,s){const e=this.keySize+6,n=this.invKeySchedule,r=this.invSBox,h=this.invSubMix,o=h[0],a=h[1],l=h[2],c=h[3],u=this.uint8ArrayToUint32Array_(s);let d=u[0],f=u[1],v=u[2],p=u[3];const g=new Int32Array(t),m=new Int32Array(g.length);let y,w,b,k,S,T,$,E,A,M,L,x,D,C;const I=this.networkToHostOrderSwap;for(;i<g.length;){for(A=I(g[i]),M=I(g[i+1]),L=I(g[i+2]),x=I(g[i+3]),S=A^n[0],T=x^n[1],$=L^n[2],E=M^n[3],D=4,C=1;C<e;C++)y=o[S>>>24]^a[T>>16&255]^l[$>>8&255]^c[255&E]^n[D],w=o[T>>>24]^a[$>>16&255]^l[E>>8&255]^c[255&S]^n[D+1],b=o[$>>>24]^a[E>>16&255]^l[S>>8&255]^c[255&T]^n[D+2],k=o[E>>>24]^a[S>>16&255]^l[T>>8&255]^c[255&$]^n[D+3],S=y,T=w,$=b,E=k,D+=4;y=r[S>>>24]<<24^r[T>>16&255]<<16^r[$>>8&255]<<8^r[255&E]^n[D],w=r[T>>>24]<<24^r[$>>16&255]<<16^r[E>>8&255]<<8^r[255&S]^n[D+1],b=r[$>>>24]<<24^r[E>>16&255]<<16^r[S>>8&255]<<8^r[255&T]^n[D+2],k=r[E>>>24]<<24^r[S>>16&255]<<16^r[T>>8&255]<<8^r[255&$]^n[D+3],m[i]=I(y^d),m[i+1]=I(k^f),m[i+2]=I(b^v),m[i+3]=I(w^p),d=A,f=M,v=L,p=x,i+=4}return m.buffer}}class te{constructor(t,{removePKCS7Padding:i=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=i,i)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:i}=this;if(!t||i)return this.reset(),null;const s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const i=t.byteLength,s=i&&new DataView(t.buffer).getUint8(i-1);return s?ot(t,0,i-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,i,s){return this.useSoftware?new Promise(((e,n)=>{this.softwareDecrypt(new Uint8Array(t),i,s);const r=this.flush();r?e(r.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),i,s)}softwareDecrypt(t,i,s){const{currentIV:e,currentResult:n,remainderData:r}=this;this.logOnce("JS AES decrypt"),r&&(t=Kt(r,t),this.remainderData=null);const h=this.getValidChunk(t);if(!h.length)return null;e&&(s=e);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new Zs),o.expandKey(i);const a=n;return this.currentResult=o.decrypt(h.buffer,0,s),this.currentIV=ot(h,-16).buffer,a||null}webCryptoDecrypt(t,i,s){if(this.key!==i||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,i,s));this.key=i,this.fastAesKey=new Qs(this.subtle,i)}return this.fastAesKey.expandKey().then((i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Js(this.subtle,new Uint8Array(s)).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized")))).catch((e=>(I.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${e.name}: ${e.message}`),this.onWebCryptoError(t,i,s))))}onWebCryptoError(t,i,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,i,s);const e=this.flush();if(e)return e.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let i=t;const s=t.length-t.length%16;return s!==t.length&&(i=ot(t,0,s),this.remainderData=ot(t,s)),i}logOnce(t){this.logEnabled&&(I.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ie="STOPPED",se="IDLE",ee="KEY_LOADING",ne="FRAG_LOADING",re="FRAG_LOADING_WAITING_RETRY",he="WAITING_TRACK",oe="PARSING",ae="PARSED",le="ENDED",ce="ERROR",ue="WAITING_INIT_PTS",de="WAITING_LEVEL";class fe extends Cs{constructor(t,i,s,e,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ie,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=e,this.log=I.log.bind(I,`${e}:`),this.warn=I.warn.bind(I,`${e}:`),this.hls=t,this.fragmentLoader=new Ws(t.config),this.keyLoader=s,this.fragmentTracker=i,this.config=t.config,this.decrypter=new te(t.config),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ie}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}_streamEnded(t,i){if(i.live||t.nextStart||!t.end||!this.media)return!1;const s=i.partList;if(null!=s&&s.length){const t=s[s.length-1];return js.isBuffered(this.media,t.start+t.duration/2)}return this.fragmentTracker.isEndListAppended(i.fragments[i.fragments.length-1].type)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,i){const s=this.media=this.mediaBuffer=i.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const e=this.config;this.levels&&e.autoStartLoad&&this.state===ie&&this.startLoad(e.startPosition)}onMediaDetaching(){const t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:i,media:s,mediaBuffer:e,state:n}=this,r=s?s.currentTime:0,h=js.bufferInfo(e||s,r,t.maxBufferHole);if(this.log(`media seeking to ${T(r)?r.toFixed(3):r}, state: ${n}`),this.state===le)this.resetLoadingState();else if(i){const s=t.maxFragLookUpTolerance,e=i.start-s,n=i.start+i.duration+s;if(!h.len||n<h.start||e>h.end){const t=r>n;(r<e||t)&&(t&&i.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),i.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,this.playlistType,!0),this.lastCurrentTime=r),this.loadedmetadata||h.len||(this.nextLoadPosition=this.startPosition=r),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,i){this.startTimeOffset=i.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=ie,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,i,s){this._loadFragForPlayback(t,i,s)}_loadFragForPlayback(t,i,s){this._doFragLoad(t,i,s,(i=>{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${i.part?" p: "+i.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(i)})).then((i=>{if(!i)return;const s=this.state;this.fragContextChanged(t)?(s===ne||!this.fragCurrent&&s===oe)&&(this.fragmentTracker.removeFragment(t),this.state=se):("payload"in i&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(A.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i))})).catch((i=>{this.state!==ie&&this.state!==ce&&(this.warn(`Frag error: ${(null==i?void 0:i.message)||i}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var i;const{fragmentTracker:s}=this;if(s.getState(t)===Rs){const i=this.getFwdBufferInfo(this.mediaBuffer,t.type),e=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1==(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(e,t.duration))&&s.removeFragment(t)}else 0===(null==(i=this.mediaBuffer)?void 0:i.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===Ps&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const i=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,i,s=null){t-i&&this.hls.trigger(A.BUFFER_FLUSHING,{startOffset:t,endOffset:i,type:s})}_loadInitSegment(t,i){this._doFragLoad(t,i).then((i=>{if(!i||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return i})).then((i=>{const{hls:s}=this,{payload:e}=i,n=t.decryptdata;if(e&&e.byteLength>0&&null!=n&&n.key&&n.iv&&"AES-128"===n.method){const r=self.performance.now();return this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer).catch((i=>{throw s.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:i,reason:i.message,frag:t}),i})).then((e=>{const n=self.performance.now();return s.trigger(A.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:r,tdecrypt:n}}),i.payload=e,this.completeInitSegmentLoad(i)}))}return this.completeInitSegmentLoad(i)})).catch((i=>{this.state!==ie&&this.state!==ce&&(this.warn(i),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:i}=this;if(!i)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=se,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:i}=this;return!t||!i||t.sn!==i.sn||t.level!==i.level}fragBufferedComplete(t,i){var s,e,n,r;const h=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${i?" part: "+i.index:""} of ${this.playlistType===Ii?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(e=t.endPTS)?e:NaN).toFixed(3)}] > buffer:${h?function(t){let i="";const s=t.length;for(let e=0;e<s;e++)i+=`[${t.start(e).toFixed(3)}-${t.end(e).toFixed(3)}]`;return i}(js.getBuffered(h)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==Pi){const i=t.elementaryStreams;if(!Object.keys(i).some((t=>!!i[t])))return void(this.state=se)}const i=null==(o=this.levels)?void 0:o[t.level];null!=i&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=se,h&&(!this.loadedmetadata&&t.type==Ii&&h.buffered.length&&(null==(n=this.fragCurrent)?void 0:n.sn)===(null==(r=this.fragPrevious)?void 0:r.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:i}=this;if(!i)return;const{frag:s,part:e,partsLoaded:n}=t,r=!n||0===n.length||n.some((t=>!t)),h=new _s(s.level,s.sn,s.stats.chunkCount+1,0,e?e.index:-1,!r);i.flush(h)}_handleFragmentLoadProgress(t){}_doFragLoad(t,i,s=null,e){var n;const r=null==i?void 0:i.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);let h=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key?!t.encrypted&&r.encryptedFragments.length&&this.keyLoader.loadClear(t,r.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${r.startSN}-${r.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=ee,this.fragCurrent=t,h=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(A.KEY_LOADED,t),this.state===ee&&(this.state=se),t})),this.hls.trigger(A.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(h=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 n=r.partList;if(n&&e){s>t.end&&r.fragmentHint&&(t=r.fragmentHint);const o=this.getNextPart(n,t,s);if(o>-1){const a=n[o];let l;return this.log(`Loading part sn: ${t.sn} p: ${a.index} cc: ${t.cc} of playlist [${r.startSN}-${r.endSN}] parts [0-${o}-${n.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=a.start+a.duration,this.state=ne,l=h?h.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,a,i,e))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,a,i,e).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(A.FRAG_LOADING,{frag:t,part:a,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):l}if(!t.url||this.loadedEndOfParts(n,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${r?"of ["+r.startSN+"-"+r.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),T(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ne;const o=this.config.progressive;let a;return a=o&&h?h.then((i=>!i||this.fragContextChanged(null==i?void 0:i.frag)?null:this.fragmentLoader.load(t,e))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?e:void 0),h]).then((([t])=>(!o&&t&&e&&e(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(A.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):a}doFragPartsLoad(t,i,s,e){return new Promise(((n,r)=>{var h;const o=[],a=null==(h=s.details)?void 0:h.partList,l=i=>{this.fragmentLoader.loadPart(t,i,e).then((e=>{o[i.index]=e;const r=e.part;this.hls.trigger(A.FRAG_LOADED,e);const h=os(s,t.sn,i.index+1)||as(a,t.sn,i.index+1);if(!h)return n({frag:t,part:r,partsLoaded:o});l(h)})).catch(r)};l(i)}))}handleFragLoadError(t){if("data"in t){const i=t.data;t.data&&i.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(i.frag,i.part):this.hls.trigger(A.ERROR,i)}else this.hls.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const i=this.getCurrentContext(t);if(!i||this.state!==oe)return void(this.fragCurrent||this.state===ie||this.state===ce||(this.state=se));const{frag:s,part:e,level:n}=i,r=self.performance.now();s.stats.parsing.end=r,e&&(e.stats.parsing.end=r),this.updateLevelTiming(s,e,n,t.partial)}getCurrentContext(t){const{levels:i,fragCurrent:s}=this,{level:e,sn:n,part:r}=t;if(null==i||!i[e])return this.warn(`Levels object was unset while buffering fragment ${n} of level ${e}. The current chunk will not be buffered.`),null;const h=i[e],o=r>-1?os(h,n,r):null,a=o?o.fragment:function(t,i,s){if(null==t||!t.details)return null;const e=t.details;let n=e.fragments[i-e.startSN];return n||(n=e.fragmentHint,n&&n.sn===i?n:i<e.startSN&&s&&s.sn===i?s:null)}(h,n,s);return a?(s&&s!==a&&(a.stats=s.stats),{frag:a,part:o,level:h}):null}bufferFragmentData(t,i,s,e,n){var r;if(!t||this.state!==oe)return;const{data1:h,data2:o}=t;let a=h;if(h&&o&&(a=Kt(h,o)),null!=(r=a)&&r.length&&(this.hls.trigger(A.BUFFER_APPENDING,{type:t.type,frag:i,part:s,chunkMeta:e,parent:i.type,data:a}),t.dropped&&t.independent&&!s)){if(n)return;this.flushBufferGap(i)}}flushBufferGap(t){const i=this.media;if(!i)return;if(!js.isBuffered(i,i.currentTime))return void this.flushMainBuffer(0,t.start);const s=i.currentTime,e=js.bufferInfo(i,s,0),n=Math.min(2*this.config.maxFragLookUpTolerance,.25*t.duration),r=Math.max(Math.min(t.start-n,e.end-n),s+n);t.start-r>n&&this.flushMainBuffer(r,t.start)}getFwdBufferInfo(t,i){const s=this.getLoadPosition();return T(s)?this.getFwdBufferInfoAtPos(t,s,i):null}getFwdBufferInfoAtPos(t,i,s){const{config:{maxBufferHole:e}}=this,n=js.bufferInfo(t,i,e);if(0===n.len&&void 0!==n.nextStart){const r=this.fragmentTracker.getBufferedFrag(i,s);if(r&&n.nextStart<r.end)return js.bufferInfo(t,i,Math.max(n.nextStart,e))}return n}getMaxBufferLength(t){const{config:i}=this;let s;return s=t?Math.max(8*i.maxBufferSize/t,i.maxBufferLength):i.maxBufferLength,Math.min(s,i.maxMaxBufferLength)}reduceMaxBufferLength(t,i){const s=this.config,e=Math.max(Math.min(t-i,s.maxBufferLength),i),n=Math.max(t-3*i,s.maxMaxBufferLength/2,e);return n>=e&&(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0)}getAppendedFrag(t,i=Ii){const s=this.fragmentTracker.getAppendedFrag(t,Ii);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,i){const s=i.fragments,e=s.length;if(!e)return null;const{config:n}=this,r=s[0].start;let h;if(i.live){const o=n.initialLiveManifestSize;if(e<o)return this.warn(`Not enough fragments to start playback (have: ${e}, need: ${o})`),null;(!i.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<r)&&(h=this.getInitialLiveFragment(i,s),this.startPosition=this.nextLoadPosition=h?this.hls.liveSyncPosition||h.start:t)}else t<=r&&(h=s[0]);return h||(h=this.getFragmentAtPosition(t,n.lowLatencyMode?i.partEnd:i.fragmentEnd,i)),this.mapToInitFragWhenRequired(h)}isLoopLoading(t,i){const s=this.fragmentTracker.getState(t);return(s===Os||s===Ps&&!!t.gap)&&this.nextLoadPosition>i}getNextFragmentLoopLoading(t,i,s,e,n){const r=t.gap,h=this.getNextFragment(this.nextLoadPosition,i);if(null===h)return h;if(t=h,r&&t&&!t.gap&&s.nextStart){const i=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,e);if(null!==i&&s.len+i.len>=n)return this.log(`buffer full after gaps in "${e}" 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,i,s){let e=-1,n=!1,r=!0;for(let h=0,o=t.length;h<o;h++){const o=t[h];if(r=r&&!o.independent,e>-1&&s<o.start)break;const a=o.loaded;a?e=-1:(n||o.independent||r)&&o.fragment===i&&(e=h),n=a}return e}loadedEndOfParts(t,i){const s=t[t.length-1];return s&&i>s.start&&s.loaded}getInitialLiveFragment(t,i){const s=this.fragPrevious;let e=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),e=function(t,i,s){if(null===i||!Array.isArray(t)||!t.length||!T(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let e=0;e<t.length;++e){const n=t[e];if(ys(i,s,n))return n}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!e){const n=s.sn+1;if(n>=t.startSN&&n<=t.endSN){const r=i[n-t.startSN];s.cc===r.cc&&(e=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${e.sn}`))}e||(e=function(t,i){return ps(t,(t=>t.cc<i?1:t.cc>i?-1:0))}(i,s.cc),e&&this.log(`Live playlist, switching playlist, load frag with same CC: ${e.sn}`))}}else{const i=this.hls.liveSyncPosition;null!==i&&(e=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return e}getFragmentAtPosition(t,i,s){const{config:e}=this;let{fragPrevious:n}=this,{fragments:r,endSN:h}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:a}=e,l=s.partList,c=!!(e.lowLatencyMode&&null!=l&&l.length&&o);let u;if(c&&o&&!this.bitrateTest&&(r=r.concat(o),h=o.sn),u=t<i?gs(n,r,t,t>i-a?0:a):r[r.length-1],u){const t=u.sn-s.startSN,i=this.fragmentTracker.getState(u);if((i===Os||i===Ps&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!c||l[0].fragment.sn>u.sn)&&n&&u.level===n.level){const i=r[t+1];u=u.sn<h&&this.fragmentTracker.getState(i)!==Os?i:null}}return u}synchronizeToLiveEdge(t){const{config:i,media:s}=this;if(!s)return;const e=this.hls.liveSyncPosition,n=s.currentTime,r=t.edge,h=n>=t.fragments[0].start-i.maxFragLookUpTolerance&&n<=r;null!==e&&s.duration>e&&(n<e||!h)&&(!h&&s.readyState<4||n<r-(void 0!==i.liveMaxLatencyDuration?i.liveMaxLatencyDuration:i.liveMaxLatencyDurationCount*t.targetduration))&&(this.loadedmetadata||(this.nextLoadPosition=e),s.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${r}, reset currentTime to : ${e.toFixed(3)}`),s.currentTime=e))}alignPlaylists(t,i,s){const e=t.fragments.length;if(!e)return this.warn("No fragments in live playlist"),0;const n=t.fragments[0].start,r=!i,h=t.alignedSliding&&T(n);if(r||!h&&!n){const{fragPrevious:n}=this;!function(t,i,s){i&&(function(t,i,s){if(function(t,i,s){return!(!i||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,i)){const t=function(t,i){const s=t.fragments,e=i.fragments;if(!e.length||!s.length)return void I.log("No fragments to align");const n=Gs(s,e[0].cc);if(n&&(!n||n.startPTS))return n;I.log("No frag in previous level to align on")}(s,i);t&&T(t.start)&&(I.log(`Adjusting PTS using last level due to CC increase within current level ${i.url}`),Ks(t.start,i))}}(t,s,i),!s.alignedSliding&&i&&Vs(s,i),s.alignedSliding||!i||s.skippedSegments||rs(i,s))}(n,s,t);const r=t.fragments[0].start;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${i?i.startSN:"na"}->${t.startSN} prev-sn: ${n?n.sn:"na"} fragments: ${e}`),r}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,i){let s=this.startPosition;if(s<i&&(s=-1),-1===s||-1===this.lastCurrentTime){const e=null!==this.startTimeOffset,n=e?this.startTimeOffset:t.startTimeOffset;null!==n&&T(n)?(s=i+n,n<0&&(s+=t.totalduration),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Start time offset ${n} found in ${e?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||i:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:t}=this;let i=0;return this.loadedmetadata&&t?i=t.currentTime:this.nextLoadPosition&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,i){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===re)||(this.state=se)}onFragmentOrKeyLoadError(t,i){if(i.chunkMeta&&!i.frag){const t=this.getCurrentContext(i.chunkMeta);t&&(i.frag=t.frag)}const s=i.frag;if(!s||s.type!==t||!this.levels)return;var e;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(e=this.fragCurrent)?void 0:e.url}`);const n=i.details===L.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const r=i.errorAction,{action:h,retryCount:o=0,retryConfig:a}=r||{};if(r&&5===h&&a){this.resetStartWhenNotLoaded(this.levelLastLoaded);const e=ds(a,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${i.details}, retrying loading ${o+1}/${a.maxNumRetry} in ${e}ms`),r.resolved=!0,this.retryDate=self.performance.now()+e,this.state=re}else if(a&&r){if(this.resetFragmentErrors(t),!(o<a.maxNumRetry))return void I.warn(`${i.details} reached or exceeded max retry (${o})`);n||3===h||(r.resolved=!0)}else this.state=2===(null==r?void 0:r.action)?de:ce;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===oe||this.state===ae){const i=t.frag,s=t.parent,e=this.getFwdBufferInfo(this.mediaBuffer,s),n=e&&e.len>.5;n&&this.reduceMaxBufferLength(e.len,(null==i?void 0:i.duration)||10);const r=!n;return r&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),i&&(this.fragmentTracker.removeFragment(i),this.nextLoadPosition=i.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(t){t===Ri&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ie&&(this.state=se)}afterBufferFlushed(t,i,s){if(!t)return;const e=js.getBuffered(t);this.fragmentTracker.detectEvictedFragments(i,e,s),this.state===le&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=se}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const i=t?t.details:null;null!=i&&i.live?(this.startPosition=-1,this.setStartPosition(i,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,i,s,e){var n;const r=s.details;if(r){if(!Object.keys(t.elementaryStreams).reduce(((i,n)=>{const h=t.elementaryStreams[n];if(h){const o=h.endPTS-h.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),i||!1;const a=e?0:ns(r,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(A.LEVEL_PTS_UPDATED,{details:r,level:s,drift:a,type:n,frag:t,start:h.startPTS,end:h.endPTS}),!0}return i}),!1)&&null===(null==(n=this.transmuxer)?void 0:n.error)){const i=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(i.message),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=ae,this.hls.trigger(A.FRAG_PARSED,{frag:t,part:i})}else this.warn("level.details undefined")}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 i=this._state;i!==t&&(this._state=t,this.log(`${i}->${t}`))}get state(){return this._state}}class ve{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:i}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,i){const s=new Uint8Array(i);let e=0;for(let i=0;i<t.length;i++){const n=t[i];s.set(n,e),e+=n.length}return s}(t,i),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function pe(t="",i=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:i,sequenceNumber:-1,samples:[],dropped:0}}class ge{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,i,s,e){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,i){return!1}appendFrame(t,i,s){}demux(t,i){this.cachedData&&(t=Kt(this.cachedData,t),this.cachedData=null);let s,e=ct(t,0),n=e?e.length:0;const r=this._audioTrack,h=this._id3Track,o=e?ft(e):void 0,a=t.length;for((null===this.basePTS||0===this.frameIndex&&T(o))&&(this.basePTS=me(o,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),e&&e.length>0&&h.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:e,type:Hi,duration:Number.POSITIVE_INFINITY});n<a;){if(this.canParse(t,n)){const i=this.appendFrame(r,t,n);i?(this.frameIndex++,this.lastPTS=i.sample.pts,n+=i.length,s=n):n=a}else dt(t,n)?(e=ct(t,n),h.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:e,type:Hi,duration:Number.POSITIVE_INFINITY}),n+=e.length,s=n):n++;if(n===a&&s!==a){const i=ot(t,s);this.cachedData=this.cachedData?Kt(this.cachedData,i):i}}return{audioTrack:r,videoTrack:pe(),id3Track:h,textTrack:pe()}}demuxSampleAes(t,i,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const i=this.cachedData;return i&&(this.cachedData=null,this.demux(i,0)),{audioTrack:this._audioTrack,videoTrack:pe(),id3Track:this._id3Track,textTrack:pe()}}destroy(){}}const me=(t,i,s)=>T(t)?90*t:9e4*i+(s?9e4*s.baseTime/s.timescale:0);function ye(t,i){return 255===t[i]&&240==(246&t[i+1])}function we(t,i){return 1&t[i+1]?7:9}function be(t,i){return(3&t[i+3])<<11|t[i+4]<<3|(224&t[i+5])>>>5}function ke(t,i){return i+1<t.length&&ye(t,i)}function Se(t,i){if(ke(t,i)){const s=we(t,i);if(i+s>=t.length)return!1;const e=be(t,i);if(e<=s)return!1;const n=i+e;return n===t.length||ke(t,n)}return!1}function Te(t,i,s,e,n){if(!t.samplerate){const r=function(t,i,s,e){let n,r,h,o;const a=navigator.userAgent.toLowerCase(),l=e,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=1+((192&i[s+2])>>>6);const u=(60&i[s+2])>>>2;if(!(u>c.length-1))return h=(1&i[s+2])<<2,h|=(192&i[s+3])>>>6,I.log(`manifest codec:${e}, ADTS type:${n}, samplingIndex:${u}`),/firefox/i.test(a)?u>=6?(n=5,o=new Array(4),r=u-3):(n=2,o=new Array(2),r=u):-1!==a.indexOf("android")?(n=2,o=new Array(2),r=u):(n=5,o=new Array(4),e&&(-1!==e.indexOf("mp4a.40.29")||-1!==e.indexOf("mp4a.40.5"))||!e&&u>=6?r=u-3:((e&&-1!==e.indexOf("mp4a.40.2")&&(u>=6&&1===h||/vivaldi/i.test(a))||!e&&1===h)&&(n=2,o=new Array(2)),r=u)),o[0]=n<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=h<<3,5===n&&(o[1]|=(14&r)>>1,o[2]=(1&r)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[u],channelCount:h,codec:"mp4a.40."+n,manifestCodec:l};{const i=new Error(`invalid ADTS sampling index:${u}`);t.emit(A.ERROR,A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:i,reason:i.message})}}(i,s,e,n);if(!r)return;t.config=r.config,t.samplerate=r.samplerate,t.channelCount=r.channelCount,t.codec=r.codec,t.manifestCodec=r.manifestCodec,I.log(`parsed codec:${t.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function $e(t){return 9216e4/t}function Ee(t,i,s,e,n){const r=e+n*$e(t.samplerate),h=function(t,i){const s=we(t,i);if(i+s<=t.length){const e=be(t,i)-s;if(e>0)return{headerLength:s,frameLength:e}}}(i,s);let o;if(h){const{frameLength:e,headerLength:n}=h,a=n+e,l=Math.max(0,s+a-i.length);l?(o=new Uint8Array(a-n),o.set(i.subarray(s+n,i.length),0)):o=i.subarray(s+n,s+a);const c={unit:o,pts:r};return l||t.samples.push(c),{sample:c,length:a,missing:l}}const a=i.length-s;return o=new Uint8Array(a),o.set(i.subarray(s,i.length),0),{sample:{unit:o,pts:r},length:a,missing:-1}}let Ae=null;const Me=[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],Le=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],xe=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],De=[0,1,1,4];function Ce(t,i,s,e,n){if(s+24>i.length)return;const r=Ie(i,s);if(r&&s+r.frameLength<=i.length){const h=e+n*(9e4*r.samplesPerFrame/r.sampleRate),o={unit:i.subarray(s,s+r.frameLength),pts:h,dts:h};return t.config=[],t.channelCount=r.channelCount,t.samplerate=r.sampleRate,t.samples.push(o),{sample:o,length:r.frameLength,missing:0}}}function Ie(t,i){const s=t[i+1]>>3&3,e=t[i+1]>>1&3,n=t[i+2]>>4&15,r=t[i+2]>>2&3;if(1!==s&&0!==n&&15!==n&&3!==r){const h=t[i+3]>>6,o=1e3*Me[14*(3===s?3-e:3===e?3:4)+n-1],a=Le[3*(3===s?0:2===s?1:2)+r],l=3===h?1:2,c=xe[s][e],u=De[e],d=8*c*u,f=Math.floor(c*o/a+(t[i+2]>>1&1))*u;if(null===Ae){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ae=t?parseInt(t[1]):0}return!!Ae&&Ae<=87&&2===e&&o>=224e3&&0===h&&(t[i+3]=128|t[i+3]),{sampleRate:a,channelCount:l,frameLength:f,samplesPerFrame:d}}}function Re(t,i){return!(255!==t[i]||224&~t[i+1]||!(6&t[i+1]))}function Pe(t,i){return i+1<t.length&&Re(t,i)}function Oe(t,i){if(i+1<t.length&&Re(t,i)){const s=4,e=Ie(t,i);let n=s;null!=e&&e.frameLength&&(n=e.frameLength);const r=i+n;return r===t.length||Pe(t,r)}return!1}const Ne=/\/emsg[-/]ID3/i,Ue=(t,i)=>{let s=0,e=5;i+=e;const n=new Uint32Array(1),r=new Uint32Array(1),h=new Uint8Array(1);for(;e>0;){h[0]=t[i];const o=Math.min(e,8),a=8-o;r[0]=4278190080>>>24+a<<a,n[0]=(h[0]&r[0])>>a,s=s?s<<o|n[0]:n[0],i+=1,e-=o}return s};function Fe(t,i,s,e,n){if(s+8>i.length)return-1;if(11!==i[s]||119!==i[s+1])return-1;const r=i[s+4]>>6;if(r>=3)return-1;const h=[48e3,44100,32e3][r],o=63&i[s+4],a=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+r];if(s+a>i.length)return-1;const l=i[s+6]>>5;let c=0;2===l?c+=2:(1&l&&1!==l&&(c+=2),4&l&&(c+=2));const u=(i[s+6]<<8|i[s+7])>>12-c&1,d=[2,1,2,3,3,4,4,5][l]+u,f=7&i[s+5],v=new Uint8Array([r<<6|i[s+5]>>3<<1|f>>2,(3&f)<<6|l<<3|u<<2|o>>4,o<<4&224]),p=e+n*(1536/h*9e4),g=i.subarray(s,s+a);return t.config=v,t.channelCount=d,t.samplerate=h,t.samples.push({unit:g,pts:p}),a}class Be{constructor(){this.VideoSample=null}createVideoSample(t,i,s,e){return{key:t,frame:!1,pts:i,dts:s,units:[],debug:e,length:0}}getLastNalUnit(t){var i;let s,e=this.VideoSample;if(e&&0!==e.units.length||(e=t[t.length-1]),null!=(i=e)&&i.units){const t=e.units;s=t[t.length-1]}return s}pushAccessUnit(t,i){if(t.units.length&&t.frame){if(void 0===t.pts){const s=i.samples,e=s.length;if(!e)return void i.dropped++;{const i=s[e-1];t.pts=i.pts,t.dts=i.dts}}i.samples.push(t)}t.debug.length&&I.log(t.pts+"/"+t.dts+":"+t.debug)}}class je{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,i=this.bytesAvailable,s=t.byteLength-i,e=new Uint8Array(4),n=Math.min(4,i);if(0===n)throw new Error("no bytes available");e.set(t.subarray(s,s+n)),this.word=new DataView(e.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}skipBits(t){let i;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(i=(t-=this.bitsAvailable)>>3,t-=i<<3,this.bytesAvailable-=i,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let i=Math.min(this.bitsAvailable,t);const s=this.word>>>32-i;if(t>32&&I.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=i,this.bitsAvailable>0)this.word<<=i;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return i=t-i,i>0&&this.bitsAvailable?s<<i|this.readBits(i):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>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 i,s=8,e=8;for(let n=0;n<t;n++)0!==e&&(i=this.readEG(),e=(s+i+256)%256),s=0===e?s:e}readSPS(){let t,i,s,e=0,n=0,r=0,h=0;const o=this.readUByte.bind(this),a=this.readBits.bind(this),l=this.readUEG.bind(this),c=this.readBoolean.bind(this),u=this.skipBits.bind(this),d=this.skipEG.bind(this),f=this.skipUEG.bind(this),v=this.skipScalingList.bind(this);o();const p=o();if(a(5),u(3),o(),f(),100===p||110===p||122===p||244===p||44===p||83===p||86===p||118===p||128===p){const t=l();if(3===t&&u(1),f(),f(),u(1),c())for(i=3!==t?8:12,s=0;s<i;s++)c()&&v(s<6?16:64)}f();const g=l();if(0===g)l();else if(1===g)for(u(1),d(),d(),t=l(),s=0;s<t;s++)d();f(),u(1);const m=l(),y=l(),w=a(1);0===w&&u(1),u(1),c()&&(e=l(),n=l(),r=l(),h=l());let b=[1,1];if(c()&&c())switch(o()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[o()<<8|o(),o()<<8|o()]}return{width:Math.ceil(16*(m+1)-2*e-2*n),height:(2-w)*(y+1)*16-(w?2:4)*(r+h),pixelRatio:b}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class _e extends Be{parseAVCPES(t,i,s,e,n){const r=this.parseAVCNALu(t,s.data);let h,o=this.VideoSample,a=!1;s.data=null,o&&r.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),r.forEach((e=>{var r;switch(e.type){case 1:{let i=!1;h=!0;const n=e.data;if(a&&n.length>4){const t=new je(n).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(i=!0)}var l;i&&null!=(l=o)&&l.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=i;break}case 5:h=!0,null!=(r=o)&&r.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:h=!0,Wt(e.data,1,s.pts,i.samples);break;case 7:{var c,u;h=!0,a=!0;const i=e.data,s=new je(i).readSPS();if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(c=t.pixelRatio)?void 0:c[0])!==s.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[i],t.duration=n;const e=i.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let i=e[t].toString(16);i.length<2&&(i="0"+i),r+=i}t.codec=r}break}case 8:h=!0,t.pps=[e.data];break;case 9:h=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:h=!0;break;default:h=!1,o&&(o.debug+="unknown NAL "+e.type+" ")}o&&h&&o.units.push(e)})),e&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,i){const s=i.byteLength;let e=t.naluState||0;const n=e,r=[];let h,o,a,l=0,c=-1,u=0;for(-1===e&&(c=0,u=31&i[0],e=0,l=1);l<s;)if(h=i[l++],e)if(1!==e)if(h)if(1===h){if(o=l-e-1,c>=0){const t={data:i.subarray(c,o),type:u};r.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(n&&l<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),o>0&&(s.data=Kt(s.data,i.subarray(0,o)),s.state=0))}l<s?(a=31&i[l],c=l,u=a,e=0):e=-1}else e=0;else e=3;else e=h?0:2;else e=h?0:1;if(c>=0&&e>=0){const t={data:i.subarray(c,s),type:u,state:e};r.push(t)}if(0===r.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Kt(s.data,i))}return t.naluState=e,r}}class Ge{constructor(t,i,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new te(i,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,i,s){const e=t[i].unit;if(e.length<=16)return;const n=e.subarray(16,e.length-e.length%16),r=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(r).then((n=>{const r=new Uint8Array(n);e.set(r,16),this.decrypter.isSync()||this.decryptAacSamples(t,i+1,s)}))}decryptAacSamples(t,i,s){for(;;i++){if(i>=t.length)return void s();if(!(t[i].unit.length<32||(this.decryptAacSample(t,i,s),this.decrypter.isSync())))return}}getAvcEncryptedData(t){const i=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(i);let e=0;for(let i=32;i<t.length-16;i+=160,e+=16)s.set(t.subarray(i,i+16),e);return s}getAvcDecryptedUnit(t,i){const s=new Uint8Array(i);let e=0;for(let i=32;i<t.length-16;i+=160,e+=16)t.set(s.subarray(e,e+16),i);return t}decryptAvcSample(t,i,s,e,n){const r=Xt(n.data),h=this.getAvcEncryptedData(r);this.decryptBuffer(h.buffer).then((h=>{n.data=this.getAvcDecryptedUnit(r,h),this.decrypter.isSync()||this.decryptAvcSamples(t,i,s+1,e)}))}decryptAvcSamples(t,i,s,e){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;i++,s=0){if(i>=t.length)return void e();const n=t[i].units;for(;!(s>=n.length);s++){const r=n[s];if(!(r.data.length<=48||1!==r.type&&5!==r.type||(this.decryptAvcSample(t,i,s,e,r),this.decrypter.isSync())))return}}}}const He=188;class Ke{constructor(t,i,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=i,this.typeSupported=s,this.videoParser=new _e}static probe(t){const i=Ke.syncOffset(t);return i>0&&I.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const i=t.length;let s=Math.min(940,i-He)+1,e=0;for(;e<s;){let n=!1,r=-1,h=0;for(let o=e;o<i;o+=He){if(71!==t[o]||i-o!==He&&71!==t[o+He]){if(h)return-1;break}if(h++,-1===r&&(r=o,0!==r&&(s=Math.min(r+18612,t.length-He)+1)),n||(n=0===Ve(t,o)),n&&h>1&&(0===r&&h>2||o+He>s))return r}e++}return-1}static createTrack(t,i){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Lt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?i:void 0}}resetInitSegment(t,i,s,e){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ke.createTrack("video"),this._audioTrack=Ke.createTrack("audio",e),this._id3Track=Ke.createTrack("id3"),this._txtTrack=Ke.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=s,this._duration=e}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:i,_id3Track:s}=this;t&&(t.pesData=null),i&&(i.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,i,s=!1,e=!1){let n;s||(this.sampleAes=null);const r=this._videoTrack,h=this._audioTrack,o=this._id3Track,a=this._txtTrack;let l=r.pid,c=r.pesData,u=h.pid,d=o.pid,f=h.pesData,v=o.pesData,p=null,g=this.pmtParsed,m=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=Kt(this.remainderData,t)).length,this.remainderData=null),y<He&&!e)return this.remainderData=t,{audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};const w=Math.max(0,Ke.syncOffset(t));y-=(y-w)%He,y<t.byteLength&&!e&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let b=0;for(let i=w;i<y;i+=He)if(71===t[i]){const e=!!(64&t[i+1]),y=Ve(t,i);let b;if((48&t[i+3])>>4>1){if(b=i+5+t[i+4],b===i+He)continue}else b=i+4;switch(y){case l:e&&(c&&(n=Ye(c))&&this.videoParser.parseAVCPES(r,a,n,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(t.subarray(b,i+He)),c.size+=i+He-b);break;case u:if(e){if(f&&(n=Ye(f)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,n);break;case"mp3":this.parseMPEGPES(h,n);break;case"ac3":this.parseAC3PES(h,n)}f={data:[],size:0}}f&&(f.data.push(t.subarray(b,i+He)),f.size+=i+He-b);break;case d:e&&(v&&(n=Ye(v))&&this.parseID3PES(o,n),v={data:[],size:0}),v&&(v.data.push(t.subarray(b,i+He)),v.size+=i+He-b);break;case 0:e&&(b+=t[b]+1),m=this._pmtId=ze(t,b);break;case m:{e&&(b+=t[b]+1);const n=We(t,b,this.typeSupported,s,this.observer);l=n.videoPid,l>0&&(r.pid=l,r.segmentCodec=n.segmentVideoCodec),u=n.audioPid,u>0&&(h.pid=u,h.segmentCodec=n.segmentAudioCodec),d=n.id3Pid,d>0&&(o.pid=d),null===p||g||(I.warn(`MPEG-TS PMT found at ${i} after unknown PID '${p}'. Backtracking to sync byte @${w} to parse all TS packets.`),p=null,i=w-188),g=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=y}}else b++;b>0&&Xe(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`)),r.pesData=c,h.pesData=f,o.pesData=v;const k={audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};return e&&this.extractRemainingSamples(k),k}flush(){const{remainderData:t}=this;let i;return this.remainderData=null,i=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t){const{audioTrack:i,videoTrack:s,id3Track:e,textTrack:n}=t,r=s.pesData,h=i.pesData,o=e.pesData;let a;if(r&&(a=Ye(r))?(this.videoParser.parseAVCPES(s,n,a,!0,this._duration),s.pesData=null):s.pesData=r,h&&(a=Ye(h))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,a);break;case"mp3":this.parseMPEGPES(i,a);break;case"ac3":this.parseAC3PES(i,a)}i.pesData=null}else null!=h&&h.size&&I.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=h;o&&(a=Ye(o))?(this.parseID3PES(e,a),e.pesData=null):e.pesData=o}demuxSampleAes(t,i,s){const e=this.demux(t,s,!0,!this.config.progressive),n=this.sampleAes=new Ge(this.observer,this.config,i);return this.decrypt(e,n)}decrypt(t,i){return new Promise((s=>{const{audioTrack:e,videoTrack:n}=t;e.samples&&"aac"===e.segmentCodec?i.decryptAacSamples(e.samples,0,(()=>{n.samples?i.decryptAvcSamples(n.samples,0,0,(()=>{s(t)})):s(t)})):n.samples&&i.decryptAvcSamples(n.samples,0,0,(()=>{s(t)}))}))}destroy(){this._duration=0}parseAACPES(t,i){let s=0;const e=this.aacOverFlow;let n,r,h,o=i.data;if(e){this.aacOverFlow=null;const i=e.missing,n=e.sample.unit.byteLength;if(-1===i)o=Kt(e.sample.unit,o);else{const r=n-i;e.sample.unit.set(o.subarray(0,i),r),t.samples.push(e.sample),s=e.missing}}for(n=s,r=o.length;n<r-1&&!ke(o,n);n++);if(n!==s){let t;const i=n<r-1;if(t=i?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",Xe(this.observer,new Error(t),i),!i)return}if(Te(t,this.observer,o,n,this.audioCodec),void 0!==i.pts)h=i.pts;else{if(!e)return void I.warn("[tsdemuxer]: AAC PES unknown PTS");{const i=$e(t.samplerate);h=e.sample.pts+i}}let a,l=0;for(;n<r;){if(a=Ee(t,o,n,h,l),n+=a.length,a.missing){this.aacOverFlow=a;break}for(l++;n<r-1&&!ke(o,n);n++);}}parseMPEGPES(t,i){const s=i.data,e=s.length;let n=0,r=0;const h=i.pts;if(void 0!==h)for(;r<e;)if(Pe(s,r)){const i=Ce(t,s,r,h,n);if(!i)break;r+=i.length,n++}else r++;else I.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,i){{const s=i.data,e=i.pts;if(void 0===e)return void I.warn("[tsdemuxer]: AC3 PES unknown PTS");const n=s.length;let r,h=0,o=0;for(;o<n&&(r=Fe(t,s,o,e,h++))>0;)o+=r}}parseID3PES(t,i){if(void 0===i.pts)return void I.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=S({},i,{type:this._videoTrack?Ki:Hi,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function Ve(t,i){return((31&t[i+1])<<8)+t[i+2]}function ze(t,i){return(31&t[i+10])<<8|t[i+11]}function We(t,i,s,e,n){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=i+3+((15&t[i+1])<<8|t[i+2])-4;for(i+=12+((15&t[i+10])<<8|t[i+11]);i<h;){const h=Ve(t,i),o=(15&t[i+3])<<8|t[i+4];switch(t[i]){case 207:if(!e){qe("ADTS AAC");break}case 15:-1===r.audioPid&&(r.audioPid=h);break;case 21:-1===r.id3Pid&&(r.id3Pid=h);break;case 219:if(!e){qe("H.264");break}case 27:-1===r.videoPid&&(r.videoPid=h,r.segmentVideoCodec="avc");break;case 3:case 4:s.mpeg||s.mp3?-1===r.audioPid&&(r.audioPid=h,r.segmentAudioCodec="mp3"):I.log("MPEG audio found, not supported in this browser");break;case 193:if(!e){qe("AC-3");break}case 129:s.ac3?-1===r.audioPid&&(r.audioPid=h,r.segmentAudioCodec="ac3"):I.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===r.audioPid&&o>0){let e=i+5,n=o;for(;n>2;){106===t[e]&&(!0!==s.ac3?I.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=h,r.segmentAudioCodec="ac3"));const i=t[e+1]+2;e+=i,n-=i}}break;case 194:case 135:return Xe(n,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return Xe(n,new Error("Unsupported HEVC in M2TS found")),r}i+=o+5}return r}function Xe(t,i,s){I.warn(`parsing error: ${i.message}`),t.emit(A.ERROR,A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:i,reason:i.message})}function qe(t){I.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ye(t){let i,s,e,n,r,h=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Kt(o[0],o[1]),o.splice(1,1);if(i=o[0],1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>t.size-6)return null;const a=i[7];192&a&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&a?(r=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-r>54e5&&(I.warn(`${Math.round((n-r)/9e4)}s delta between PTS and DTS, align them`),n=r)):r=n),e=i[8];let l=e+9;if(t.size<=l)return null;t.size-=l;const c=new Uint8Array(t.size);for(let t=0,s=o.length;t<s;t++){i=o[t];let s=i.byteLength;if(l){if(l>s){l-=s;continue}i=i.subarray(l),s-=l,l=0}c.set(i,h),h+=s}return s&&(s-=e+3),{data:c,pts:n,dts:r,len:s}}return null}class Je{static getSilentFrame(t,i){if("mp4a.40.2"===t){if(1===i)return new Uint8Array([0,200,0,128,35,128]);if(2===i)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===i)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===i)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===i)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===i)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===i)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===i)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===i)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 Qe=Math.pow(2,32)-1;class Ze{static init(){let t;for(t in Ze.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:[]},Ze.types)Ze.types.hasOwnProperty(t)&&(Ze.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const i=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]);Ze.HDLR_TYPES={video:i,audio:s};const e=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);Ze.STTS=Ze.STSC=Ze.STCO=n,Ze.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ze.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ze.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ze.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const r=new Uint8Array([105,115,111,109]),h=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Ze.FTYP=Ze.box(Ze.types.ftyp,r,o,r,h),Ze.DINF=Ze.box(Ze.types.dinf,Ze.box(Ze.types.dref,e))}static box(t,...i){let s=8,e=i.length;const n=e;for(;e--;)s+=i[e].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=255&s,r.set(t,4),e=0,s=8;e<n;e++)r.set(i[e],s),s+=i[e].byteLength;return r}static hdlr(t){return Ze.box(Ze.types.hdlr,Ze.HDLR_TYPES[t])}static mdat(t){return Ze.box(Ze.types.mdat,t)}static mdhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),e=Math.floor(i%(Qe+1));return Ze.box(Ze.types.mdhd,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,e>>24,e>>16&255,e>>8&255,255&e,85,196,0,0]))}static mdia(t){return Ze.box(Ze.types.mdia,Ze.mdhd(t.timescale,t.duration),Ze.hdlr(t.type),Ze.minf(t))}static mfhd(t){return Ze.box(Ze.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return Ze.box(Ze.types.minf,"audio"===t.type?Ze.box(Ze.types.smhd,Ze.SMHD):Ze.box(Ze.types.vmhd,Ze.VMHD),Ze.DINF,Ze.stbl(t))}static moof(t,i,s){return Ze.box(Ze.types.moof,Ze.mfhd(t),Ze.traf(s,i))}static moov(t){let i=t.length;const s=[];for(;i--;)s[i]=Ze.trak(t[i]);return Ze.box.apply(null,[Ze.types.moov,Ze.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(Ze.mvex(t)))}static mvex(t){let i=t.length;const s=[];for(;i--;)s[i]=Ze.trex(t[i]);return Ze.box.apply(null,[Ze.types.mvex,...s])}static mvhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),e=Math.floor(i%(Qe+1)),n=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,e>>24,e>>16&255,e>>8&255,255&e,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 Ze.box(Ze.types.mvhd,n)}static sdtp(t){const i=t.samples||[],s=new Uint8Array(4+i.length);let e,n;for(e=0;e<i.length;e++)n=i[e].flags,s[e+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return Ze.box(Ze.types.sdtp,s)}static stbl(t){return Ze.box(Ze.types.stbl,Ze.stsd(t),Ze.box(Ze.types.stts,Ze.STTS),Ze.box(Ze.types.stsc,Ze.STSC),Ze.box(Ze.types.stsz,Ze.STSZ),Ze.box(Ze.types.stco,Ze.STCO))}static avc1(t){let i,s,e,n=[],r=[];for(i=0;i<t.sps.length;i++)s=t.sps[i],e=s.byteLength,n.push(e>>>8&255),n.push(255&e),n=n.concat(Array.prototype.slice.call(s));for(i=0;i<t.pps.length;i++)s=t.pps[i],e=s.byteLength,r.push(e>>>8&255),r.push(255&e),r=r.concat(Array.prototype.slice.call(s));const h=Ze.box(Ze.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),o=t.width,a=t.height,l=t.pixelRatio[0],c=t.pixelRatio[1];return Ze.box(Ze.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,a>>8&255,255&a,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]),h,Ze.box(Ze.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ze.box(Ze.types.pasp,new Uint8Array([l>>24,l>>16&255,l>>8&255,255&l,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const i=t.config.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([i]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const i=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,i>>8&255,255&i,0,0])}static mp4a(t){return Ze.box(Ze.types.mp4a,Ze.audioStsd(t),Ze.box(Ze.types.esds,Ze.esds(t)))}static mp3(t){return Ze.box(Ze.types[".mp3"],Ze.audioStsd(t))}static ac3(t){return Ze.box(Ze.types["ac-3"],Ze.audioStsd(t),Ze.box(Ze.types.dac3,t.config))}static stsd(t){return Ze.box(Ze.types.stsd,Ze.STSD,"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?Ze.mp3(t):"ac3"===t.segmentCodec?Ze.ac3(t):Ze.mp4a(t):Ze.avc1(t))}static tkhd(t){const i=t.id,s=t.duration*t.timescale,e=t.width,n=t.height,r=Math.floor(s/(Qe+1)),h=Math.floor(s%(Qe+1));return Ze.box(Ze.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,h>>24,h>>16&255,h>>8&255,255&h,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,e>>8&255,255&e,0,0,n>>8&255,255&n,0,0]))}static traf(t,i){const s=Ze.sdtp(t),e=t.id,n=Math.floor(i/(Qe+1)),r=Math.floor(i%(Qe+1));return Ze.box(Ze.types.traf,Ze.box(Ze.types.tfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e])),Ze.box(Ze.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r])),Ze.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,Ze.box(Ze.types.trak,Ze.tkhd(t),Ze.mdia(t))}static trex(t){const i=t.id;return Ze.box(Ze.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,i){const s=t.samples||[],e=s.length,n=12+16*e,r=new Uint8Array(n);let h,o,a,l,c,u;for(r.set(["video"===t.type?1:0,0,15,1,e>>>24&255,e>>>16&255,e>>>8&255,255&e,(i+=8+n)>>>24&255,i>>>16&255,i>>>8&255,255&i],0),h=0;h<e;h++)o=s[h],a=o.duration,l=o.size,c=o.flags,u=o.cts,r.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,l>>>24&255,l>>>16&255,l>>>8&255,255&l,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*h);return Ze.box(Ze.types.trun,r)}static initSegment(t){Ze.types||Ze.init();const i=Ze.moov(t);return Kt(Ze.FTYP,i)}}Ze.types=void 0,Ze.HDLR_TYPES=void 0,Ze.STTS=void 0,Ze.STSC=void 0,Ze.STCO=void 0,Ze.STSZ=void 0,Ze.VMHD=void 0,Ze.SMHD=void 0,Ze.STSD=void 0,Ze.FTYP=void 0,Ze.DINF=void 0;function tn(t,i,s=1,e=!1){const n=t*i*s;return e?Math.round(n):n}function sn(t,i=!1){return tn(t,1e3,1/9e4,i)}let en,nn=null,rn=null;class hn{constructor(t,i,s,e=""){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=i,this.typeSupported=s,this.ISGenerated=!1,null===nn){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);nn=t?parseInt(t[1]):0}if(null===rn){const t=navigator.userAgent.match(/Safari\/(\d+)/i);rn=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){I.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){I.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){I.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let i=!1;const s=t[0].pts,e=t.reduce(((t,e)=>{let n=e.pts,r=n-t;return r<-4294967296&&(i=!0,n=on(n,s),r=n-t),r>0?t:n}),s);return i&&I.debug("PTS rollover detected"),e}remux(t,i,s,e,n,r,h,o){let a,l,c,u,d,f,v=n,p=n;const g=i.pid>-1,m=i.samples.length,y=t.samples.length>0,w=h&&m>0||m>1;if((!(t.pid>-1)||y)&&(!g||w)||this.ISGenerated||h){if(this.ISGenerated){var b,k,S,T;const t=this.videoTrackConfig;!t||i.width===t.width&&i.height===t.height&&(null==(b=i.pixelRatio)?void 0:b[0])===(null==(k=t.pixelRatio)?void 0:k[0])&&(null==(S=i.pixelRatio)?void 0:S[1])===(null==(T=t.pixelRatio)?void 0:T[1])||this.resetInitSegment()}else c=this.generateIS(t,i,n,r);const s=this.isVideoContiguous;let e,h=-1;if(w&&(h=function(t){for(let i=0;i<t.length;i++)if(t[i].key)return i;return-1}(i.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,h>0){I.warn(`[mp4-remuxer]: Dropped ${h} out of ${m} video samples due to a missing keyframe`);const t=this.getVideoStartPts(i.samples);i.samples=i.samples.slice(h),i.dropped+=h,p+=(i.samples[0].pts-t)/i.inputTimeScale,e=p}else-1===h&&(I.warn(`[mp4-remuxer]: No keyframe found out of ${m} video samples`),f=!1);if(this.ISGenerated){if(y&&w){const s=this.getVideoStartPts(i.samples),e=(on(t.samples[0].pts,s)-s)/i.inputTimeScale;v+=Math.max(0,e),p+=Math.max(0,-e)}if(y){if(t.samplerate||(I.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(t,i,n,r)),l=this.remuxAudio(t,v,this.isAudioContiguous,r,g||w||o===Ri?p:void 0),w){const e=l?l.endPTS-l.startPTS:0;i.inputTimeScale||(I.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(t,i,n,r)),a=this.remuxVideo(i,p,s,e)}}else w&&(a=this.remuxVideo(i,p,s,0));a&&(a.firstKeyFrame=h,a.independent=-1!==h,a.firstKeyFramePTS=e)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(d=an(s,n,this._initPTS,this._initDTS)),e.samples.length&&(u=ln(e,n,this._initPTS))),{audio:l,video:a,initSegment:c,independent:f,text:u,id3:d}}generateIS(t,i,s,e){const n=t.samples,r=i.samples,h=this.typeSupported,o={},a=this._initPTS;let l,c,u,d=!a||e,f="audio/mp4";if(d&&(l=c=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):Ze.initSegment([t]),metadata:{channelCount:t.channelCount}},d&&(u=t.inputTimeScale,a&&u===a.timescale?d=!1:l=c=n[0].pts-Math.round(u*s))}if(i.sps&&i.pps&&r.length){if(i.timescale=i.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:i.codec,initSegment:Ze.initSegment([i]),metadata:{width:i.width,height:i.height}},d)if(u=i.inputTimeScale,a&&u===a.timescale)d=!1;else{const t=this.getVideoStartPts(r),i=Math.round(u*s);c=Math.min(c,on(r[0].dts,t)-i),l=Math.min(l,t-i)}this.videoTrackConfig={width:i.width,height:i.height,pixelRatio:i.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:l,timescale:u},this._initDTS={baseTime:c,timescale:u}):l=u=void 0,{tracks:o,initPTS:l,timescale:u}}remuxVideo(t,i,s,e){const n=t.inputTimeScale,r=t.samples,h=[],o=r.length,a=this._initPTS;let l,c,u=this.nextAvcDts,d=8,f=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,g=!1;if(!s||null===u){const t=i*n,e=r[0].pts-on(r[0].dts,r[0].pts);nn&&null!==u&&Math.abs(t-e-u)<15e3?s=!0:u=t-e}const m=a.baseTime*n/a.timescale;for(let t=0;t<o;t++){const i=r[t];i.pts=on(i.pts-m,u),i.dts=on(i.dts-m,u),i.dts<r[t>0?t-1:t].dts&&(g=!0)}g&&r.sort((function(t,i){return t.dts-i.dts||t.pts-i.pts})),l=r[0].dts,c=r[r.length-1].dts;const y=c-l,w=y?Math.round(y/(o-1)):f||t.inputTimeScale/30;if(s){const t=l-u,s=t>w,e=t<-1;if((s||e)&&(I.warn(s?`AVC: ${sn(t,!0)} ms (${t}dts) hole between fragments detected at ${i.toFixed(3)}`:`AVC: ${sn(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${i.toFixed(3)}`),!e||u>=r[0].pts||nn)){l=u;const i=r[0].pts-t;if(s)r[0].dts=l,r[0].pts=i;else for(let s=0;s<r.length&&!(r[s].dts>i);s++)r[s].dts-=t,r[s].pts-=t;I.log(`Video: Initial PTS/DTS adjusted: ${sn(i,!0)}/${sn(l,!0)}, delta: ${sn(t,!0)} ms`)}}l=Math.max(0,l);let b=0,k=0,T=l;for(let t=0;t<o;t++){const i=r[t],s=i.units,e=s.length;let n=0;for(let t=0;t<e;t++)n+=s[t].data.length;k+=n,b+=e,i.length=n,i.dts<T?(i.dts=T,T+=w/4|0||1):T=i.dts,v=Math.min(i.pts,v),p=Math.max(i.pts,p)}c=r[o-1].dts;const $=k+4*b+8;let E;try{E=new Uint8Array($)}catch(t){return void this.observer.emit(A.ERROR,A.ERROR,{type:M.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:$,reason:`fail allocating video mdat ${$}`})}const x=new DataView(E.buffer);x.setUint32(0,$),E.set(Ze.types.mdat,4);let D=!1,C=Number.POSITIVE_INFINITY,R=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const i=r[t],s=i.units;let a,l=0;for(let t=0,i=s.length;t<i;t++){const i=s[t],e=i.data,n=i.data.byteLength;x.setUint32(d,n),d+=4,E.set(e,d),d+=n,l+=4+n}if(t<o-1)f=r[t+1].dts-i.dts,a=r[t+1].pts-i.pts;else{const s=this.config,h=t>0?i.dts-r[t-1].dts:w;if(a=t>0?i.pts-r[t-1].pts:w,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*n),r=(e?v+e*n:this.nextAudioPts)-i.pts;r>t?(f=r-h,f<0?f=h:D=!0,I.log(`[mp4-remuxer]: It is approximately ${r/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=h}else f=h}const c=Math.round(i.pts-i.dts);C=Math.min(C,f),P=Math.max(P,f),R=Math.min(R,a),O=Math.max(O,a),h.push(new cn(i.key,f,l,c))}if(h.length)if(nn){if(nn<70){const t=h[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(rn&&O-R<P-C&&w/P<.025&&0===h[0].cts){I.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=l;for(let i=0,s=h.length;i<s;i++){const e=t+h[i].duration;h[i].duration=i<s-1?e+h[i+1].cts-(t+h[i].cts):i?h[i-1].duration:w,h[i].cts=0,t=e}}f=D||!f?w:f,this.nextAvcDts=u=c+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const N={data1:Ze.moof(t.sequenceNumber++,l,S({},t,{samples:h})),data2:E,startPTS:v/n,endPTS:(p+f)/n,startDTS:l/n,endDTS:u/n,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,i,s,e,n){const r=t.inputTimeScale,h=r/(t.samplerate?t.samplerate:r),o=this.getSamplesPerFrame(t),a=o*h,l=this._initPTS,c="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],d=void 0!==n;let f=t.samples,v=c?0:8,p=this.nextAudioPts||-1;const g=i*r,m=l.baseTime*r/l.timescale;if(this.isAudioContiguous=s=s||f.length&&p>0&&(e&&Math.abs(g-p)<9e3||Math.abs(on(f[0].pts-m,g)-p)<20*a),f.forEach((function(t){t.pts=on(t.pts-m,g)})),!s||p<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;p=0===n?0:e&&!d?Math.max(0,g):f[0].pts}if("aac"===t.segmentCodec){const i=this.config.maxAudioFramesDrift;for(let s=0,e=p;s<f.length;s++){const n=f[s],h=n.pts,o=h-e,l=Math.abs(1e3*o/r);if(o<=-i*a&&d)0===s&&(I.warn(`Audio frame @ ${(h/r).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/r)} ms.`),this.nextAudioPts=p=e=h);else if(o>=i*a&&l<1e4&&d){let i=Math.round(o/a);e=h-i*a,e<0&&(i--,e+=a),0===s&&(this.nextAudioPts=p=e),I.warn(`[mp4-remuxer]: Injecting ${i} audio frame @ ${(e/r).toFixed(3)}s due to ${Math.round(1e3*o/r)} ms gap.`);for(let r=0;r<i;r++){const i=Math.max(e,0);let r=Je.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);r||(I.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),r=n.unit.subarray()),f.splice(s,0,{unit:r,pts:i}),e+=a,s++}}n.pts=e,e+=a}}let y,w=null,b=null,k=0,T=f.length;for(;T--;)k+=f[T].unit.byteLength;for(let i=0,e=f.length;i<e;i++){const e=f[i],n=e.unit;let r=e.pts;if(null!==b)u[i-1].duration=Math.round((r-b)/h);else{if(s&&"aac"===t.segmentCodec&&(r=p),w=r,!(k>0))return;k+=v;try{y=new Uint8Array(k)}catch(t){return void this.observer.emit(A.ERROR,A.ERROR,{type:M.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:`fail allocating audio mdat ${k}`})}c||(new DataView(y.buffer).setUint32(0,k),y.set(Ze.types.mdat,4))}y.set(n,v);const a=n.byteLength;v+=a,u.push(new cn(!0,o,a,0)),b=r}const $=u.length;if(!$)return;this.nextAudioPts=p=b+h*u[u.length-1].duration;const E=c?new Uint8Array(0):Ze.moof(t.sequenceNumber++,w/h,S({},t,{samples:u}));t.samples=[];const x=w/r,D=p/r,C={data1:E,data2:y,startPTS:x,endPTS:D,startDTS:x,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:$};return this.isAudioContiguous=!0,C}remuxEmptyAudio(t,i,s,e){const n=t.inputTimeScale,r=this.nextAudioPts,h=this._initDTS,o=9e4*h.baseTime/h.timescale,a=(null!==r?r:e.startDTS*n)+o,l=n/(t.samplerate?t.samplerate:n)*1024,c=Math.ceil((e.endDTS*n+o-a)/l),u=Je.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(I.warn("[mp4-remuxer]: remux empty Audio"),!u)return void I.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const d=[];for(let t=0;t<c;t++){const i=a+t*l;d.push({unit:u,pts:i,dts:i})}return t.samples=d,this.remuxAudio(t,i,s,!1)}}function on(t,i){let s;if(null===i)return t;for(s=i<t?-8589934592:8589934592;Math.abs(t-i)>4294967296;)t+=s;return t}function an(t,i,s,e){const n=t.samples.length;if(!n)return;const r=t.inputTimeScale;for(let h=0;h<n;h++){const n=t.samples[h];n.pts=on(n.pts-s.baseTime*r/s.timescale,i*r)/r,n.dts=on(n.dts-e.baseTime*r/e.timescale,i*r)/r}const h=t.samples;return t.samples=[],{samples:h}}function ln(t,i,s){const e=t.samples.length;if(!e)return;const n=t.inputTimeScale;for(let r=0;r<e;r++){const e=t.samples[r];e.pts=on(e.pts-s.baseTime*n/s.timescale,i*n)/n}t.samples.sort(((t,i)=>t.pts-i.pts));const r=t.samples;return t.samples=[],{samples:r}}class cn{constructor(t,i,s,e){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=i,this.size=s,this.cts=e,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function un(t,i){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(i===B){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s)return fi(s,!1);const t="mp4a.40.5";return I.info(`Parsed audio codec "${s}" or audio object type not handled. Using "${t}"`),t}return I.warn(`Unhandled video codec "${s}"`),"hvc1"===s||"hev1"===s?"hvc1.1.6.L120.90":"av01"===s?"av01.0.04M.08":"avc1.42e01e"}try{en=self.performance.now.bind(self.performance)}catch(t){I.debug("Unable to use Performance API on this environment"),en=null==X?void 0:X.Date.now}const dn=[{demux:class{constructor(t,i){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=i}resetTimeStamp(){}resetInitSegment(t,i,s,e){const n=this.videoTrack=pe("video",1),r=this.audioTrack=pe("audio",1),h=this.txtTrack=pe("text",1);if(this.id3Track=pe("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Ut(t);if(o.video){const{id:t,timescale:i,codec:s}=o.video;n.id=t,n.timescale=h.timescale=i,n.codec=s}if(o.audio){const{id:t,timescale:i,codec:s}=o.audio;r.id=t,r.timescale=i,r.codec=s}h.id=Lt.text,n.sampleDuration=0,n.duration=r.duration=e}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const i=t.byteLength;for(let s=0;s<i;){const e=Ct(t,s);if(e>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=e>1?s+e:i}return!1}(t)}demux(t,i){this.timeOffset=i;let s=t;const e=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Kt(this.remainderData,t));const i=function(t){const i={valid:null,remainder:null},s=Ot(t,["moof"]);if(s.length<2)return i.remainder=t,i;const e=s[s.length-1];return i.valid=ot(t,0,e.byteOffset-8),i.remainder=ot(t,e.byteOffset-8),i}(s);this.remainderData=i.remainder,e.samples=i.valid||new Uint8Array}else e.samples=s;const r=this.extractID3Track(e,i);return n.samples=Vt(i,e),{videoTrack:e,audioTrack:this.audioTrack,id3Track:r,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,i=this.videoTrack,s=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const e=this.extractID3Track(i,this.timeOffset);return s.samples=Vt(t,i),{videoTrack:i,audioTrack:pe(),id3Track:e,textTrack:pe()}}extractID3Track(t,i){const s=this.id3Track;if(t.samples.length){const e=Ot(t.samples,["emsg"]);e&&e.forEach((t=>{const e=function(t){const i=t[0];let s="",e="",n=0,r=0,h=0,o=0,a=0,l=0;if(0===i){for(;"\0"!==xt(t.subarray(l,l+1));)s+=xt(t.subarray(l,l+1)),l+=1;for(s+=xt(t.subarray(l,l+1)),l+=1;"\0"!==xt(t.subarray(l,l+1));)e+=xt(t.subarray(l,l+1)),l+=1;e+=xt(t.subarray(l,l+1)),l+=1,n=Ct(t,12),r=Ct(t,16),o=Ct(t,20),a=Ct(t,24),l=28}else if(1===i){l+=4,n=Ct(t,l),l+=4;const i=Ct(t,l);l+=4;const r=Ct(t,l);for(l+=4,h=2**32*i+r,$(h)||(h=Number.MAX_SAFE_INTEGER,I.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ct(t,l),l+=4,a=Ct(t,l),l+=4;"\0"!==xt(t.subarray(l,l+1));)s+=xt(t.subarray(l,l+1)),l+=1;for(s+=xt(t.subarray(l,l+1)),l+=1;"\0"!==xt(t.subarray(l,l+1));)e+=xt(t.subarray(l,l+1)),l+=1;e+=xt(t.subarray(l,l+1)),l+=1}return{schemeIdUri:s,value:e,timeScale:n,presentationTime:h,presentationTimeDelta:r,eventDuration:o,id:a,payload:t.subarray(l,t.byteLength)}}(t);if(Ne.test(e.schemeIdUri)){const t=T(e.presentationTime)?e.presentationTime/e.timeScale:i+e.presentationTimeDelta/e.timeScale;let n=4294967295===e.eventDuration?Number.POSITIVE_INFINITY:e.eventDuration/e.timeScale;n<=.001&&(n=Number.POSITIVE_INFINITY);const r=e.payload;s.samples.push({data:r,len:r.byteLength,dts:t,pts:t,type:Ki,duration:n})}}))}return s}demuxSampleAes(t,i,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,i,s,e){this.audioCodec=i,this.videoCodec=s,this.generateInitSegment(function(t,i){if(!t||!i)return t;const s=i.keyId;return s&&i.isCommonEncryption&&Ot(t,["moov","trak"]).forEach((t=>{const i=Ot(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let e=Ot(i,["enca"]);const n=e.length>0;n||(e=Ot(i,["encv"])),e.forEach((t=>{Ot(t.subarray(n?28:78),["sinf"]).forEach((t=>{const i=Gt(t);if(i){const t=i.subarray(8,24);t.some((t=>0!==t))||(I.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Et(t)} -> ${Et(s)}`),i.set(s,8))}}))}))})),t}(t,e)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:i,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const e=this.initData=Ut(t);e.audio&&(i=un(e.audio,B)),e.video&&(s=un(e.video,j));const n={};e.audio&&e.video?n.audiovideo={container:"video/mp4",codec:i+","+s,initSegment:t,id:"main"}:e.audio?n.audio={container:"audio/mp4",codec:i,initSegment:t,id:"audio"}:e.video?n.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:I.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(t,i,s,e,n,r){var h,o;let{initPTS:a,lastEndTime:l}=this;const c={audio:void 0,video:void 0,text:e,id3:s,initSegment:void 0};T(l)||(l=this.lastEndTime=n||0);const u=i.samples;if(null==u||!u.length)return c;const d={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(h=f)&&h.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return I.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const v=function(t,i){let s=0,e=0,n=0;const r=Ot(t,["moof","traf"]);for(let t=0;t<r.length;t++){const h=r[t],o=Ot(h,["tfhd"])[0],a=i[Ct(o,4)];if(!a)continue;const l=a.default,c=Ct(o,0)|(null==l?void 0:l.flags);let u=null==l?void 0:l.duration;8&c&&(u=Ct(o,2&c?12:8));const d=a.timescale||9e4,f=Ot(h,["trun"]);for(let t=0;t<f.length;t++)s=Ht(f[t]),!s&&u&&(s=u*Ct(f[t],4)),a.type===j?e+=s/d:a.type===B&&(n+=s/d)}if(0===e&&0===n){let i=1/0,s=0,e=0;const n=Ot(t,["sidx"]);for(let t=0;t<n.length;t++){const r=Nt(n[t]);if(null!=r&&r.references){i=Math.min(i,r.earliestPresentationTime/r.timescale);const t=r.references.reduce(((t,i)=>t+i.info.duration||0),0);s=Math.max(s,t+r.earliestPresentationTime/r.timescale),e=s-i}}if(e&&T(e))return e}return e||n}(u,f),p=function(t,i){return Ot(i,["moof","traf"]).reduce(((i,s)=>{const e=Ot(s,["tfdt"])[0],n=e[0],r=Ot(s,["tfhd"]).reduce(((i,s)=>{const r=Ct(s,4),h=t[r];if(h){let t=Ct(e,4);if(1===n){if(t===At)return I.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),i;t*=At+1,t+=Ct(e,8)}const s=t/(h.timescale||9e4);if(T(s)&&(null===i||s<i))return s}return i}),null);return null!==r&&T(r)&&(null===i||r<i)?r:i}),null)}(f,u),g=null===p?n:p;(function(t,i,s,e){if(null===t)return!0;const n=Math.max(e,1);return Math.abs(i-t.baseTime/t.timescale-s)>n}(a,g,n,v)||d.timescale!==a.timescale&&r)&&(d.initPTS=g-n,a&&1===a.timescale&&I.warn("Adjusting initPTS by "+(d.initPTS-a.baseTime)),this.initPTS=a={baseTime:d.initPTS,timescale:1});const m=t?g-a.baseTime/a.timescale:l,y=m+v;!function(t,i,s){Ot(i,["moof","traf"]).forEach((i=>{Ot(i,["tfhd"]).forEach((e=>{const n=Ct(e,4),r=t[n];if(!r)return;const h=r.timescale||9e4;Ot(i,["tfdt"]).forEach((t=>{const i=t[0],e=s*h;if(e){let s=Ct(t,4);if(0===i)s-=e,s=Math.max(s,0),Pt(t,4,s);else{s*=Math.pow(2,32),s+=Ct(t,8),s-=e,s=Math.max(s,0);const i=Math.floor(s/(At+1)),n=Math.floor(s%(At+1));Pt(t,4,i),Pt(t,8,n)}}}))}))}))}(f,u,a.baseTime/a.timescale),v>0?this.lastEndTime=y:(I.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!f.audio,b=!!f.video;let k="";w&&(k+="audio"),b&&(k+="video");const S={data1:u,startPTS:m,startDTS:m,endPTS:y,endDTS:y,type:k,hasAudio:w,hasVideo:b,nb:1,dropped:0};return c.audio="audio"===S.type?S:void 0,c.video="audio"!==S.type?S:void 0,c.initSegment=d,c.id3=an(s,n,a,a),e.samples.length&&(c.text=ln(e,n,a)),c}}},{demux:Ke,remux:hn},{demux:class extends ge{constructor(t,i){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=i}resetInitSegment(t,i,s,e){super.resetInitSegment(t,i,s,e),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:e,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const i=ct(t,0);let s=(null==i?void 0:i.length)||0;if(Oe(t,s))return!1;for(let i=t.length;s<i;s++)if(Se(t,s))return I.log("ADTS sync word found !"),!0;return!1}canParse(t,i){return function(t,i){return function(t,i){return i+5<t.length}(t,i)&&ye(t,i)&&be(t,i)<=t.length-i}(t,i)}appendFrame(t,i,s){Te(t,this.observer,i,s,t.manifestCodec);const e=Ee(t,i,s,this.basePTS,this.frameIndex);if(e&&0===e.missing)return e}},remux:hn},{demux:class extends ge{resetInitSegment(t,i,s,e){super.resetInitSegment(t,i,s,e),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:e,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const i=ct(t,0);let s=(null==i?void 0:i.length)||0;if(i&&11===t[s]&&119===t[s+1]&&void 0!==ft(i)&&Ue(t,s)<=16)return!1;for(let i=t.length;s<i;s++)if(Oe(t,s))return I.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,i){return function(t,i){return Re(t,i)&&4<=t.length-i}(t,i)}appendFrame(t,i,s){if(null!==this.basePTS)return Ce(t,i,s,this.basePTS,this.frameIndex)}},remux:hn}];dn.splice(2,0,{demux:class extends ge{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,i,s,e){super.resetInitSegment(t,i,s,e),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:e,inputTimeScale:9e4,dropped:0}}canParse(t,i){return i+64<t.length}appendFrame(t,i,s){const e=Fe(t,i,s,this.basePTS,this.frameIndex);if(-1!==e)return{sample:t.samples[t.samples.length-1],length:e,missing:0}}static probe(t){if(!t)return!1;const i=ct(t,0);if(!i)return!1;const s=i.length;return 11===t[s]&&119===t[s+1]&&void 0!==ft(i)&&Ue(t,s)<16}},remux:hn});class fn{constructor(t,i,s,e,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=i,this.config=s,this.vendor=e,this.id=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,i,s,e){const n=s.transmuxing;n.executeStart=en();let r=new Uint8Array(t);const{currentTransmuxState:h,transmuxConfig:o}=this;e&&(this.currentTransmuxState=e);const{contiguous:a,discontinuity:l,trackSwitch:c,accurateTimeOffset:u,timeOffset:d,initSegmentChange:f}=e||h,{audioCodec:v,videoCodec:p,defaultInitPts:g,duration:m,initSegmentData:y}=o,w=function(t,i){let s=null;return t.byteLength>0&&null!=(null==i?void 0:i.key)&&null!==i.iv&&null!=i.method&&(s=i),s}(r,i);if(w&&"AES-128"===w.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(r,w.key.buffer,w.iv.buffer).then((t=>{const i=this.push(t,null,s);return this.decryptionPromise=null,i})),this.decryptionPromise;{let i=t.softwareDecrypt(r,w.key.buffer,w.iv.buffer);if(s.part>-1&&(i=t.flush()),!i)return n.executeEnd=en(),vn(s);r=new Uint8Array(i)}}const b=this.needsProbing(l,c);if(b){const t=this.configureTransmuxer(r);if(t)return I.warn(`[transmuxer] ${t.message}`),this.observer.emit(A.ERROR,A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),n.executeEnd=en(),vn(s)}(l||c||f||b)&&this.resetInitSegment(y,v,p,m,i),(l||f||b)&&this.resetInitialTimestamp(g),a||this.resetContiguity();const k=this.transmux(r,w,d,u,s),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=en(),k}flush(t){const i=t.transmuxing;i.executeStart=en();const{decrypter:s,currentTransmuxState:e,decryptionPromise:n}=this;if(n)return n.then((()=>this.flush(t)));const r=[],{timeOffset:h}=e;if(s){const i=s.flush();i&&r.push(this.push(i,null,t))}const{demuxer:o,remuxer:a}=this;if(!o||!a)return i.executeEnd=en(),[vn(t)];const l=o.flush(h);return pn(l)?l.then((i=>(this.flushRemux(r,i,t),r))):(this.flushRemux(r,l,t),r)}flushRemux(t,i,s){const{audioTrack:e,videoTrack:n,id3Track:r,textTrack:h}=i,{accurateTimeOffset:o,timeOffset:a}=this.currentTransmuxState;I.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const l=this.remuxer.remux(e,n,r,h,a,o,!0,this.id);t.push({remuxResult:l,chunkMeta:s}),s.transmuxing.executeEnd=en()}resetInitialTimestamp(t){const{demuxer:i,remuxer:s}=this;i&&s&&(i.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetContiguity(),i.resetNextTimestamp())}resetInitSegment(t,i,s,e,n){const{demuxer:r,remuxer:h}=this;r&&h&&(r.resetInitSegment(t,i,s,e),h.resetInitSegment(t,i,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,i,s,e,n){let r;return r=i&&"SAMPLE-AES"===i.method?this.transmuxSampleAes(t,i,s,e,n):this.transmuxUnencrypted(t,s,e,n),r}transmuxUnencrypted(t,i,s,e){const{audioTrack:n,videoTrack:r,id3Track:h,textTrack:o}=this.demuxer.demux(t,i,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,r,h,o,i,s,!1,this.id),chunkMeta:e}}transmuxSampleAes(t,i,s,e,n){return this.demuxer.demuxSampleAes(t,i,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,e,!1,this.id),chunkMeta:n})))}configureTransmuxer(t){const{config:i,observer:s,typeSupported:e,vendor:n}=this;let r;for(let i=0,s=dn.length;i<s;i++){var h;if(null!=(h=dn[i].demux)&&h.probe(t)){r=dn[i];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,a=this.remuxer,l=r.remux,c=r.demux;a&&a instanceof l||(this.remuxer=new l(s,i,e,n)),o&&o instanceof c||(this.demuxer=new c(s,i,e),this.probe=c.probe)}needsProbing(t,i){return!this.demuxer||!this.remuxer||t||i}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new te(this.config)),t}}const vn=t=>({remuxResult:{},chunkMeta:t});function pn(t){return"then"in t&&t.then instanceof Function}class gn{constructor(t,i,s,e,n){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=i,this.initSegmentData=s,this.duration=e,this.defaultInitPts=n||null}}class mn{constructor(t,i,s,e,n,r){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=i,this.accurateTimeOffset=s,this.trackSwitch=e,this.timeOffset=n,this.initSegmentChange=r}}var yn={exports:{}};!function(t){var i=Object.prototype.hasOwnProperty,s="~";function e(){}function n(t,i,s){this.fn=t,this.context=i,this.once=s||!1}function r(t,i,e,r,h){if("function"!=typeof e)throw new TypeError("The listener must be a function");var o=new n(e,r||t,h),a=s?s+i:i;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],o]:t._events[a].push(o):(t._events[a]=o,t._eventsCount++),t}function h(t,i){0==--t._eventsCount?t._events=new e:delete t._events[i]}function o(){this._events=new e,this._eventsCount=0}Object.create&&(e.prototype=Object.create(null),(new e).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,e,n=[];if(0===this._eventsCount)return n;for(e in t=this._events)i.call(t,e)&&n.push(s?e.slice(1):e);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(t)):n},o.prototype.listeners=function(t){var i=this._events[s?s+t:t];if(!i)return[];if(i.fn)return[i.fn];for(var e=0,n=i.length,r=new Array(n);e<n;e++)r[e]=i[e].fn;return r},o.prototype.listenerCount=function(t){var i=this._events[s?s+t:t];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,i,e,n,r,h){var o=s?s+t:t;if(!this._events[o])return!1;var a,l,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,i),!0;case 3:return c.fn.call(c.context,i,e),!0;case 4:return c.fn.call(c.context,i,e,n),!0;case 5:return c.fn.call(c.context,i,e,n,r),!0;case 6:return c.fn.call(c.context,i,e,n,r,h),!0}for(l=1,a=new Array(u-1);l<u;l++)a[l-1]=arguments[l];c.fn.apply(c.context,a)}else{var d,f=c.length;for(l=0;l<f;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,i);break;case 3:c[l].fn.call(c[l].context,i,e);break;case 4:c[l].fn.call(c[l].context,i,e,n);break;default:if(!a)for(d=1,a=new Array(u-1);d<u;d++)a[d-1]=arguments[d];c[l].fn.apply(c[l].context,a)}}return!0},o.prototype.on=function(t,i,s){return r(this,t,i,s,!1)},o.prototype.once=function(t,i,s){return r(this,t,i,s,!0)},o.prototype.removeListener=function(t,i,e,n){var r=s?s+t:t;if(!this._events[r])return this;if(!i)return h(this,r),this;var o=this._events[r];if(o.fn)o.fn!==i||n&&!o.once||e&&o.context!==e||h(this,r);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==i||n&&!o[a].once||e&&o[a].context!==e)&&l.push(o[a]);l.length?this._events[r]=1===l.length?l[0]:l:h(this,r)}return this},o.prototype.removeAllListeners=function(t){var i;return t?this._events[i=s?s+t:t]&&h(this,i):(this._events=new e,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(yn);var wn=f(yn.exports);class bn{constructor(t,i,s,e){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=t.config;this.hls=t,this.id=i,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=e;const r=(t,i)=>{(i=i||{}).frag=this.frag,i.id=this.id,t===A.ERROR&&(this.error=i.error),this.hls.trigger(t,i)};this.observer=new wn,this.observer.on(A.FRAG_DECRYPTED,r),this.observer.on(A.ERROR,r);const h=ni(n.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:h.isTypeSupported("audio/mpeg"),mp3:h.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:h.isTypeSupported('audio/mp4; codecs="ac-3"')};if(!this.useWorker||"undefined"==typeof Worker||!n.workerPath&&"function"!=typeof __HLS_WORKER_BUNDLE__)this.transmuxer=new fn(this.observer,o,n,"",i);else try{n.workerPath?(I.log(`loading Web Worker ${n.workerPath} for "${i}"`),this.workerContext=function(t){const i=new self.URL(t,self.location.href).href;return{worker:new self.Worker(i),scriptURL:i}}(n.workerPath)):(I.log(`injecting Web Worker for "${i}"`),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"}),i=self.URL.createObjectURL(t);return{worker:new self.Worker(i),objectURL:i}}()),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})`);n.enableWorker=!1,I.warn(`Error in "${i}" Web Worker, fallback to inline`),this.hls.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:o,vendor:"",id:i,config:JSON.stringify(n)})}catch(t){I.warn(`Error setting up "${i}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new fn(this.observer,o,n,"",i)}}resetWorker(){if(this.workerContext){const{worker:t,objectURL:i}=this.workerContext;i&&self.URL.revokeObjectURL(i),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,i,s,e,n,r,h,o,a,l){var c,u;a.transmuxing.start=self.performance.now();const{transmuxer:d}=this,f=r?r.start:n.start,v=n.decryptdata,p=this.frag,g=!(p&&n.cc===p.cc),m=!(p&&a.level===p.level),y=p?a.sn-p.sn:-1,w=this.part?a.part-this.part.index:-1,b=!m&&(1===y||0===y&&(1===w||0===y&&a.id>1&&a.id===(null==p?void 0:p.stats.chunkCount)&&w<=0)),k=self.performance.now();(m||y||0===n.stats.parsing.start)&&(n.stats.parsing.start=k),!r||!w&&b||(r.stats.parsing.start=k);const S=!(p&&(null==(c=n.initSegment)?void 0:c.url)===(null==(u=p.initSegment)?void 0:u.url)),T=new mn(g,b,o,m,f,S);if(!b||g||S){I.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${a.sn} p: ${a.part} level: ${a.level} id: ${a.id}\n discontinuity: ${g}\n trackSwitch: ${m}\n contiguous: ${b}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${S}`);const t=new gn(s,e,i,h,l);this.configureTransmuxer(t)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:v,chunkMeta:a,state:T},t instanceof ArrayBuffer?[t]:[]);else if(d){const i=d.push(t,v,a,T);pn(i)?(d.async=!0,i.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,a,"transmuxer-interface push error")}))):(d.async=!1,this.handleTransmuxComplete(i))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(i){let s=i.flush(t);pn(s)||i.async?(pn(s)||(s=Promise.resolve(s)),s.then((i=>{this.handleFlushResult(i,t)})).catch((i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}))):this.handleFlushResult(s,t)}}transmuxerError(t,i,s){this.hls&&(this.error=t,this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:i,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,i){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(i)}onWorkerMessage(t){const i=t.data;if(null==i||!i.event)return void I.warn("worker message received with no "+(i?"event name":"data"));const s=this.hls;if(this.hls)switch(i.event){case"init":{var e;const t=null==(e=this.workerContext)?void 0:e.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(i.data);break;case"flush":this.onFlush(i.data);break;case"workerLog":I[i.data.logType]&&I[i.data.logType](i.data.message);break;default:i.data=i.data||{},i.data.frag=this.frag,i.data.id=this.id,s.trigger(i.event,i.data)}}configureTransmuxer(t){const{transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function kn(t,i){if(t.length!==i.length)return!1;for(let s=0;s<t.length;s++)if(!Sn(t[s].attrs,i[s].attrs))return!1;return!0}function Sn(t,i,s){const e=t["STABLE-RENDITION-ID"];return e&&!s?e===i["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((s=>t[s]!==i[s]))}function Tn(t,i){return i.label.toLowerCase()===t.name.toLowerCase()&&(!i.language||i.language.toLowerCase()===(t.lang||"").toLowerCase())}class $n{constructor(t){this.buffered=void 0;const i=(i,s,e)=>{if((s>>>=0)>e-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${e})`);return t[s][i]};this.buffered={get length(){return t.length},end:s=>i("end",s,t.length),start:s=>i("start",s,t.length)}}}class En{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,i,s){const e=this.queues[i];e.push(t),1!==e.length||s||this.executeNext(i)}insertAbort(t,i){this.queues[i].unshift(t),this.executeNext(i)}appendBlocker(t){let i;const s=new Promise((t=>{i=t}));return this.append({execute:i,onStart:()=>{},onComplete:()=>{},onError:()=>{}},t),s}executeNext(t){const i=this.queues[t];if(i.length){const s=i[0];try{s.execute()}catch(i){I.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${i}`),s.onError(i);const e=this.buffers[t];null!=e&&e.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const An=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Mn(t){const i=t.querySelectorAll("source");[].slice.call(i).forEach((i=>{t.removeChild(i)}))}const Ln={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},xn=t=>String.fromCharCode(Ln[t]||t),Dn=15,Cn=100,In={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Rn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Pn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},On={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Nn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Un{constructor(){this.time=null,this.verboseLevel=0}log(t,i){if(this.verboseLevel>=t){const s="function"==typeof i?i():i;I.log(`${this.time} [${t}] ${s}`)}}}const Fn=function(t){const i=[];for(let s=0;s<t.length;s++)i.push(t[s].toString(16));return i};class Bn{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const i=["foreground","underline","italics","background","flash"];for(let s=0;s<i.length;s++){const e=i[s];t.hasOwnProperty(e)&&(this[e]=t[e])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class jn{constructor(){this.uchar=" ",this.penState=new Bn}reset(){this.uchar=" ",this.penState.reset()}setChar(t,i){this.uchar=t,this.penState.copy(i)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class _n{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Bn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Cn;t++)this.chars.push(new jn);this.logger=t}equals(t){for(let i=0;i<Cn;i++)if(!this.chars[i].equals(t.chars[i]))return!1;return!0}copy(t){for(let i=0;i<Cn;i++)this.chars[i].copy(t.chars[i])}isEmpty(){let t=!0;for(let i=0;i<Cn;i++)if(!this.chars[i].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Cn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Cn)}moveCursor(t){const i=this.pos+t;if(t>1)for(let t=this.pos+1;t<i+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(i)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const i=xn(t);this.pos>=Cn?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+i+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))}clearFromPos(t){let i;for(i=t;i<Cn;i++)this.chars[i].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let i=!0;for(let s=0;s<Cn;s++){const e=this.chars[s].uchar;" "!==e&&(i=!1),t.push(e)}return i?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}class Gn{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let i=0;i<Dn;i++)this.rows.push(new _n(t));this.logger=t}reset(){for(let t=0;t<Dn;t++)this.rows[t].clear();this.currRow=14}equals(t){let i=!0;for(let s=0;s<Dn;s++)if(!this.rows[s].equals(t.rows[s])){i=!1;break}return i}copy(t){for(let i=0;i<Dn;i++)this.rows[i].copy(t.rows[i])}isEmpty(){let t=!0;for(let i=0;i<Dn;i++)if(!this.rows[i].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,(()=>"pacData = "+JSON.stringify(t)));let i=t.row-1;if(this.nrRollUpRows&&i<this.nrRollUpRows-1&&(i=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==i){for(let t=0;t<Dn;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const e=s.rows[t].cueStartTime,n=this.logger.time;if(null!==e&&null!==n&&e<n)for(let e=0;e<this.nrRollUpRows;e++)this.rows[i-this.nrRollUpRows+e+1].copy(s.rows[t+e])}}this.currRow=i;const s=this.rows[this.currRow];if(null!==t.indent){const i=Math.max(t.indent-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}this.setPen({foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1})}setBkgData(t){this.logger.log(2,(()=>"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.rows.splice(this.currRow+1-this.nrRollUpRows,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const i=[];let s="",e=-1;for(let s=0;s<Dn;s++){const n=this.rows[s].getTextString();n&&(e=s+1,i.push(t?"Row "+e+": '"+n+"'":n.trim()))}return i.length>0&&(s=t?"["+i.join(" | ")+"]":i.join("\n")),s}getTextAndFormat(){return this.rows}}class Hn{constructor(t,i,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=i,this.mode=null,this.verbose=0,this.displayedMemory=new Gn(s),this.nonDisplayedMemory=new Gn(s),this.lastOutputScreen=new Gn(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 i=0;i<t.length;i++)this.writeScreen.insertChar(t[i]);const i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>i+": "+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 i={flash:!1};if(i.underline=t%2==1,i.italics=t>=46,i.italics)i.foreground="white";else{const s=Math.floor(t/2)-16;i.foreground=["white","green","blue","cyan","red","yellow","magenta"][s]}this.logger.log(2,"MIDROW: "+JSON.stringify(i)),this.writeScreen.setPen(i)}outputDataUpdate(t=!1){const i=this.logger.time;null!==i&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,i,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:i):this.cueStartTime=i,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 Kn{constructor(t,i,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const e=this.logger=new Un;this.channels=[null,new Hn(t,i,e),new Hn(t+1,s,e)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,i){this.channels[t].setHandler(i)}addData(t,i){this.logger.time=t;for(let t=0;t<i.length;t+=2){const s=127&i[t],e=127&i[t+1];let n=!1,r=null;if(0===s&&0===e)continue;this.logger.log(3,(()=>"["+Fn([i[t],i[t+1]])+"] -> ("+Fn([s,e])+")"));const h=this.cmdHistory;if(s>=16&&s<=31){if(zn(s,e,h)){Vn(null,null,h),this.logger.log(3,(()=>"Repeated command ("+Fn([s,e])+") is dropped"));continue}Vn(s,e,this.cmdHistory),n=this.parseCmd(s,e),n||(n=this.parseMidrow(s,e)),n||(n=this.parsePAC(s,e)),n||(n=this.parseBackgroundAttributes(s,e))}else Vn(null,null,h);if(!n&&(r=this.parseChars(s,e),r)){const t=this.currentChannel;t&&t>0?this.channels[t].insertChars(r):this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||r||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Fn([s,e])+" orig: "+Fn([i[t],i[t+1]])))}}parseCmd(t,i){if(!((20===t||28===t||21===t||29===t)&&i>=32&&i<=47||(23===t||31===t)&&i>=33&&i<=35))return!1;const s=20===t||21===t||23===t?1:2,e=this.channels[s];return 20===t||21===t||28===t||29===t?32===i?e.ccRCL():33===i?e.ccBS():34===i?e.ccAOF():35===i?e.ccAON():36===i?e.ccDER():37===i?e.ccRU(2):38===i?e.ccRU(3):39===i?e.ccRU(4):40===i?e.ccFON():41===i?e.ccRDC():42===i?e.ccTR():43===i?e.ccRTD():44===i?e.ccEDM():45===i?e.ccCR():46===i?e.ccENM():47===i&&e.ccEOC():e.ccTO(i-32),this.currentChannel=s,!0}parseMidrow(t,i){let s=0;if((17===t||25===t)&&i>=32&&i<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const e=this.channels[s];return!!e&&(e.ccMIDROW(i),this.logger.log(3,(()=>"MIDROW ("+Fn([t,i])+")")),!0)}return!1}parsePAC(t,i){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&i>=64&&i<=127||(16===t||24===t)&&i>=64&&i<=95))return!1;const e=t<=23?1:2;s=i>=64&&i<=95?1===e?In[t]:Pn[t]:1===e?Rn[t]:On[t];const n=this.channels[e];return!!n&&(n.setPAC(this.interpretPAC(s,i)),this.currentChannel=e,!0)}interpretPAC(t,i){let s;const e={color:null,italics:!1,indent:null,underline:!1,row:t};return s=i>95?i-96:i-64,e.underline=!(1&~s),s<=13?e.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(e.italics=!0,e.color="white"):e.indent=4*Math.floor((s-16)/2),e}parseChars(t,i){let s,e=null,n=null;if(t>=25?(s=2,n=t-8):(s=1,n=t),n>=17&&n<=19){let t;t=17===n?i+80:18===n?i+112:i+144,this.logger.log(2,(()=>"Special char '"+xn(t)+"' in channel "+s)),e=[t]}else t>=32&&t<=127&&(e=0===i?[t]:[t,i]);return e&&this.logger.log(3,(()=>"Char codes = "+Fn(e).join(","))),e}parseBackgroundAttributes(t,i){if(!((16===t||24===t)&&i>=32&&i<=47||(23===t||31===t)&&i>=45&&i<=47))return!1;let s;const e={};return 16===t||24===t?(s=Math.floor((i-32)/2),e.background=Nn[s],i%2==1&&(e.background=e.background+"_semi")):45===i?e.background="transparent":(e.foreground="black",47===i&&(e.underline=!0)),this.channels[t<=23?1:2].setBkgData(e),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const i=this.channels[t];i&&i.reset()}Vn(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let i=0;i<this.channels.length;i++){const s=this.channels[i];s&&s.cueSplitAtTime(t)}}}function Vn(t,i,s){s.a=t,s.b=i}function zn(t,i,s){return s.a===t&&s.b===i}class Wn{constructor(t,i){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=i}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,i,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=i,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Xn=function(){if(null!=X&&X.VTTCue)return self.VTTCue;const t=["","lr","rl"],i=["start","middle","end","left","right"];function s(t,i){if("string"!=typeof i)return!1;if(!Array.isArray(t))return!1;const s=i.toLowerCase();return!!~t.indexOf(s)&&s}function e(t){return s(i,t)}function n(t){let i=1;for(;i<arguments.length;i++){const s=arguments[i];for(const i in s)t[i]=s[i]}return t}function r(i,r,h){const o=this,a={enumerable:!0};o.hasBeenReset=!1;let l="",c=!1,u=i,d=r,f=h,v=null,p="",g=!0,m="auto",y="start",w=50,b="middle",k=50,S="middle";Object.defineProperty(o,"id",n({},a,{get:function(){return l},set:function(t){l=""+t}})),Object.defineProperty(o,"pauseOnExit",n({},a,{get:function(){return c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",n({},a,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},a,{get:function(){return d},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},a,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},a,{get:function(){return v},set:function(t){v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},a,{get:function(){return p},set:function(i){const e=function(i){return s(t,i)}(i);if(!1===e)throw new SyntaxError("An invalid or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},a,{get:function(){return g},set:function(t){g=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},a,{get:function(){return m},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},a,{get:function(){return y},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");y=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},a,{get:function(){return w},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},a,{get:function(){return b},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");b=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},a,{get:function(){return k},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");k=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},a,{get:function(){return S},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");S=i,this.hasBeenReset=!0}})),o.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class qn{decode(t,i){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Yn(t){function i(t,i,s,e){return 3600*(0|t)+60*(0|i)+(0|s)+parseFloat(e||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?i(s[2],s[3],0,s[4]):i(s[1],s[2],s[3],s[4]):null}class Jn{constructor(){this.values=Object.create(null)}set(t,i){this.get(t)||""===i||(this.values[t]=i)}get(t,i,s){return s?this.has(t)?this.values[t]:i[s]:this.has(t)?this.values[t]:i}has(t){return t in this.values}alt(t,i,s){for(let e=0;e<s.length;++e)if(i===s[e]){this.set(t,i);break}}integer(t,i){/^-?\d+$/.test(i)&&this.set(t,parseInt(i,10))}percent(t,i){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(i)){const s=parseFloat(i);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function Qn(t,i,s,e){const n=e?t.split(e):[t];for(const t in n){if("string"!=typeof n[t])continue;const e=n[t].split(s);2===e.length&&i(e[0],e[1])}}const Zn=new Xn(0,0,""),tr="middle"===Zn.align?"middle":"center";function ir(t,i,s){const e=t;function n(){const i=Yn(t);if(null===i)throw new Error("Malformed timestamp: "+e);return t=t.replace(/^[^\sa-zA-Z-]+/,""),i}function r(){t=t.replace(/^\s+/,"")}if(r(),i.startTime=n(),r(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+e);t=t.slice(3),r(),i.endTime=n(),r(),function(t,i){const e=new Jn;Qn(t,(function(t,i){let n;switch(t){case"region":for(let n=s.length-1;n>=0;n--)if(s[n].id===i){e.set(t,s[n].region);break}break;case"vertical":e.alt(t,i,["rl","lr"]);break;case"line":n=i.split(","),e.integer(t,n[0]),e.percent(t,n[0])&&e.set("snapToLines",!1),e.alt(t,n[0],["auto"]),2===n.length&&e.alt("lineAlign",n[1],["start",tr,"end"]);break;case"position":n=i.split(","),e.percent(t,n[0]),2===n.length&&e.alt("positionAlign",n[1],["start",tr,"end","line-left","line-right","auto"]);break;case"size":e.percent(t,i);break;case"align":e.alt(t,i,["start",tr,"end","left","right"])}}),/:/,/\s/),i.region=e.get("region",null),i.vertical=e.get("vertical","");let n=e.get("line","auto");"auto"===n&&-1===Zn.line&&(n=-1),i.line=n,i.lineAlign=e.get("lineAlign","start"),i.snapToLines=e.get("snapToLines",!0),i.size=e.get("size",100),i.align=e.get("align",tr);let r=e.get("position","auto");"auto"===r&&50===Zn.position&&(r="start"===i.align||"left"===i.align?0:"end"===i.align||"right"===i.align?100:50),i.position=r}(t,i)}function sr(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class er{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new qn,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const i=this;function s(){let t=i.buffer,s=0;for(t=sr(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const e=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,i.buffer=t.slice(s),e}t&&(i.buffer+=i.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===i.state){if(!/\r\n|\n/.test(i.buffer))return this;t=s();const e=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==e||!e[0])throw new Error("Malformed WebVTT signature.");i.state="HEADER"}let e=!1;for(;i.buffer;){if(!/\r\n|\n/.test(i.buffer))return this;switch(e?e=!1:t=s(),i.state){case"HEADER":/:/.test(t)?Qn(t,(function(){}),/:/):t||(i.state="ID");continue;case"NOTE":t||(i.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){i.state="NOTE";break}if(!t)continue;if(i.cue=new Xn(0,0,""),i.state="CUE",-1===t.indexOf("--\x3e")){i.cue.id=t;continue}case"CUE":if(!i.cue){i.state="BADCUE";continue}try{ir(t,i.cue,i.regionList)}catch(t){i.cue=null,i.state="BADCUE";continue}i.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(e=!0)){i.oncue&&i.cue&&i.oncue(i.cue),i.cue=null,i.state="ID";continue}if(null===i.cue)continue;i.cue.text&&(i.cue.text+="\n"),i.cue.text+=t}continue;case"BADCUE":t||(i.state="ID")}}}catch(t){"CUETEXT"===i.state&&i.cue&&i.oncue&&i.oncue(i.cue),i.cue=null,i.state="INITIAL"===i.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(i){t.onparsingerror&&t.onparsingerror(i)}return t.onflush&&t.onflush(),this}}const nr=/\r\n|\n\r|\n|\r/g,rr=function(t,i,s=0){return t.slice(s,s+i.length)===i},hr=function(t){let i=5381,s=t.length;for(;s;)i=33*i^t.charCodeAt(--s);return(i>>>0).toString()};function or(t,i,s){return hr(t.toString())+hr(i.toString())+hr(s)}const ar="stpp.ttml.im1t",lr=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,cr=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ur={left:"start",center:"center",right:"end",start:"start",end:"end"};function dr(t,i,s,e){const n=Ot(new Uint8Array(t),["mdat"]);if(0===n.length)return void e(new Error("Could not parse IMSC1 mdat"));const r=n.map((t=>St(t))),h=function(t,i,s=1,e=!1){return tn(t,1,1/s,e)}(i.baseTime,0,i.timescale);try{r.forEach((t=>s(function(t,i){const s=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const e={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(e).reduce(((t,i)=>(t[i]=s.getAttribute(`ttp:${i}`)||e[i],t)),{}),r="preserve"!==s.getAttribute("xml:space"),h=vr(fr(s,"styling","style")),o=vr(fr(s,"layout","region")),a=fr(s,"body","[begin]");return[].map.call(a,(t=>{const s=pr(t,r);if(!s||!t.hasAttribute("begin"))return null;const e=yr(t.getAttribute("begin"),n),a=yr(t.getAttribute("dur"),n);let l=yr(t.getAttribute("end"),n);if(null===e)throw mr(t);if(null===l){if(null===a)throw mr(t);l=e+a}const c=new Xn(e-i,l-i,s);c.id=or(c.startTime,c.endTime,c.text);const u=function(t,i,s){const e="http://www.w3.org/ns/ttml#styling";let n=null;const r=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return r&&s.hasOwnProperty(r)&&(n=s[r]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(((s,r)=>{const h=gr(i,e,r)||gr(t,e,r)||gr(n,e,r);return h&&(s[r]=h),s}),{})}(o[t.getAttribute("region")],h[t.getAttribute("style")],h),{textAlign:d}=u;if(d){const t=ur[d];t&&(c.lineAlign=t),c.align=d}return S(c,u),c})).filter((t=>null!==t))}(t,h))))}catch(t){e(t)}}function fr(t,i,s){const e=t.getElementsByTagName(i)[0];return e?[].slice.call(e.querySelectorAll(s)):[]}function vr(t){return t.reduce(((t,i)=>{const s=i.getAttribute("xml:id");return s&&(t[s]=i),t}),{})}function pr(t,i){return[].slice.call(t.childNodes).reduce(((t,s,e)=>{var n;return"br"===s.nodeName&&e?t+"\n":null!=(n=s.childNodes)&&n.length?pr(s,i):i?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function gr(t,i,s){return t&&t.hasAttributeNS(i,s)?t.getAttributeNS(i,s):null}function mr(t){return new Error(`Could not parse ttml timestamp ${t}`)}function yr(t,i){if(!t)return null;let s=Yn(t);return null===s&&(lr.test(t)?s=function(t,i){const s=lr.exec(t);return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+((0|s[4])+(0|s[5])/i.subFrameRate)/i.frameRate}(t,i):cr.test(t)&&(s=function(t,i){const s=cr.exec(t),e=Number(s[1]);switch(s[2]){case"h":return 3600*e;case"m":return 60*e;case"ms":return 1e3*e;case"f":return e/i.frameRate;case"t":return e/i.tickRate}return e}(t,i))),s}function wr(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function br(t,i){return!!t&&t.kind===wr(i)&&Tn(i,t)}class kr{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(A.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.BUFFER_CODECS,this.onBufferCodecs,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(A.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.BUFFER_CODECS,this.onBufferCodecs,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,i){const s=this.hls.levels[i.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,i){this.media=i.media instanceof HTMLVideoElement?i.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,i){const s=this.hls;this.restrictedLevels=[],this.firstLevel=i.firstLevel,s.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onLevelsUpdated(t,i){this.timer&&T(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,i){this.hls.config.capLevelToPlayerSize&&i.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 i=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&I.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),i.autoLevelCapping=s,i.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=i.autoLevelCapping}}}getMaxLevel(t){const i=this.hls.levels;if(!i.length)return-1;const s=i.filter(((i,s)=>this.isLevelAllowed(i)&&s<=t));return this.clientRect=null,kr.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,i={width:0,height:0};if(t){const s=t.getBoundingClientRect();i.width=s.width,i.height=s.height,i.width||i.height||(i.width=s.right-s.left||t.width||0,i.height=s.bottom-s.top||t.height||0)}return this.clientRect=i,i}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((i=>t.bitrate===i.bitrate&&t.width===i.width&&t.height===i.height))}static getMaxLevelByMediaSize(t,i,s){if(null==t||!t.length)return-1;let e=t.length-1;const n=Math.max(i,s);for(let i=0;i<t.length;i+=1){const s=t[i];if((s.width>=n||s.height>=n)&&(r=s,!(h=t[i+1])||r.width!==h.width||r.height!==h.height)){e=i;break}}var r,h;return e}}const Sr="[eme]";class Tr{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=Tr.CDMCleanupPromise?[Tr.CDMCleanupPromise]:[],this.debug=I.debug.bind(I,Sr),this.log=I.log.bind(I,Sr),this.warn=I.warn.bind(I,Sr),this.error=I.error.bind(I,Sr),this.onMediaEncrypted=t=>{const{initDataType:i,initData:s}=t,e=`"${t.type}" event: init data type: "${i}"`;if(this.debug(e),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=et(this.config));const i=t.map(st).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(i)}this.keyFormatPromise.then((n=>{const r=tt(n);let h,o;if("sinf"===i){if(r!==q.FAIRPLAY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${r}`);const n=xt(new Uint8Array(s));try{const t=Gt(z(JSON.parse(n).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=t.subarray(8,24),o=q.FAIRPLAY}catch(t){return void this.warn(`${e} Failed to parse sinf: ${t}`)}}else{if(r!==q.WIDEVINE&&r!==q.PLAYREADY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${r}`);const n=function(t){const i=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let e=0;for(;e+32<s;){const s=qt(new DataView(t,e));i.push(s),e+=s.size}}return i}(s),a=n.filter((t=>!!t.systemId&&it(t.systemId)===r));a.length>1&&this.warn(`${e} Using first of ${a.length} pssh found for selected key-system ${r}`);const l=a[0];if(!l)return void(0===n.length||n.some((t=>!t.systemId))?this.warn(`${e} contains incomplete or invalid pssh data`):this.log(`ignoring ${e} for ${n.map((t=>it(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=it(l.systemId),0===l.version&&l.data)if(o===q.WIDEVINE){const t=l.data.length-22;h=l.data.subarray(t,t+16)}else o===q.PLAYREADY&&(h=ht(l.data))}if(!o||!h)return void this.log(`Unable to handle ${e} with key-system ${r}`);const a=Et(h),{keyIdToKeySessionPromise:l,mediaKeySessions:c}=this;let u=l[a];for(let t=0;t<c.length;t++){const e=c[t],n=e.decryptdata;if(!n.keyId)continue;const r=Et(n.keyId);if(a===r||-1!==n.uri.replace(/-/g,"").indexOf(a)){if(u=l[r],n.pssh)break;delete l[r],n.pssh=new Uint8Array(s),n.keyId=h,u=l[a]=u.then((()=>this.generateRequestWithPreferredKeySession(e,i,s,"encrypted-event-key-match"))),u.catch((t=>this.handleError(t)));break}}if(!u){if(o!==r)return void this.log(`Ignoring "${e}" with ${o} init data for selected key-system ${r}`);u=l[a]=this.getKeySystemSelectionPromise([o]).then((({keySystem:t,mediaKeys:e})=>{var n;this.throwIfDestroyed();const r=new Jt("ISO-23001-7",a,null!=(n=st(t))?n:"");return r.pssh=new Uint8Array(s),r.keyId=h,this.attemptSetMediaKeys(t,e).then((()=>{this.throwIfDestroyed();const n=this.createMediaKeySessionContext({decryptdata:r,keySystem:t,mediaKeys:e});return this.generateRequestWithPreferredKeySession(n,i,s,"encrypted-event-no-match")}))})),u.catch((t=>this.handleError(t)))}}))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},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.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(A.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(A.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(A.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(A.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:i,widevineLicenseUrl:s}=this.config,e=i[t];return e?e.licenseUrl:t===q.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(t){const i=this.getLicenseServerUrl(t);if(void 0===i)throw new Error(`no license server URL configured for key-system "${t}"`);return i}getServerCertificateUrl(t){const{drmSystems:i}=this.config,s=i[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const i=this.hls.levels,s=(t,i,s)=>!!t&&s.indexOf(t)===i,e=i.map((t=>t.audioCodec)).filter(s),n=i.map((t=>t.videoCodec)).filter(s);return e.length+n.length===0&&n.push("avc1.42e01e"),new Promise(((i,s)=>{const r=t=>{const h=t.shift();this.getMediaKeysPromise(h,e,n).then((t=>i({keySystem:h,mediaKeys:t}))).catch((i=>{t.length?r(t):s(i instanceof $r?i:new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:i,fatal:!0},i.message))}))};r(t)}))}requestMediaKeySystemAccess(t,i){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===nt&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,i)}getMediaKeysPromise(t,i,s){const e=function(t,i,s,e){let n;switch(t){case q.FAIRPLAY:n=["cenc","sinf"];break;case q.WIDEVINE:case q.PLAYREADY:n=["cenc"];break;case q.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,i,s,e){return[{initDataTypes:t,persistentState:e.persistentState||"optional",distinctiveIdentifier:e.distinctiveIdentifier||"optional",sessionTypes:e.sessionTypes||[e.sessionType||"temporary"],audioCapabilities:i.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:e.audioRobustness||"",encryptionScheme:e.audioEncryptionScheme||null}))),videoCapabilities:s.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:e.videoRobustness||"",encryptionScheme:e.videoEncryptionScheme||null})))}]}(n,i,s,e)}(t,i,s,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t];let r=null==n?void 0:n.keySystemAccess;if(!r){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(e)}`),r=this.requestMediaKeySystemAccess(t,e);const i=this.keySystemAccessPromises[t]={keySystemAccess:r};return r.catch((i=>{this.log(`Failed to obtain access to key-system "${t}": ${i}`)})),r.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const e=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),i.mediaKeys=s.createMediaKeys().then((i=>(this.log(`Media-keys created for "${t}"`),e.then((s=>s?this.setMediaKeysServerCertificate(i,t,s):i))))),i.mediaKeys.catch((i=>{this.error(`Failed to create media-keys for "${t}"}: ${i}`)})),i.mediaKeys}))}return r.then((()=>n.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:i,mediaKeys:s}){this.log(`Creating key-system session "${i}" keyId: ${Et(t.keyId||[])}`);const e=s.createSession(),n={decryptdata:t,keySystem:i,mediaKeys:s,mediaKeysSession:e,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(t){const i=t.decryptdata;if(i.pssh){const s=this.createMediaKeySessionContext(t),e=this.getKeyIdString(i);this.keyIdToKeySessionPromise[e]=this.generateRequestWithPreferredKeySession(s,"cenc",i.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 Et(t.keyId)}updateKeySession(t,i){var s;const e=t.mediaKeysSession;return this.log(`Updating key-session "${e.sessionId}" for keyID ${Et((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${i?i.byteLength:i})`),e.update(i)}selectKeySystemFormat(t){const i=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((i,s)=>{const e=et(this.config),n=t.map(tt).filter((t=>!!t&&-1!==e.indexOf(t)));return this.getKeySystemSelectionPromise(n).then((({keySystem:t})=>{const e=st(t);e?i(e):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)}))}loadKey(t){const i=t.keyInfo.decryptdata,s=this.getKeyIdString(i),e=`(keyId: ${s} format: "${i.keyFormat}" method: ${i.method} uri: ${i.uri})`;this.log(`Starting session for key ${e}`);let n=this.keyIdToKeySessionPromise[s];return n||(n=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(i).then((({keySystem:s,mediaKeys:n})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${e}`),this.attemptSetMediaKeys(s,n).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:n,decryptdata:i});return this.generateRequestWithPreferredKeySession(t,"cenc",i.pssh,"playlist-key")}))))),n.catch((t=>this.handleError(t)))),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),this.hls.trigger(A.ERROR,t instanceof $r?t.data:{type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const i=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[i];if(!s){const i=tt(t.keyFormat),s=i?[i]:et(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=et(this.config)),0===t.length)throw new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,i){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const e=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(i)}));return this.setMediaKeysQueue.push(e),e.then((()=>{this.log(`Media-keys set for "${t}"`),s.push(e),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===s.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,i,s,e){var n,r;const h=null==(n=this.config.drmSystems)||null==(r=n[t.keySystem])?void 0:r.generateRequest;if(h)try{const e=h.call(this.hls,i,s,t);if(!e)throw new Error("Invalid response from configured generateRequest filter");i=e.initDataType,s=t.decryptdata.pssh=e.initData?new Uint8Array(e.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 "${e}" (no initData)`),Promise.resolve(t);const a=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${e}": ${a} (init data type: ${i} length: ${s?s.byteLength:null})`);const l=new wn,c=t._onmessage=i=>{const s=t.mediaKeysSession;if(!s)return void l.emit("error",new Error("invalid state"));const{messageType:e,message:n}=i;this.log(`"${e}" message event for session "${s.sessionId}" message size: ${n.byteLength}`),"license-request"===e||"license-renewal"===e?this.renewLicense(t,n).catch((t=>{this.handleError(t),l.emit("error",t)})):"license-release"===e?t.keySystem===q.FAIRPLAY&&(this.updateKeySession(t,W("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${e}"`)},u=t._onkeystatuseschange=()=>{if(!t.mediaKeysSession)return void l.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const i=t.keyStatus;l.emit("keyStatus",i),"expired"===i&&(this.warn(`${t.keySystem} expired for key ${a}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",c),t.mediaKeysSession.addEventListener("keystatuseschange",u);const d=new Promise(((t,i)=>{l.on("error",i),l.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?i(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?i(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?i(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return t.mediaKeysSession.generateRequest(i,s).then((()=>{var i;this.log(`Request generated for key-session "${null==(i=t.mediaKeysSession)?void 0:i.sessionId}" keyId: ${a}`)})).catch((t=>{throw new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>d)).catch((i=>{throw l.removeAllListeners(),this.removeSession(t),i})).then((()=>(l.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((i,s)=>{this.log(`key status change "${i}" for keyStatuses keyId: ${Et("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Et(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=i}))}fetchServerCertificate(t){const i=this.config,s=new(0,i.loader)(i),e=this.getServerCertificateUrl(t);return e?(this.log(`Fetching server certificate for "${t}"`),new Promise(((n,r)=>{const h={responseType:"arraybuffer",url:e},o=i.certLoadPolicy.default;s.load(h,{loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},{onSuccess:t=>{n(t.data)},onError:(i,s,n)=>{r(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:k({url:h.url,data:void 0},i)},`"${t}" certificate request failed (${e}). Status: ${i.code} (${i.text})`))},onTimeout:(i,s,n)=>{r(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:h.url,data:void 0}},`"${t}" certificate request timed out (${e})`))},onAbort:()=>{r(new Error("aborted"))}})}))):Promise.resolve()}setMediaKeysServerCertificate(t,i,s){return new Promise(((e,n)=>{t.setServerCertificate(s).then((n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${i}"`),e(t)})).catch((t=>{n(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,i){return this.requestLicense(t,new Uint8Array(i)).then((i=>this.updateKeySession(t,new Uint8Array(i)).catch((t=>{throw new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,i){const s=String.fromCharCode.apply(null,new Uint16Array(i.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),i;const e=(new DOMParser).parseFromString(s,"application/xml"),n=e.querySelectorAll("HttpHeader");if(n.length>0){let i;for(let s=0,e=n.length;s<e;s++){var r,h;i=n[s];const e=null==(r=i.querySelector("name"))?void 0:r.textContent,o=null==(h=i.querySelector("value"))?void 0:h.textContent;e&&o&&t.setRequestHeader(e,o)}}const o=e.querySelector("Challenge"),a=null==o?void 0:o.textContent;if(!a)throw new Error("Cannot find <Challenge> in key message");return W(atob(a))}setupLicenseXHR(t,i,s,e){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,i,s,e)})).catch((r=>{if(!s.decryptdata)throw r;return t.open("POST",i,!0),n.call(this.hls,t,i,s,e)})).then((s=>(t.readyState||t.open("POST",i,!0),{xhr:t,licenseChallenge:s||e}))):(t.open("POST",i,!0),Promise.resolve({xhr:t,licenseChallenge:e}))}requestLicense(t,i){const s=this.config.keyLoadPolicy.default;return new Promise(((e,n)=>{const r=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${r}`);const h=new XMLHttpRequest;h.responseType="arraybuffer",h.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(4===h.readyState)if(200===h.status){this._requestLicenseFailureCount=0;let i=h.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);const s=this.config.licenseResponseCallback;if(s)try{i=s.call(this.hls,h,r,t)}catch(t){this.error(t)}e(i)}else{const o=s.errorRetry,a=o?o.maxNumRetry:0;this._requestLicenseFailureCount++,this._requestLicenseFailureCount>a||h.status>=400&&h.status<500?n(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:h,response:{url:r,data:void 0,code:h.status,text:h.statusText}},`License Request XHR failed (${r}). Status: ${h.status} (${h.statusText})`)):(this.warn(`Retrying license request, ${a-this._requestLicenseFailureCount+1} attempts left`),this.requestLicense(t,i).then(e,n))}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=h,this.setupLicenseXHR(h,r,t,i).then((({xhr:i,licenseChallenge:s})=>{t.keySystem==q.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(i,s)),i.send(s)}))}))}onMediaAttached(t,i){if(!this.config.emeEnabled)return;const s=i.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,i=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=i.length;Tr.CDMCleanupPromise=Promise.all(i.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"),i.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:i}){if(i&&this.config.emeEnabled&&!this.keyFormatPromise){const t=i.reduce(((t,i)=>(-1===t.indexOf(i.keyFormat)&&t.push(i.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:i,licenseXhr:s}=t;if(i){this.log(`Remove licenses and keys and close session ${i.sessionId}`),t._onmessage&&(i.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const e=this.mediaKeySessions.indexOf(t);return e>-1&&this.mediaKeySessions.splice(e,1),i.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>i.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}Tr.CDMCleanupPromise=void 0;class $r extends Error{constructor(t,i){super(i),this.data=void 0,t.error||(t.error=new Error(i)),this.data=t,t.err=t.error}}var Er,Ar,Mr;!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"}(Er||(Er={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(Ar||(Ar={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(Mr||(Mr={}));const Lr={[Mr.OBJECT]:["br","d","ot","tb"],[Mr.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Mr.SESSION]:["cid","pr","sf","sid","st","v"],[Mr.STATUS]:["bs","rtp"]};class xr{constructor(t,i){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof xr?t:new xr(t)))),this.value=t,this.params=i}}class Dr{constructor(t){this.description=void 0,this.description=t}}const Cr="Dict";const Ir="Bare Item",Rr="Boolean",Pr="Byte Sequence",Or="Decimal",Nr="Integer",Ur=/[\x00-\x1f\x7f]+/,Fr="Token",Br="Key";function jr(t,i,s){return function(t,i,s,e){return new Error(`failed to ${t} "${n=i,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n)}" as ${s}`,{cause:e});var n}("serialize",t,i,s)}function _r(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw jr(t,Nr);return t.toString()}function Gr(t,i){if(t<0)return-Gr(-t,i);const s=Math.pow(10,i);if(Math.abs(t*s%1-.5)<Number.EPSILON){const i=Math.floor(t*s);return(i%2==0?i:i+1)/s}return Math.round(t*s)/s}function Hr(t){const i=Gr(t,3);if(Math.floor(Math.abs(i)).toString().length>12)throw jr(t,Or);const s=i.toString();return s.includes(".")?s:`${s}.0`}const Kr="String";function Vr(t){const i=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw jr(i,Fr);return i}function zr(t){switch(typeof t){case"number":if(!T(t))throw jr(t,Ir);return Number.isInteger(t)?_r(t):Hr(t);case"string":return function(t){if(Ur.test(t))throw jr(t,Kr);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Vr(t);case"boolean":return function(t){if("boolean"!=typeof t)throw jr(t,Rr);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${_r(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return function(t){if(!1===ArrayBuffer.isView(t))throw jr(t,Pr);return`:${i=t,btoa(String.fromCharCode(...i))}:`;var i}(t);if(t instanceof Dr)return Vr(t);default:throw jr(t,Ir)}}function Wr(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw jr(t,Br);return t}function Xr(t){return null==t?"":Object.entries(t).map((([t,i])=>!0===i?`;${Wr(t)}`:`;${Wr(t)}=${zr(i)}`)).join("")}function qr(t){return t instanceof xr?`${zr(t.value)}${Xr(t.params)}`:zr(t)}const Yr=t=>"ot"===t||"sf"===t||"st"===t,Jr=t=>"number"==typeof t?T(t):null!=t&&""!==t&&!1!==t,Qr=t=>Math.round(t),Zr=t=>100*Qr(t/100),th={br:Qr,d:Qr,bl:Zr,dl:Zr,mtp:Zr,nor:(t,i)=>(null!=i&&i.baseUrl&&(t=function(t,i){const s=new URL(t),e=new URL(i);if(s.origin!==e.origin)return t;const n=s.pathname.split("/").slice(1),r=e.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")}(t,i.baseUrl)),encodeURIComponent(t)),rtp:Zr,tb:Qr};function ih(t,i={}){return t?function(t,i){return function(t,i={whitespace:!0}){if("object"!=typeof t)throw jr(t,Cr);const s=t instanceof Map?t.entries():Object.entries(t),e=null!=i&&i.whitespace?" ":"";return Array.from(s).map((([t,i])=>{i instanceof xr==0&&(i=new xr(i));let s=Wr(t);var e;return!0===i.value?s+=Xr(i.params):(s+="=",Array.isArray(i.value)?s+=`(${(e=i).value.map(qr).join(" ")})${Xr(e.params)}`:s+=qr(i)),s})).join(`,${e}`)}(t,i)}(function(t,i){const s={};if(null==t||"object"!=typeof t)return s;const e=Object.keys(t).sort(),n=S({},th,null==i?void 0:i.formatters),r=null==i?void 0:i.filter;return e.forEach((e=>{if(null!=r&&r(e))return;let h=t[e];const o=n[e];o&&(h=o(h,i)),"v"===e&&1===h||"pr"==e&&1===h||Jr(h)&&(Yr(e)&&"string"==typeof h&&(h=new Dr(h)),s[e]=h)})),s}(t,i),S({whitespace:!1},i)):""}const sh=/CMCD=[^&#]+/;function eh(t,i,s,e){t&&Object.keys(i).forEach((n=>{const r=t.filter((t=>t.groupId===n)).map((t=>{const r=S({},t);return r.details=void 0,r.attrs=new O(r.attrs),r.url=r.attrs.URI=nh(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),r.groupId=r.attrs["GROUP-ID"]=i[n],r.attrs["PATHWAY-ID"]=e,r}));t.push(...r)}))}function nh(t,i,s,e){const{HOST:n,PARAMS:r,[s]:h}=e;let o;i&&(o=null==h?void 0:h[i],o&&(t=o));const a=new self.URL(t);return n&&!o&&(a.host=n),r&&Object.keys(r).sort().forEach((t=>{t&&a.searchParams.set(t,r[t])})),a.href}const rh=/^age:\s*[\d.]+\s*$/im;class hh{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 F,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,i,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=i,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:i}=this;if(!t||!i)return;const s=this.loader=new self.XMLHttpRequest,e=this.stats;e.loading.first=0,e.loaded=0,e.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return n(s,i.url)})).catch((()=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",i.url,!0),n(s,i.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,i,t)})).catch((t=>{this.callbacks.onError({code:s.status,text:t.message},i,s,e)})):this.openAndSendXhr(s,i,t)}openAndSendXhr(t,i,s){t.readyState||t.open("GET",i.url,!0);const e=i.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:r}=s.loadPolicy;if(e)for(const i in e)t.setRequestHeader(i,e[i]);i.rangeEnd&&t.setRequestHeader("Range","bytes="+i.rangeStart+"-"+(i.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=i.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&T(n)?n:r,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:i,stats:s}=this;if(!t||!i)return;const e=i.readyState,n=this.config;if(!s.aborted&&e>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===e)){self.clearTimeout(this.requestTimeout),i.onreadystatechange=null,i.onprogress=null;const e=i.status,r="text"===i.responseType?i.responseText:null;if(e>=200&&e<300){const n=null!=r?r:i.response;if(null!=n){if(s.loading.end=Math.max(self.performance.now(),s.loading.first),s.loaded=s.total="arraybuffer"===i.responseType?n.byteLength:n.length,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const r=this.callbacks.onProgress;if(r&&r(s,t,n,i),!this.callbacks)return;return void this.callbacks.onSuccess({url:i.responseURL,data:n,code:e},s,t,i)}}const h=n.loadPolicy.errorRetry;vs(h,s.retry,!1,{url:t.url,data:void 0,code:e})?this.retry(h):(I.error(`${e} while loading ${t.url}`),this.callbacks.onError({code:e,text:i.statusText},t,i,s))}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(vs(t,this.stats.retry,!0))this.retry(t);else{var i;I.warn(`timeout while loading ${null==(i=this.context)?void 0:i.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:i,stats:s}=this;this.retryDelay=ds(t,s.retry),s.retry++,I.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==i?void 0:i.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 i=this.stats;i.loaded=t.loaded,t.lengthComputable&&(i.total=t.total)}getCacheAge(){let t=null;if(this.loader&&rh.test(this.loader.getAllResponseHeaders())){const i=this.loader.getResponseHeader("age");t=i?parseFloat(i):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 oh=/(\d+)-(\d+)\/(\d+)/;class ah{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||lh,this.controller=new self.AbortController,this.stats=new F}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,i,s){const e=this.stats;if(e.loading.start)throw new Error("Loader can only be used once.");e.loading.start=self.performance.now();const n=function(t,i){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:i,headers:new self.Headers(S({},t.headers))};return t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),s}(t,this.controller.signal),r=s.onProgress,h="arraybuffer"===t.responseType,o=h?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:l}=i.loadPolicy;this.context=t,this.config=i,this.callbacks=s,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),i.timeout=a&&T(a)?a:l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(e,t,this.response)}),i.timeout),self.fetch(this.request).then((n=>{this.response=this.loader=n;const o=Math.max(self.performance.now(),e.loading.start);if(self.clearTimeout(this.requestTimeout),i.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(e,t,this.response)}),l-(o-e.loading.start)),!n.ok){const{status:t,statusText:i}=n;throw new ch(i||"fetch, bad network response",t,n)}return e.loading.first=o,e.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const i=oh.exec(t);if(i)return parseInt(i[2])-parseInt(i[1])+1}(i);if(T(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(n.headers)||e.total,r&&T(i.highWaterMark)?this.loadProgressively(n,e,t,i.highWaterMark,r):h?n.arrayBuffer():"json"===t.responseType?n.json():n.text()})).then((n=>{const h=this.response;if(!h)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),e.loading.end=Math.max(self.performance.now(),e.loading.first);const a=n[o];a&&(e.loaded=e.total=a);const l={url:h.url,data:n,code:h.status};r&&!T(i.highWaterMark)&&r(e,t,n,h),s.onSuccess(l,e,t,h)})).catch((i=>{self.clearTimeout(this.requestTimeout),e.aborted||s.onError({code:i&&i.code||0,text:i?i.message:null},t,i?i.details:null,e)}))}getCacheAge(){let t=null;if(this.response){const i=this.response.headers.get("age");t=i?parseFloat(i):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,i,s,e=0,n){const r=new ve,h=t.body.getReader(),o=()=>h.read().then((h=>{if(h.done)return r.dataLength&&n(i,s,r.flush(),t),Promise.resolve(new ArrayBuffer(0));const a=h.value,l=a.length;return i.loaded+=l,l<e||r.dataLength?(r.push(a),r.dataLength>=e&&n(i,s,r.flush(),t)):n(i,s,a,t),o()})).catch((()=>Promise.reject()));return o()}}function lh(t,i){return new self.Request(t.url,i)}class ch extends Error{constructor(t,i,s){super(t),this.code=void 0,this.details=void 0,this.code=i,this.details=s}}const uh=/\s/,dh={newCue(t,i,s,e){const n=[];let r,h,o,a,l;const c=self.VTTCue||self.TextTrackCue;for(let d=0;d<e.rows.length;d++)if(r=e.rows[d],o=!0,a=0,l="",!r.isEmpty()){var u;for(let t=0;t<r.chars.length;t++)uh.test(r.chars[t].uchar)&&o?a++:(l+=r.chars[t].uchar,o=!1);r.cueStartTime=i,i===s&&(s+=1e-4),a>=16?a--:a++;const e=sr(l.trim()),f=or(i,s,e);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(h=new c(i,s,e),h.id=f,h.line=d+1,h.align="left",h.position=10+Math.min(80,10*Math.floor(8*a/32)),n.push(h))}return t&&n.length&&(n.sort(((t,i)=>"auto"===t.line||"auto"===i.line?0:t.line>8&&i.line>8?i.line-t.line:t.line-i.line)),n.forEach((i=>Bi(t,i)))),n}},fh=k(k({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:hh,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:i,hls:s}=this,{autoLevelEnabled:e,media:n}=s;if(!t||!n)return;const r=performance.now(),h=i?i.stats:t.stats,o=i?i.duration:t.duration,a=r-h.loading.start,l=s.minAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||t.level<=l)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!e||n.paused||!n.playbackRate||!n.readyState)return;const c=s.mainForwardBufferInfo;if(null===c)return;const u=this.bwEstimator.getEstimateTTFB(),d=Math.abs(n.playbackRate);if(a<=Math.max(u,o/(2*d)*1e3))return;const f=c.len/d,v=h.loading.first?h.loading.first-h.loading.start:-1,p=h.loaded&&v>-1,g=this.getBwEstimate(),m=s.levels,y=h.total||Math.max(h.loaded,Math.round(o*m[t.level].averageBitrate/8));let w=p?a-v:a;w<1&&p&&(w=Math.min(a,8*h.loaded/g));const b=p?1e3*h.loaded/w:0,k=b?(y-h.loaded)/b:8*y/g+u/1e3;if(k<=f)return;const S=b?8*b:g;let $,E=Number.POSITIVE_INFINITY;for($=t.level-1;$>l&&(E=this.getTimeToLoadFrag(u/1e3,S,o*m[$].maxBitrate,!m[$].details),!(E<f));$--);if(E>=k)return;if(E>10*o)return;s.nextLoadLevel=s.nextAutoLevel=$,p?this.bwEstimator.sample(a-Math.min(u,v),h.loaded):this.bwEstimator.sampleTTFB(a);const M=m[$].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>M&&this.resetEstimator(M),this.clearTimer(),I.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${k.toFixed(3)} s\n Estimated load time for down switch fragment: ${E.toFixed(3)} s\n TTFB estimate: ${0|v} ms\n Current BW estimate: ${T(g)?0|g:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${$} @ ${0|M} bps`),s.trigger(A.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:h})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(I.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 ks(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.FRAG_LOADING,this.onFragLoading,this),t.on(A.FRAG_LOADED,this.onFragLoaded,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this),t.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.FRAG_LOADING,this.onFragLoading,this),t.off(A.FRAG_LOADED,this.onFragLoaded,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this),t.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(A.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,i){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,i){const s=i.frag;var e;this.ignoreFragment(s)||(s.bitrateTest||(this.fragCurrent=s,this.partCurrent=null!=(e=i.part)?e:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(t,i){this.clearTimer()}onError(t,i){if(!i.fatal)switch(i.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{const t=i.frag,{fragCurrent:s,partCurrent:e}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const i=performance.now(),s=e?e.stats:t.stats,n=i-s.loading.start,r=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&r>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(n-Math.min(t,r),s.loaded)}else this.bwEstimator.sampleTTFB(n)}break}}}getTimeToLoadFrag(t,i,s,e){return t+s/i+(e?this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:e}=i.stats,n=e.end-e.start;T(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(t,{frag:i,part:s}){const e=s?s.stats:i.stats;if(i.type===Ii&&this.bwEstimator.sampleTTFB(e.loading.first-e.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=this.hls.levels[i.level],n=(t.loaded?t.loaded.bytes:0)+e.loaded,r=(t.loaded?t.loaded.duration:0)+(s?s.duration:i.duration);t.loaded={bytes:n,duration:r},t.realBitrate=Math.round(8*n/r)}i.bitrateTest?(this.onFragBuffered(A.FRAG_BUFFERED,{stats:e,frag:i,part:s,id:i.type}),i.bitrateTest=!1):this.lastLoadedFragLevel=i.level}}onFragBuffered(t,i){const{frag:s,part:e}=i,n=null!=e&&e.stats.loaded?e.stats:s.stats;if(n.aborted)return;if(this.ignoreFragment(s))return;const r=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(r,n.loaded),n.bwEstimate=this.getBwEstimate(),this.bitrateTestDelay=s.bitrateTest?r/1e3:0}ignoreFragment(t){return t.type!==Ii||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,s=this.getBwEstimate(),e=this.findBestLevel(s,i,t,0,this.hls.config.maxStarvationDelay,1,1);if(e>-1)return e;const n=this.hls.firstLevel,r=Math.min(Math.max(n,i),t);return I.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${r}`),r}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||i&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const e=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const i=this.hls.levels;if(i.length>Math.max(t,e)&&i[t].loadError<=i[e].loadError)return t}return this._nextAutoLevel=e,this.nextAutoLevelKey=this.getAutoLevelKey(),e}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:i,hls:s}=this,{maxAutoLevel:e,config:n,minAutoLevel:r}=s,h=i?i.duration:t?t.duration:0,o=this.getBwEstimate(),a=this.getStarvationDelay();let l=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(a){const t=this.findBestLevel(o,r,e,a,0,l,c);if(t>=0)return t}let u=h?Math.min(h,n.maxStarvationDelay):n.maxStarvationDelay;if(!a){const t=this.bitrateTestDelay;t&&(u=(h?Math.min(h,n.maxLoadingDelay):n.maxLoadingDelay)-t,I.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),l=c=1)}const d=this.findBestLevel(o,r,e,a,u,l,c);if(I.info(`[abr] ${a?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`),d>-1)return d;const f=s.levels[r],v=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==v?void 0:v.bitrate)?r:s.loadLevel}getStarvationDelay(){const t=this.hls,i=t.media;if(!i)return 1/0;const s=i&&0!==i.playbackRate?Math.abs(i.playbackRate):1,e=t.mainForwardBufferInfo;return(e?e.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,i,s,e,n,r,h){var o;const a=e+n,l=this.lastLoadedFragLevel,c=-1===l?this.hls.firstLevel:l,{fragCurrent:u,partCurrent:d}=this,{levels:f,allAudioTracks:v,loadLevel:p,config:g}=this.hls;if(1===f.length)return 0;const m=f[c],y=!(null==m||null==(o=m.details)||!o.live),w=-1===p||-1===l;let b,k="SDR",S=(null==m?void 0:m.frameRate)||0;const{audioPreference:$,videoPreference:E}=g,A=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,i)=>{let s=t.groups[i.groupId];s||(s=t.groups[i.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(i);const e=i.channels||"2";return s.channels[e]=(s.channels[e]||0)+1,s.hasDefault=s.hasDefault||i.default,s.hasAutoSelect=s.hasAutoSelect||i.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(v));if(w){if(-1!==this.firstSelection)return this.firstSelection;const e=this.codecTiers||(this.codecTiers=function(t,i,s,e){return t.slice(s,e+1).reduce(((t,s)=>{if(!s.codecSet)return t;const e=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!e,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const r=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,r),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,e&&e.forEach((t=>{if(!t)return;const s=i.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||i.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!i.hasDefaultAudio&&!i.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]})))})),t}),{})}(f,A,i,s)),n=function(t,i,s,e,n){const r=Object.keys(t),h=null==e?void 0:e.channels,o=null==e?void 0:e.audioCodec,a=h&&2===parseInt(h);let l=!0,c=!1,u=1/0,d=1/0,f=1/0,v=0,p=[];const{preferHDR:g,allowedVideoRanges:m}=function(t,i){let s=!1,e=[];return t&&(s="SDR"!==t,e=[t]),i&&(e=i.allowedVideoRanges||Qi.slice(0),s=void 0!==i.preferHDR?i.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),i=matchMedia("bad query");if(t.media!==i.media)return!0===t.matches}return!1}(),e=s?e.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:s,allowedVideoRanges:e}}(i,n);for(let i=r.length;i--;){const s=t[r[i]];l=s.channels[2]>0,u=Math.min(u,s.minHeight),d=Math.min(d,s.minFramerate),f=Math.min(f,s.minBitrate);const e=m.filter((t=>s.videoRanges[t]>0));e.length>0&&(c=!0,p=e)}u=T(u)?u:0,d=T(d)?d:0;const y=Math.max(1080,u),w=Math.max(30,d);return f=T(f)?f:s,s=Math.max(f,s),c||(i=void 0,p=[]),{codecSet:r.reduce(((i,e)=>{const n=t[e];if(e===i)return i;if(n.minBitrate>s)return As(e,`min bitrate of ${n.minBitrate} > current estimate of ${s}`),i;if(!n.hasDefaultAudio)return As(e,"no renditions with default or auto-select sound found"),i;if(o&&e.indexOf(o.substring(0,4))%5!=0)return As(e,`audio codec preference "${o}" not found`),i;if(h&&!a){if(!n.channels[h])return As(e,`no renditions with ${h} channel sound found (channels options: ${Object.keys(n.channels)})`),i}else if((!o||a)&&l&&0===n.channels[2])return As(e,"no renditions with stereo sound found"),i;return n.minHeight>y?(As(e,`min resolution of ${n.minHeight} > maximum of ${y}`),i):n.minFramerate>w?(As(e,`min framerate of ${n.minFramerate} > maximum of ${w}`),i):p.some((t=>n.videoRanges[t]>0))?n.maxScore<v?(As(e,`max score of ${n.maxScore} < selected max of ${v}`),i):i&&(ci(e)>=ci(i)||n.fragmentError>t[i].fragmentError)?i:(v=n.maxScore,e):(As(e,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),i)}),void 0),videoRanges:p,preferHDR:g,minFramerate:d,minBitrate:f}}(e,k,t,$,E),{codecSet:r,videoRanges:h,minFramerate:o,minBitrate:a,preferHDR:l}=n;b=r,k=l?h[h.length-1]:h[0],S=o,t=Math.max(t,a),I.log(`[abr] picked start tier ${JSON.stringify(n)}`)}else b=null==m?void 0:m.codecSet,k=null==m?void 0:m.videoRange;const M=d?d.duration:u?u.duration:0,L=this.bwEstimator.getEstimateTTFB()/1e3,x=[];for(let o=s;o>=i;o--){var D;const i=f[o],u=o>c;if(!i)continue;if(g.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&$s(i,A,k,S,t,$)?(i.supportedPromise=Es(i,A,s),i.supportedPromise.then((t=>{if(!this.hls)return;i.supportedResult=t;const s=this.hls.levels,e=s.indexOf(i);t.error?I.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${e} ${JSON.stringify(t)}`):t.supported||(I.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${e} ${JSON.stringify(t)}`),e>-1&&s.length>1&&(I.log(`[abr] Removing unsupported level ${e}`),this.hls.removeLevel(e)))}))):i.supportedResult=Ss}if(b&&i.codecSet!==b||k&&i.videoRange!==k||u&&S>i.frameRate||!u&&S>0&&S<i.frameRate||i.supportedResult&&(null==(D=i.supportedResult.decodingInfoResults)||!D[0].smooth)){x.push(o);continue}const v=i.details,E=(d?null==v?void 0:v.partTarget:null==v?void 0:v.averagetargetduration)||M;let C;C=u?h*t:r*t;const R=M&&e>=2*M&&0===n?f[o].averageBitrate:f[o].maxBitrate,P=this.getTimeToLoadFrag(L,C,R*E,void 0===v);if(C>=R&&(o===l||0===i.loadError&&0===i.fragmentError)&&(P<=L||!T(P)||y&&!this.bitrateTestDelay||P<a)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(x.length&&I.trace(`[abr] Skipped level(s) ${x.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[x[0]].codecs}" ${f[x[0]].videoRange}; not compatible with "${m.codecs}" ${k}`),I.info(`[abr] switch candidate:${c}->${o} adjustedbw(${Math.round(C)})-bitrate=${Math.round(C-R)} ttfb:${L.toFixed(1)} avgDuration:${E.toFixed(1)} maxFetchDuration:${a.toFixed(1)} fetchDuration:${P.toFixed(1)} firstSelection:${w} codecSet:${b} videoRange:${k} hls.loadLevel:${p}`)),w&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:i,minAutoLevel:s}=this.hls,e=Math.min(Math.max(t,s),i);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}},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=()=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=()=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:i}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(A.MEDIA_ATTACHED,{media:t,mediaSource:i})),i&&i.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:i}=this;t!==i&&I.error(`Media element src was set while attaching MediaSource (${i} > ${t})`)},this.hls=t;const i="[buffer-controller]";var s;this.appendSource=(s=ni(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.log=I.log.bind(I,i),this.warn=I.warn.bind(I,i),this.error=I.error.bind(I,i),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(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.BUFFER_RESET,this.onBufferReset,this),t.on(A.BUFFER_APPENDING,this.onBufferAppending,this),t.on(A.BUFFER_CODECS,this.onBufferCodecs,this),t.on(A.BUFFER_EOS,this.onBufferEos,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(A.FRAG_PARSED,this.onFragParsed,this),t.on(A.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.BUFFER_RESET,this.onBufferReset,this),t.off(A.BUFFER_APPENDING,this.onBufferAppending,this),t.off(A.BUFFER_CODECS,this.onBufferCodecs,this),t.off(A.BUFFER_EOS,this.onBufferEos,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(A.FRAG_PARSED,this.onFragParsed,this),t.off(A.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new En(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,i){let s=2;(i.audio&&!i.video||!i.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,i){const s=this.media=i.media,e=ni(this.appendSource);if(s&&e){var n;const t=this.mediaSource=new e;this.log(`created media source: ${null==(n=t.constructor)?void 0:n.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 i=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&t instanceof e,Mn(s),function(t,i){const s=self.document.createElement("source");s.type="video/mp4",s.src=i,t.appendChild(s)}(s,i),s.load()}catch(t){s.src=i}else s.src=i;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:i,_objectUrl:s}=this;if(i){if(this.log("media source detaching"),"open"===i.readyState)try{i.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&Mn(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(A.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer(),this.hls.resumeBuffering()}resetBuffer(t){const i=this.sourceBuffer[t];try{var s;i&&(this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i))}catch(i){this.warn(`onBufferReset ${t}`,i)}}onBufferCodecs(t,i){const s=this.getSourceBufferTypes().length,e=Object.keys(i);if(e.forEach((t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var e;const{id:n,codec:r,levelCodec:h,container:o,metadata:a}=i[t],l=vi(s.codec,s.levelCodec),c=null==l?void 0:l.replace(An,"$1");let u=vi(r,h);const d=null==(e=u)?void 0:e.replace(An,"$1");u&&c!==d&&("audio"===t.slice(0,5)&&(u=fi(u,this.appendSource)),this.appendChangeType(t,`${o};codecs=${u}`),this.log(`switching codec ${l} to ${u}`),this.tracks[t]={buffer:s.buffer,codec:r,container:o,levelCodec:h,metadata:a,id:n})}}else this.pendingTracks[t]=i[t]})),s)return;const n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${e.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,i){const{operationQueue:s}=this,e={execute:()=>{const e=this.sourceBuffer[t];e&&(this.log(`changing ${t} sourceBuffer type to ${i}`),e.changeType(i)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:i=>{this.warn(`Failed to change ${t} SourceBuffer type`,i)}};s.append(e,t,!!this.pendingTracks[t])}onBufferAppending(t,i){const{hls:s,operationQueue:e,tracks:n}=this,{data:r,type:h,frag:o,part:a,chunkMeta:l}=i,c=l.buffering[h],u=self.performance.now();c.start=u;const d=o.stats.buffering,f=a?a.stats.buffering:null;0===d.start&&(d.start=u),f&&0===f.start&&(f.start=u);const v=n.audio;let p=!1;"audio"===h&&"audio/mpeg"===(null==v?void 0:v.container)&&(p=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const g=o.start,m={execute:()=>{if(c.executeStart=self.performance.now(),p){const t=this.sourceBuffer[h];if(t){const i=g-t.timestampOffset;Math.abs(i)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${g} (delta: ${i}) sn: ${o.sn})`),t.timestampOffset=g)}}this.appendExecutor(r,h)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();c.executeEnd=c.end=t,0===d.first&&(d.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:i}=this,s={};for(const t in i)s[t]=js.getBuffered(i[t]);this.appendErrors[h]=0,"audio"===h||"video"===h?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(A.BUFFER_APPENDED,{type:h,frag:o,part:a,chunkMeta:l,parent:o.type,timeRanges:s})},onError:t=>{const i={type:M.MEDIA_ERROR,parent:o.type,details:L.BUFFER_APPEND_ERROR,sourceBufferName:h,frag:o,part:a,chunkMeta:l,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)i.details=L.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[h];i.details=L.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${s.config.appendErrorMaxRetry} times to append segment in "${h}" sourceBuffer`),t>=s.config.appendErrorMaxRetry&&(i.fatal=!0)}s.trigger(A.ERROR,i)}};e.append(m,h,!!this.pendingTracks[h])}onBufferFlushing(t,i){const{operationQueue:s}=this,e=t=>({execute:this.removeExecutor.bind(this,t,i.startOffset,i.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(A.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove from ${t} SourceBuffer`,i)}});i.type?s.append(e(i.type),i.type):this.getSourceBufferTypes().forEach((t=>{s.append(e(t),t)}))}onFragParsed(t,i){const{frag:s,part:e}=i,n=[],r=e?e.elementaryStreams:s.elementaryStreams;r[_]?n.push("audiovideo"):(r[B]&&n.push("audio"),r[j]&&n.push("video")),0===n.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,e&&(e.stats.buffering.end=t),this.hls.trigger(A.FRAG_BUFFERED,{frag:s,part:e,stats:e?e.stats:s.stats,id:s.type})}),n)}onFragChanged(t,i){this.trimBuffers()}onBufferEos(t,i){this.getSourceBufferTypes().reduce(((t,s)=>{const e=this.sourceBuffer[s];return!e||i.type&&i.type!==s||(e.ending=!0,e.ended||(e.ended=!0,this.log(`${s} sourceBuffer now EOS`))),t&&!(e&&!e.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const i=this.sourceBuffer[t];i&&(i.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:i}){i.fragments.length&&(this.details=i,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:i,media:s}=this;if(!s||null===i)return;if(!this.getSourceBufferTypes().length)return;const e=t.config,n=s.currentTime,r=i.levelTargetDuration,h=i.live&&null!==e.liveBackBufferLength?e.liveBackBufferLength:e.backBufferLength;if(T(h)&&h>0){const t=Math.max(h,r),i=Math.floor(n/r)*r-t;this.flushBackBuffer(n,r,i)}if(T(e.frontBufferFlushThreshold)&&e.frontBufferFlushThreshold>0){const t=Math.max(e.maxBufferLength,e.frontBufferFlushThreshold),i=Math.max(t,r),s=Math.floor(n/r)*r+i;this.flushFrontBuffer(n,r,s)}}flushBackBuffer(t,i,s){const{details:e,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach((r=>{const h=n[r];if(h){const n=js.getBuffered(h);if(n.length>0&&s>n.start(0)){if(this.hls.trigger(A.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=e&&e.live)this.hls.trigger(A.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(h.ended&&n.end(n.length-1)-t<2*i)return void this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);this.hls.trigger(A.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}}))}flushFrontBuffer(t,i,s){const{sourceBuffer:e}=this;this.getSourceBufferTypes().forEach((n=>{const r=e[n];if(r){const e=js.getBuffered(r),h=e.length;if(h<2)return;const o=e.start(h-1),a=e.end(h-1);if(s>o||t>=o&&t<=a)return;if(r.ended&&t-a<2*i)return void this.log(`Cannot flush ${n} front buffer while SourceBuffer is in ended state`);this.hls.trigger(A.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:n})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:i,media:s,mediaSource:e}=this,n=t.fragments[0].start+t.totalduration,r=s.duration,h=T(e.duration)?e.duration:0;t.live&&i.config.liveDurationInfinity?(e.duration=1/0,this.updateSeekableRange(t)):(n>h&&n>r||!T(r))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),e.duration=n)}updateSeekableRange(t){const i=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=i&&i.setLiveSeekableRange){const e=Math.max(0,s[0].start),n=Math.max(e,e+t.totalduration);this.log(`Media Source duration is set to ${i.duration}. Setting seekable range to ${e}-${n}.`),i.setLiveSeekableRange(e,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:i,pendingTracks:s}=this,e=Object.keys(s).length;if(e&&(!t||2===e||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(A.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{i.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:i,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const n in t)if(!i[n]){var e;const r=t[n];if(!r)throw Error(`source buffer exists for track ${n}, however track does not`);let h=-1===(null==(e=r.levelCodec)?void 0:e.indexOf(","))?r.levelCodec:r.codec;h&&"audio"===n.slice(0,5)&&(h=fi(h,this.appendSource));const o=`${r.container};codecs=${h}`;this.log(`creating sourceBuffer(${o})`);try{const t=i[n]=s.addSourceBuffer(o),e=n;this.addBufferListener(e,"updatestart",this._onSBUpdateStart),this.addBufferListener(e,"updateend",this._onSBUpdateEnd),this.addBufferListener(e,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((t,i)=>{const s=i.removedRanges;null!=s&&s.length&&this.hls.trigger(A.BUFFER_FLUSHED,{type:n})})),this.tracks[n]={buffer:t,codec:h,container:r.container,levelCodec:r.levelCodec,metadata:r.metadata,id:r.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:o})}}}get mediaSrc(){var t,i;const s=(null==(t=this.media)||null==(i=t.querySelector)?void 0:i.call(t,"source"))||this.media;return null==s?void 0:s.src}_onSBUpdateStart(t){const{operationQueue:i}=this;i.current(t).onStart()}_onSBUpdateEnd(t){var i;if("closed"===(null==(i=this.mediaSource)?void 0:i.readyState))return void this.resetBuffer(t);const{operationQueue:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t)}_onSBUpdateError(t,i){var s;const e=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${e}`,i),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:e,fatal:!1});const n=this.operationQueue.current(t);n&&n.onError(e)}removeExecutor(t,i,s){const{media:e,mediaSource:n,operationQueue:r,sourceBuffer:h}=this,o=h[t];if(!e||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void r.shiftAndExecuteNext(t);const a=T(e.duration)?e.duration:1/0,l=T(n.duration)?n.duration:1/0,c=Math.max(0,i),u=Math.min(s,a,l);u>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${u}] from the ${t} SourceBuffer`),o.remove(c,u)):r.shiftAndExecuteNext(t)}appendExecutor(t,i){const s=this.sourceBuffer[i];if(s)s.ended=!1,s.appendBuffer(t);else if(!this.pendingTracks[i])throw new Error(`Attempting to append to the ${i} SourceBuffer, but it does not exist`)}blockBuffers(t,i=this.getSourceBufferTypes()){if(!i.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:s}=this,e=i.map((t=>s.appendBlocker(t)));Promise.all(e).then((()=>{t(),i.forEach((t=>{const i=this.sourceBuffer[t];null!=i&&i.updating||s.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,i,s){const e=this.sourceBuffer[t];if(!e)return;const n=s.bind(this,t);this.listeners[t].push({event:i,listener:n}),e.addEventListener(i,n)}removeBufferListeners(t){const i=this.sourceBuffer[t];i&&this.listeners[t].forEach((t=>{i.removeEventListener(t.event,t.listener)}))}},capLevelController:kr,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=I.log.bind(I,"[info]:"),this.warn=I.warn.bind(I,"[warning]:"),this.error=I.error.bind(I,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(A.ERROR,this.onError,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(A.ERROR,this.onError,this),t.off(A.ERROR,this.onErrorOut,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.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)===Ii?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,i){var s,e;if(i.fatal)return;const n=this.hls,r=i.context;switch(i.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:return void(i.errorAction=this.getFragRetryOrSwitchAction(i));case L.FRAG_PARSING_ERROR:if(null!=(s=i.frag)&&s.gap)return void(i.errorAction={action:0,flags:0});case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:return i.errorAction=this.getFragRetryOrSwitchAction(i),void(i.errorAction.action=2);case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var h,o;const t=i.parent===Ii?i.level:n.loadLevel;i.details===L.LEVEL_EMPTY_ERROR&&null!=(h=i.context)&&null!=(o=h.levelDetails)&&o.live?i.errorAction=this.getPlaylistRetryOrSwitchAction(i,t):(i.levelRetry=!1,i.errorAction=this.getLevelSwitchAction(i,t))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(i.errorAction=this.getPlaylistRetryOrSwitchAction(i,r.level)));case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=n.levels[n.loadLevel];if(t&&(r.type===Di&&t.hasAudioGroup(r.groupId)||r.type===Ci&&t.hasSubtitleGroup(r.groupId)))return i.errorAction=this.getPlaylistRetryOrSwitchAction(i,n.loadLevel),i.errorAction.action=2,void(i.errorAction.flags=1)}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=n.levels[n.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?i.errorAction={action:2,flags:2,hdcpLevel:s}:this.keySystemError(i)}return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:return void(i.errorAction=this.getLevelSwitchAction(i,null!=(e=i.level)?e:n.loadLevel));case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:return void(i.errorAction={action:0,flags:0})}i.type===M.KEY_SYSTEM_ERROR&&this.keySystemError(i)}keySystemError(t){const i=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,i)}getPlaylistRetryOrSwitchAction(t,i){const s=us(this.hls.config.playlistLoadPolicy,t),e=this.playlistError++;if(vs(s,e,cs(t),t.response))return{action:5,flags:0,retryConfig:s,retryCount:e};const n=this.getLevelSwitchAction(t,i);return s&&(n.retryConfig=s,n.retryCount=e),n}getFragRetryOrSwitchAction(t){const i=this.hls,s=this.getVariantLevelIndex(t.frag),e=i.levels[s],{fragLoadPolicy:n,keyLoadPolicy:r}=i.config,h=us(t.details.startsWith("key")?r:n,t),o=i.levels.reduce(((t,i)=>t+i.fragmentError),0);if(e&&(t.details!==L.FRAG_GAP&&e.fragmentError++,vs(h,o,cs(t),t.response)))return{action:5,flags:0,retryConfig:h,retryCount:o};const a=this.getLevelSwitchAction(t,s);return h&&(a.retryConfig=h,a.retryCount=o),a}getLevelSwitchAction(t,i){const s=this.hls;null==i&&(i=s.loadLevel);const e=this.hls.levels[i];if(e){var n,r;const i=t.details;e.loadError++,i===L.BUFFER_APPEND_ERROR&&e.fragmentError++;let a=-1;const{levels:l,loadLevel:c,minAutoLevel:u,maxAutoLevel:d}=s;s.autoLevelEnabled||(s.loadLevel=-1);const f=null==(n=t.frag)?void 0:n.type,v=(f===Ri&&i===L.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(i===L.BUFFER_ADD_CODEC_ERROR||i===L.BUFFER_APPEND_ERROR))&&l.some((({audioCodec:t})=>e.audioCodec!==t)),p="video"===t.sourceBufferName&&(i===L.BUFFER_ADD_CODEC_ERROR||i===L.BUFFER_APPEND_ERROR)&&l.some((({codecSet:t,audioCodec:i})=>e.codecSet!==t&&e.audioCodec===i)),{type:g,groupId:m}=null!=(r=t.context)?r:{};for(let s=l.length;s--;){const n=(s+c)%l.length;if(n!==c&&n>=u&&n<=d&&0===l[n].loadError){var h,o;const s=l[n];if(i===L.FRAG_GAP&&f===Ii&&t.frag){const i=l[n].details;if(i){const s=gs(t.frag,i.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(g===Di&&s.hasAudioGroup(m)||g===Ci&&s.hasSubtitleGroup(m))continue;if(f===Ri&&null!=(h=e.audioGroups)&&h.some((t=>s.hasAudioGroup(t)))||f===Pi&&null!=(o=e.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||v&&e.audioCodec===s.audioCodec||!v&&e.audioCodec!==s.audioCodec||p&&e.codecSet===s.codecSet)continue}a=n;break}}if(a>-1&&s.loadLevel!==a)return t.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:a}}return{action:2,flags:1}}onErrorOut(t,i){var s;switch(null==(s=i.errorAction)?void 0:s.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(i),i.errorAction.resolved||i.details===L.FRAG_GAP?/MediaSource readyState: ended/.test(i.error.message)&&(this.warn(`MediaSource ended after "${i.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):i.fatal=!0}i.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const i=this.hls,s=t.errorAction;if(!s)return;const{flags:e,hdcpLevel:n,nextAutoLevel:r}=s;switch(e){case 0:this.switchLevel(t,r);break;case 2:n&&(i.maxHdcpLevel=Ji[Ji.indexOf(n)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${i.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,r)}switchLevel(t,i){void 0!==i&&t.errorAction&&(this.warn(`switching to level ${i} after ${t.details}`),this.hls.nextAutoLevel=i,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(A.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,i){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=i.media instanceof self.HTMLVideoElement?i.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,i,s){const e=performance.now();if(i){if(this.lastTime){const t=s-this.lastDroppedFrames,n=i-this.lastDecodedFrames,r=1e3*t/(e-this.lastTime),h=this.hls;if(h.trigger(A.FPS_DROP,{currentDropped:t,currentDecoded:n,totalDroppedFrames:s}),r>0&&t>h.config.fpsDroppedMonitoringThreshold*n){let t=h.currentLevel;I.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=t)&&(t-=1,h.trigger(A.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:h.currentLevel}),h.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=e,this.lastDroppedFrames=s,this.lastDecodedFrames=i}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const i=t.getVideoPlaybackQuality();this.checkFPS(t,i.totalVideoFrames,i.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:nt,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:dh,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 fe{constructor(t,i,s){super(t,i,s,"[subtitle-stream-controller]",Pi),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(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.ERROR,this.onError,this),t.on(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(A.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(A.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.ERROR,this.onError,this),t.off(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(A.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(A.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=se,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,i){this.mainDetails=i.details}onSubtitleFragProcessed(t,i){const{frag:s,success:e}=i;if(this.fragPrevious=s,this.state=se,!e)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let r;const h=s.start;for(let t=0;t<n.length;t++)if(h>=n[t].start&&h<=n[t].end){r=n[t];break}const o=s.start+s.duration;r?r.end=o:(r={start:h,end:o},n.push(r)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(t,i){const{startOffset:s,endOffset:e}=i;if(0===s&&e!==Number.POSITIVE_INFINITY){const t=e-1;if(t<=0)return;i.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((i=>{for(let s=0;s<i.length;)if(i[s].end<=t)i.shift();else{if(!(i[s].start<t))break;i[s].start=t,s++}})),this.fragmentTracker.removeFragmentsInRange(s,t,Pi)}}onFragBuffered(t,i){var s;this.loadedmetadata||i.frag.type!==Ii||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,i){const s=i.frag;(null==s?void 0:s.type)===Pi&&(i.details===L.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ie&&(this.state=se))}onSubtitleTracksUpdated(t,{subtitleTracks:i}){this.levels&&kn(this.levels,i)?this.levels=i.map((t=>new is(t))):(this.tracksBuffered=[],this.levels=i.map((t=>{const i=new is(t);return this.tracksBuffered[i.id]=[],i})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Pi),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,i){var s;if(this.currentTrackId=i.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const e=this.levels[this.currentTrackId];this.mediaBuffer=null!=e&&e.details?this.mediaBufferTimeRanges:null,e&&this.setInterval(500)}onSubtitleTrackLoaded(t,i){var s;const{currentTrackId:e,levels:n}=this,{details:r,id:h}=i;if(!n)return void this.warn(`Subtitle tracks were reset while loading level ${h}`);const o=n[h];if(h>=n.length||!o)return;this.log(`Subtitle track ${h} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let a=0;if(r.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;const i=t.fragments[0];var l;o.details?(a=this.alignPlaylists(r,o.details,null==(l=this.levelLastLoaded)?void 0:l.details),0===a&&i&&(a=i.start,hs(r,a))):r.hasProgramDateTime&&t.hasProgramDateTime?(Vs(r,t),a=r.fragments[0].start):i&&(a=i.start,hs(r,a))}o.details=r,this.levelLastLoaded=o,h===e&&(this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(this.mainDetails||r,a),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===se)&&(gs(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0))}_handleFragmentLoadComplete(t){const{frag:i,payload:s}=t,e=i.decryptdata,n=this.hls;if(!this.fragContextChanged(i)&&s&&s.byteLength>0&&null!=e&&e.key&&e.iv&&"AES-128"===e.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),e.key.buffer,e.iv.buffer).catch((t=>{throw n.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((s=>{const e=performance.now();n.trigger(A.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:t,tdecrypt:e}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=se}))}}doTick(){if(this.media){if(this.state===se){const{currentTrackId:t,levels:i}=this,s=null==i?void 0:i[t];if(!s||!i.length||!s.details)return;const{config:e}=this,n=this.getLoadPosition(),r=js.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,e.maxBufferHole),{end:h,len:o}=r,a=this.getFwdBufferInfo(this.media,Ii),l=s.details;if(o>this.getMaxBufferLength(null==a?void 0:a.len)+l.levelTargetDuration)return;const c=l.fragments,u=c.length,d=l.edge;let f=null;const v=this.fragPrevious;if(h<d){const t=e.maxFragLookUpTolerance,i=h>d-t?0:t;f=gs(v,c,Math.max(c[0].start,h),i),!f&&v&&v.start<c[0].start&&(f=c[0])}else f=c[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const t=c[f.sn-l.startSN-1];t&&t.cc===f.cc&&this.fragmentTracker.getState(t)===Is&&(f=t)}this.fragmentTracker.getState(f)===Is&&this.loadFragment(f,s,h)}}else this.state=se}getMaxBufferLength(t){const i=super.getMaxBufferLength();return t?Math.max(i,t):i}loadFragment(t,i,s){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,i):(this.startFragRequested=!0,super.loadFragment(t,i,s))}get mediaBufferTimeRanges(){return new $n(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends ws{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.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 i=Gi(this.media.textTracks);for(let s=0;s<i.length;s++)if("hidden"===i[s].mode)t=i[s];else if("showing"===i[s].mode){t=i[s];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVEL_LOADING,this.onLevelLoading,this),t.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(A.ERROR,this.onError,this)}onMediaAttached(t,i){this.media=i.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(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Gi(this.media.textTracks).forEach((t=>{ji(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,i){this.tracks=i.subtitleTracks}onSubtitleTrackLoaded(t,i){const{id:s,groupId:e,details:n}=i,r=this.tracksInGroup[s];if(!r||r.groupId!==e)return void this.warn(`Subtitle track with id:${s} and group:${e} not found in active group ${null==r?void 0:r.groupId}`);const h=r.details;r.details=i.details,this.log(`Subtitle track ${s} "${r.name}" lang:${r.lang} group:${e} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,i,h)}onLevelLoading(t,i){this.switchLevel(i.level)}onLevelSwitching(t,i){this.switchLevel(i.level)}switchLevel(t){const i=this.hls.levels[t];if(!i)return;const s=i.subtitleGroups||null,e=this.groupIds;let n=this.currentTrack;if(!s||(null==e?void 0:e.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==e?void 0:e.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,i)=>{t.id=i}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const i=this.hls.config.subtitlePreference;if(!n&&i){this.selectDefaultTrack=!1;const s=Ms(i,t);if(s>-1)n=t[s];else{const t=Ms(i,this.tracks);n=this.tracks[t]}}let e=this.findTrackId(n);-1===e&&n&&(e=this.findTrackId(null));const r={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(A.SUBTITLE_TRACKS_UPDATED,r),-1!==e&&-1===this.trackId&&this.setSubtitleTrack(e)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const i=this.tracksInGroup,s=this.selectDefaultTrack;for(let e=0;e<i.length;e++){const n=i[e];if((!s||n.default)&&(s||t)&&(!t||Ls(n,t)))return e}if(t){for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE"]))return s}return-1}findTrackForTextTrack(t){if(t){const i=this.tracksInGroup;for(let s=0;s<i.length;s++)if(Tn(i[s],t))return s}return-1}onError(t,i){!i.fatal&&i.context&&(i.context.type!==Ci||i.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(i.context.groupId)||this.checkRetry(i))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const i=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&Ls(t,s))return s;const e=Ms(t,this.tracksInGroup);if(e>-1){const t=this.tracksInGroup[e];return this.setSubtitleTrack(e),t}if(s)return null;{const s=Ms(t,i);if(s>-1)return i[s]}}}return null}loadPlaylist(t){super.loadPlaylist();const i=this.currentTrack;if(this.shouldLoadPlaylist(i)&&i){const s=i.id,e=i.groupId;let n=i.url;if(t)try{n=t.addDirectives(n)}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(A.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const i=Gi(t.textTracks),s=this.currentTrack;let e;if(s&&(e=i.filter((t=>Tn(s,t)))[0],e||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(i).forEach((t=>{"disabled"!==t.mode&&t!==e&&(t.mode="disabled")})),e){const t=this.subtitleDisplay?"showing":"hidden";e.mode!==t&&(e.mode=t)}}setSubtitleTrack(t){const i=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=i.length||!T(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,e=i[t]||null;if(this.trackId=t,this.currentTrack=e,this.toggleTrackModes(),!e)return void this.hls.trigger(A.SUBTITLE_TRACK_SWITCH,{id:t});if(t===this.trackId&&e===s&&e.details&&!e.details.live)return;this.log(`Switching to subtitle-track ${t}`+(e?` "${e.name}" lang:${e.lang} group:${e.groupId}`:""));const{id:n,groupId:r="",name:h,type:o,url:a}=e;this.hls.trigger(A.SUBTITLE_TRACK_SWITCH,{id:n,groupId:r,name:h,type:o,url:a});const l=this.switchParams(e.url,null==s?void 0:s.details,e.details);this.loadPlaylist(l)}},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(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(A.FRAG_LOADING,this.onFragLoading,this),t.on(A.FRAG_LOADED,this.onFragLoaded,this),t.on(A.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(A.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(A.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(A.FRAG_LOADING,this.onFragLoading,this),t.off(A.FRAG_LOADED,this.onFragLoaded,this),t.off(A.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(A.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(A.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(A.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 Wn(this,"textTrack1"),i=new Wn(this,"textTrack2"),s=new Wn(this,"textTrack3"),e=new Wn(this,"textTrack4");this.cea608Parser1=new Kn(1,t,i),this.cea608Parser2=new Kn(3,s,e)}}addCues(t,i,s,e,n){let r=!1;for(let t=n.length;t--;){const e=n[t],a=(h=e[0],o=i,Math.min(e[1],s)-Math.max(h,o));if(a>=0&&(e[0]=Math.min(e[0],i),e[1]=Math.max(e[1],s),r=!0,a/(s-i)>.5))return}var h,o;if(r||n.push([i,s]),this.config.renderTextTracksNatively)this.Cues.newCue(this.captionsTracks[t],i,s,e);else{const n=this.Cues.newCue(null,i,s,e);this.hls.trigger(A.CUES_PARSED,{type:"captions",cues:n,track:t})}}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){const{unparsedVttFrags:r}=this;"main"===s&&(this.initPTS[i.cc]={baseTime:e,timescale:n}),r.length&&(this.unparsedVttFrags=[],r.forEach((t=>{this.onFragLoaded(A.FRAG_LOADED,t)})))}getExistingTrack(t,i){const{media:s}=this;if(s)for(let e=0;e<s.textTracks.length;e++){const n=s.textTracks[e];if(br(n,{name:t,lang:i,attrs:{}}))return n}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:i,captionsTracks:s,media:e}=this,{label:n,languageCode:r}=i[t],h=this.getExistingTrack(n,r);if(h)s[t]=h,ji(s[t]),Fi(s[t],e);else{const i=this.createTextTrack("captions",n,r);i&&(i[t]=!0,s[t]=i)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const i=this.captionsProperties[t];if(!i)return;const s={_id:t,label:i.label,kind:"captions",default:!!i.media&&!!i.media.default,closedCaptions:i.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(A.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,i,s){const e=this.media;if(e)return e.addTextTrack(t,i,s)}onMediaAttaching(t,i){this.media=i.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach((i=>{ji(t[i]),delete t[i]})),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 i=t.textTracks;if(i)for(let t=0;t<i.length;t++)ji(i[t])}onSubtitleTracksUpdated(t,i){const s=i.subtitleTracks||[],e=s.some((t=>t.textCodec===ar));if(this.config.enableWebVTT||e&&this.config.enableIMSC1){if(kn(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,i=t?Gi(t.textTracks):null;if(this.tracks.forEach((t=>{let s;if(i){let e=null;for(let s=0;s<i.length;s++)if(i[s]&&br(i[s],t)){e=i[s],i[s]=null;break}e&&(s=e)}if(s)ji(s);else{const i=wr(t);s=this.createTextTrack(i,t.name,t.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)})),null!=i&&i.length){const t=i.filter((t=>null!==t)).map((t=>t.label));t.length&&I.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(A.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,i){this.config.enableCEA708Captions&&i.captions&&i.captions.forEach((t=>{const i=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!i)return;const s=this.captionsProperties[`textTrack${i[1]}`];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)}))}closedCaptionsForLevel(t){const i=this.hls.levels[t.level];return null==i?void 0:i.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,i){if(this.enabled&&i.frag.type===Ii){var s,e;const{cea608Parser1:t,cea608Parser2:n,lastSn:r}=this,{cc:h,sn:o}=i.frag,a=null!=(s=null==(e=i.part)?void 0:e.index)?s:-1;t&&n&&(o!==r+1||o===r&&a!==this.lastPartIndex+1||h!==this.lastCc)&&(t.reset(),n.reset()),this.lastCc=h,this.lastSn=o,this.lastPartIndex=a}}onFragLoaded(t,i){const{frag:s,payload:e}=i;if(s.type===Pi)if(e.byteLength){const t=s.decryptdata;if(null==t||!t.encrypted||"stats"in i){const t=this.tracks[s.level],n=this.vttCCs;n[s.cc]||(n[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===ar?this._parseIMSC1(s,e):this._parseVTTs(i)}}else this.hls.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,i){const s=this.hls;dr(i,this.initPTS[t.cc],(i=>{this._appendCues(i,t.level),s.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(i=>{I.log(`Failed to parse IMSC1: ${i}`),s.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:i})}))}_parseVTTs(t){var i;const{frag:s,payload:e}=t,{initPTS:n,unparsedVttFrags:r}=this,h=n.length-1;if(!n[s.cc]&&-1===h)return void r.push(t);const o=this.hls;!function(t,i,s,e,n,r,h){const o=new er,a=St(new Uint8Array(t)).trim().replace(nr,"\n").split("\n"),l=[],c=i?function(t,i=1){return tn(t,9e4,1/i)}(i.baseTime,i.timescale):0;let u,d="00:00.000",f=0,v=0,p=!0;o.oncue=function(t){const r=s[e];let h=s.ccOffset;const o=(f-c)/9e4;if(null!=r&&r.new&&(void 0!==v?h=s.ccOffset=r.start:function(t,i,s){let e=t[i],n=t[e.prevCC];if(!n||!n.new&&e.new)return t.ccOffset=t.presentationOffset=e.start,void(e.new=!1);for(;null!=(r=n)&&r.new;){var r;t.ccOffset+=e.start-n.start,e.new=!1,e=n,n=t[e.prevCC]}t.presentationOffset=s}(s,e,o)),o){if(!i)return void(u=new Error("Missing initPTS for VTT MPEGTS"));h=o-s.presentationOffset}const a=t.endTime-t.startTime,d=on(9e4*(t.startTime+h-v),9e4*n)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+a,0);const p=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(p)),t.id||(t.id=or(t.startTime,t.endTime,p)),t.endTime>0&&l.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?h(u):r(l)},a.forEach((t=>{if(p){if(rr(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{rr(t,"LOCAL:")?d=t.slice(6):rr(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{v=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),e=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(T(i)&&T(s)&&T(e)&&T(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*e,i+=36e5*n,i}(d)/1e3}catch(t){u=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}(null!=(i=s.initSegment)&&i.data?Kt(s.initSegment.data,new Uint8Array(e)):e,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(i=>{const n="Missing initPTS for VTT MPEGTS"===i.message;n?r.push(t):this._fallbackToIMSC1(s,e),I.log(`Failed to parse VTT cue: ${i}`),n&&h>s.cc||o.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:i})}))}_fallbackToIMSC1(t,i){const s=this.tracks[t.level];s.textCodec||dr(i,this.initPTS[t.cc],(()=>{s.textCodec=ar,this._parseIMSC1(t,i)}),(()=>{s.textCodec="wvtt"}))}_appendCues(t,i){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[i];if(!s||"disabled"===s.mode)return;t.forEach((t=>Bi(s,t)))}else{const e=this.tracks[i];if(!e)return;s.trigger(A.CUES_PARSED,{type:"subtitles",cues:t,track:e.default?"default":"subtitles"+i})}}onFragDecrypted(t,i){const{frag:s}=i;s.type===Pi&&this.onFragLoaded(A.FRAG_LOADED,i)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,i){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:e}=this;if(!this.enabled||!s||!e)return;const{frag:n,samples:r}=i;if(n.type!==Ii||"NONE"!==this.closedCaptionsForLevel(n))for(let t=0;t<r.length;t++){const i=r[t].bytes;if(i){const n=this.extractCea608Data(i);s.addData(r[t].pts,n[0]),e.addData(r[t].pts,n[1])}}}onBufferFlushing(t,{startOffset:i,endOffset:s,endOffsetSubtitles:e,type:n}){const{media:r}=this;if(r&&!(r.currentTime<s)){if(!n||"video"===n){const{captionsTracks:t}=this;Object.keys(t).forEach((e=>_i(t[e],i,s)))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==e){const{textTracks:t}=this;Object.keys(t).forEach((s=>_i(t[s],i,e)))}}}extractCea608Data(t){const i=[[],[]],s=31&t[0];let e=2;for(let n=0;n<s;n++){const s=t[e++],n=127&t[e++],r=127&t[e++];if((0!==n||0!==r)&&4&s){const t=3&s;0!==t&&1!==t||(i[t].push(n),i[t].push(r))}}return i}},audioStreamController:class extends fe{constructor(t,i,s){super(t,i,s,"[audio-stream-controller]",Ri),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(A.ERROR,this.onError,this),t.on(A.BUFFER_RESET,this.onBufferReset,this),t.on(A.BUFFER_CREATED,this.onBufferCreated,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(A.ERROR,this.onError,this),t.off(A.BUFFER_RESET,this.onBufferReset,this),t.off(A.BUFFER_CREATED,this.onBufferCreated,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){if("main"===s){const t=i.cc;this.initPTS[i.cc]={baseTime:e,timescale:n},this.log(`InitPTS for cc: ${t} found from main: ${e}`),this.videoTrackCC=t,this.state===ue&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=ie);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=se):(this.loadedmetadata=!1,this.state=he),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case se:this.doTickIdle();break;case he:{var t;const{levels:i,trackId:s}=this,e=null==i||null==(t=i[s])?void 0:t.details;if(e){if(this.waitForCdnTuneIn(e))break;this.state=ue}break}case re:{var i;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(i=this.media)&&i.seeking){const{levels:t,trackId:i}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[i])||null),this.state=se}break}case ue:{const t=this.waitingData;if(t){const{frag:i,part:s,cache:e,complete:n}=t;if(void 0!==this.initPTS[i.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=ne;const t={frag:i,part:s,payload:e.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),n&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=js.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);ms(s.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=se}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=se)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:i,media:s,trackId:e}=this;if(!this.buffering||!s&&(this.startFragRequested||!t.config.startFragPrefetch)||null==i||!i[e])return;const n=i[e],r=n.details;if(!r||r.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(r))return void(this.state=he);const h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,B,Ri));const o=this.getFwdBufferInfo(h,Ri);if(null===o)return;if(!this.switchingTrack&&this._streamEnded(o,r))return t.trigger(A.BUFFER_EOS,{type:"audio"}),void(this.state=le);const a=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Ii),l=o.len,c=this.getMaxBufferLength(null==a?void 0:a.len),u=r.fragments,d=u[0].start,f=this.getLoadPosition(),v=this.flushing?f:o.end;if(this.switchingTrack&&s&&r.PTSKnown&&f<d&&(o.end>d||o.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=d+.05),l>=c&&!this.switchingTrack&&v<u[u.length-1].start)return;let p=this.getNextFragment(v,r),g=!1;if(p&&this.isLoopLoading(p,v)&&(g=!!p.gap,p=this.getNextFragmentLoopLoading(p,r,o,Ii,c)),!p)return void(this.bufferFlushed=!0);const m=a&&p.start>a.end+r.targetduration;if(m||(null==a||!a.len)&&o.len){const t=this.getAppendedFrag(p.start,Ii);if(null===t)return;if(g||(g=!!t.gap||!!m&&0===a.len),m&&!g||g&&o.nextStart&&o.nextStart<t.end)return}this.loadFragment(p,n,v)}getMaxBufferLength(t){const i=super.getMaxBufferLength();return t?Math.min(Math.max(i,t),this.config.maxMaxBufferLength):i}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:i}){this.resetTransmuxer(),this.levels=i.map((t=>new is(t)))}onAudioTrackSwitching(t,i){const s=!!i.url;this.trackId=i.id;const{fragCurrent:e}=this;e&&(e.abortRequests(),this.removeUnbufferedFrags(e.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=i,this.state=se,this.flushAudioIfNeeded(i)):(this.switchingTrack=null,this.bufferedTrack=i,this.state=ie),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,i){this.mainDetails=i.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(A.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,i){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=i);const{levels:e}=this,{details:n,id:r}=i;if(!e)return void this.warn(`Audio tracks were reset while loading level ${r}`);this.log(`Audio track ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const h=e[r];let o=0;if(n.live||null!=(s=h.details)&&s.live){this.checkLiveUpdate(n);const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;var a;!h.details&&n.hasProgramDateTime&&t.hasProgramDateTime?(Vs(n,t),o=n.fragments[0].start):o=this.alignPlaylists(n,h.details,null==(a=this.levelLastLoaded)?void 0:a.details)}h.details=n,this.levelLastLoaded=h,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,o),this.state!==he||this.waitForCdnTuneIn(n)||(this.state=se),this.tick()}_handleFragmentLoadProgress(t){var i;const{frag:s,part:e,payload:n}=t,{config:r,trackId:h,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 a=o[h];if(!a)return void this.warn("Audio track is undefined on fragment load progress");const l=a.details;if(!l)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const c=r.defaultAudioCodec||a.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new bn(this.hls,Ri,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[s.cc],f=null==(i=s.initSegment)?void 0:i.data;if(void 0!==d){const t=!1,i=e?e.index:-1,r=new _s(s.level,s.sn,s.stats.chunkCount,n.byteLength,i,-1!==i);u.push(n,f,c,"",s,e,l.totalduration,t,r,d)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${l.startSN} ,${l.endSN}],track ${h}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:e,cache:new ve,complete:!1};t.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=ue}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,i){const s=i.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),i.tracks.video&&(this.videoBuffer=i.tracks.video.buffer||null)}onFragBuffered(t,i){const{frag:s,part:e}=i;if(s.type===Ri)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${e?" p: "+e.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(A.AUDIO_TRACK_SWITCHED,k({},t)))}this.fragBufferedComplete(s,e)}else if(!this.loadedmetadata&&s.type===Ii){const t=this.videoBuffer||this.media;t&&js.getBuffered(t).length&&(this.loadedmetadata=!0)}}onError(t,i){var s;if(i.fatal)this.state=ce;else switch(i.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ri,i);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==he||(null==(s=i.context)?void 0:s.type)!==Di||(this.state=se);break;case L.BUFFER_APPEND_ERROR:case L.BUFFER_FULL_ERROR:if(!i.parent||"audio"!==i.parent)return;if(i.details===L.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}onBufferFlushing(t,{type:i}){i!==j&&(this.flushing=!0)}onBufferFlushed(t,{type:i}){if(i!==j){this.flushing=!1,this.bufferFlushed=!0,this.state===le&&(this.state=se);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,i,Ri),this.tick())}}_handleTransmuxComplete(t){var i;const s="audio",{hls:e}=this,{remuxResult:n,chunkMeta:r}=t,h=this.getCurrentContext(r);if(!h)return void this.resetWhenMissingContext(r);const{frag:o,part:a,level:l}=h,{details:c}=l,{audio:u,text:d,id3:f,initSegment:v}=n;if(!this.fragContextChanged(o)&&c){if(this.state=oe,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,v.tracks,t,r),e.trigger(A.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:v.tracks})}if(u){const{startPTS:t,endPTS:i,startDTS:s,endDTS:e}=u;a&&(a.elementaryStreams[B]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(B,t,i,s,e),this.bufferFragmentData(u,o,a,r)}if(null!=f&&null!=(i=f.samples)&&i.length){const t=S({id:s,frag:o,details:c},f);e.trigger(A.FRAG_PARSING_METADATA,t)}if(d){const t=S({id:s,frag:o,details:c},d);e.trigger(A.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,i,s,e){if(this.state!==oe)return;i.video&&delete i.video;const n=i.audio;if(!n)return;n.id="audio";const r=t.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${r}/${n.codec}]`),r&&1===r.split(",").length&&(n.levelCodec=r),this.hls.trigger(A.BUFFER_CODECS,i);const h=n.initSegment;null!=h&&h.byteLength&&this.hls.trigger(A.BUFFER_APPENDING,{type:"audio",frag:s,part:null,chunkMeta:e,parent:s.type,data:h}),this.tickImmediate()}loadFragment(t,i,s){const e=this.fragmentTracker.getState(t);var n;if(this.fragCurrent=t,this.switchingTrack||e===Is||e===Ps)if("initSegment"===t.sn)this._loadInitSegment(t,i);else if(null!=(n=i.details)&&n.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=ue;const s=this.mainDetails;s&&s.fragments[0].start!==i.details.fragments[0].start&&Vs(i.details,s)}else this.startFragRequested=!0,super.loadFragment(t,i,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:i,lang:s,assocLang:e,characteristics:n,audioCodec:r,channels:h}=this.bufferedTrack;Ls({name:i,lang:s,assocLang:e,characteristics:n,audioCodec:r,channels:h},t,xs)||(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}}completeAudioSwitch(t){const{hls:i}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,i.trigger(A.AUDIO_TRACK_SWITCHED,k({},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(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVEL_LOADING,this.onLevelLoading,this),t.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(A.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,i){this.tracks=i.audioTracks||[]}onAudioTrackLoaded(t,i){const{id:s,groupId:e,details:n}=i,r=this.tracksInGroup[s];if(!r||r.groupId!==e)return void this.warn(`Audio track with id:${s} and group:${e} not found in active group ${null==r?void 0:r.groupId}`);const h=r.details;r.details=i.details,this.log(`Audio track ${s} "${r.name}" lang:${r.lang} group:${e} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,i,h)}onLevelLoading(t,i){this.switchLevel(i.level)}onLevelSwitching(t,i){this.switchLevel(i.level)}switchLevel(t){const i=this.hls.levels[t];if(!i)return;const s=i.audioGroups||null,e=this.groupIds;let n=this.currentTrack;if(!s||(null==e?void 0:e.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==e?void 0:e.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,i)=>{t.id=i}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const i=this.hls.config.audioPreference;if(!n&&i){const s=Ms(i,t,xs);if(s>-1)n=t[s];else{const t=Ms(i,this.tracks);n=this.tracks[t]}}let e=this.findTrackId(n);-1===e&&n&&(e=this.findTrackId(null));const h={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(A.AUDIO_TRACKS_UPDATED,h);const o=this.trackId;if(-1!==e&&-1===o)this.setAudioTrack(e);else if(t.length&&-1===o){var r;const i=new Error(`No audio track selected for current audio group-ID(s): ${null==(r=this.groupIds)?void 0:r.join(",")} track count: ${t.length}`);this.warn(i.message),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}onError(t,i){!i.fatal&&i.context&&(i.context.type!==Di||i.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(i.context.groupId)||(this.requestScheduled=-1,this.checkRetry(i)))}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 i=this.hls;if(i.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const e=this.currentTrack;if(e&&Ls(t,e,xs))return e;const n=Ms(t,this.tracksInGroup,xs);if(n>-1){const t=this.tracksInGroup[n];return this.setAudioTrack(n),t}if(e){let e=i.loadLevel;-1===e&&(e=i.firstAutoLevel);const n=function(t,i,s,e,n){const r=i[e],h=i.reduce(((t,i,s)=>{const e=i.uri;return(t[e]||(t[e]=[])).push(s),t}),{})[r.uri];h.length>1&&(e=Math.max.apply(Math,h));const o=r.videoRange,a=r.frameRate,l=r.codecSet.substring(0,4),c=Ds(i,e,(i=>{if(i.videoRange!==o||i.frameRate!==a||i.codecSet.substring(0,4)!==l)return!1;const e=i.audioGroups,r=s.filter((t=>!e||-1!==e.indexOf(t.groupId)));return Ms(t,r,n)>-1}));return c>-1?c:Ds(i,e,(i=>{const e=i.audioGroups,r=s.filter((t=>!e||-1!==e.indexOf(t.groupId)));return Ms(t,r,n)>-1}))}(t,i.levels,s,e,xs);if(-1===n)return null;i.nextLoadLevel=n}if(t.channels||t.audioCodec){const i=Ms(t,s);if(i>-1)return s[i]}}}return null}setAudioTrack(t){const i=this.tracksInGroup;if(t<0||t>=i.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,e=i[t],n=e.details&&!e.details.live;if(t===this.trackId&&e===s&&n)return;if(this.log(`Switching to audio-track ${t} "${e.name}" lang:${e.lang} group:${e.groupId} channels:${e.channels}`),this.trackId=t,this.currentTrack=e,this.hls.trigger(A.AUDIO_TRACK_SWITCHING,k({},e)),n)return;const r=this.switchParams(e.url,null==s?void 0:s.details,e.details);this.loadPlaylist(r)}findTrackId(t){const i=this.tracksInGroup;for(let s=0;s<i.length;s++){const e=i[s];if((!this.selectDefaultTrack||e.default)&&(!t||Ls(t,e,xs)))return s}if(t){const{name:s,lang:e,assocLang:n,characteristics:r,audioCodec:h,channels:o}=t;for(let t=0;t<i.length;t++)if(Ls({name:s,lang:e,assocLang:n,characteristics:r,audioCodec:h,channels:o},i[t],xs))return t;for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE"]))return s}return-1}loadPlaylist(t){const i=this.currentTrack;if(this.shouldLoadPlaylist(i)&&i){super.loadPlaylist();const s=i.id,e=i.groupId;let n=i.url;if(t)try{n=t.addDirectives(n)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`loading audio-track playlist ${s} "${i.name}" lang:${i.lang} group:${e}`),this.clearTimer(),this.hls.trigger(A.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:t||null})}}},emeController:Tr,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{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:Er.MANIFEST,su:!this.initialized})}catch(t){I.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const i=t.frag,s=this.hls.levels[i.level],e=this.getObjectType(i),n={d:1e3*i.duration,ot:e};e!==Er.VIDEO&&e!==Er.AUDIO&&e!=Er.MUXED||(n.br=s.bitrate/1e3,n.tb=this.getTopBandwidth(e)/1e3,n.bl=this.getBufferLength(e)),this.apply(t,n)}catch(t){I.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const i=this.config=t.config,{cmcd:s}=i;null!=s&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),i=t.toString();return URL.revokeObjectURL(t),i.slice(i.lastIndexOf("/")+1)}catch(t){let i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const s=(i+16*Math.random())%16|0;return i=Math.floor(i/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(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHED,this.onMediaDetached,this),t.on(A.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHED,this.onMediaDetached,this),t.off(A.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,i){this.media=i.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,i){var s,e;this.audioBuffer=null==(s=i.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(e=i.tracks.video)?void 0:e.buffer}createData(){var t;return{v:1,sf:Ar.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,i={}){S(i,this.createData()),this.starved&&(i.ot===Er.INIT||i.ot===Er.VIDEO||i.ot===Er.MUXED)&&(i.bs=!0,i.su=!0,this.starved=!1),null==i.su&&(i.su=this.buffering);const{includeKeys:s}=this;var e;s&&(i=Object.keys(i).reduce(((t,e)=>(s.includes(e)&&(t[e]=i[e]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),S(t.headers,function(t,i={}){if(!t)return{};const s=Object.entries(t),e=Object.entries(Lr).concat(Object.entries((null==i?void 0:i.customHeaderMap)||{})),n=s.reduce(((t,i)=>{var s;const[n,r]=i,h=(null==(s=e.find((t=>t[1].includes(n))))?void 0:s[0])||Mr.REQUEST;return null!=t[h]||(t[h]={}),t[h][n]=r,t}),{});return Object.entries(n).reduce(((t,[s,e])=>(t[s]=ih(e,i),t)),{})}(i,e))):t.url=function(t,i,s){const e=function(t,i={}){if(!t)return"";const s=ih(t,i);return`CMCD=${encodeURIComponent(s)}`}(i,s);if(!e)return t;if(sh.test(t))return t.replace(sh,e);const n=t.includes("?")?"&":"?";return`${t}${n}${e}`}(t.url,i)}getObjectType(t){const{type:i}=t;return"subtitle"===i?Er.TIMED_TEXT:"initSegment"===t.sn?Er.INIT:"audio"===i?Er.AUDIO:"main"===i?this.hls.audioTracks.length?Er.VIDEO:Er.MUXED:void 0}getTopBandwidth(t){let i,s=0;const e=this.hls;if(t===Er.AUDIO)i=e.audioTracks;else{const t=e.maxAutoLevel;i=e.levels.slice(0,t>-1?t+1:e.levels.length)}for(const t of i)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const i=this.hls.media,s=t===Er.AUDIO?this.audioBuffer:this.videoBuffer;return s&&i?1e3*js.bufferInfo(s,i.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){const{pLoader:t}=this.config,i=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,e){i(t),this.loader.load(t,s,e)}}}createFragmentLoader(){const{fLoader:t}=this.config,i=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,e){i(t),this.loader.load(t,s,e)}}}},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=I.log.bind(I,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.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 i=this.levels;i&&(this.levels=i.filter((i=>i!==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,i){const{contentSteering:s}=i;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,i){this.audioTracks=i.audioTracks,this.subtitleTracks=i.subtitleTracks}onError(t,i){const{errorAction:s}=i;if(2===(null==s?void 0:s.action)&&1===s.flags){const t=this.levels;let e=this.pathwayPriority,n=this.pathwayId;if(i.context){const{groupId:s,pathwayId:e,type:r}=i.context;s&&t?n=this.getPathwayForGroupId(s,r,n):e&&(n=e)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!e&&t&&(e=t.reduce(((t,i)=>(-1===t.indexOf(i.pathwayId)&&t.push(i.pathwayId),t)),[])),e&&e.length>1&&(this.updatePathwayPriority(e),s.resolved=this.pathwayId!==n),s.resolved||I.warn(`Could not resolve ${i.details} ("${i.error.message}") with content-steering for Pathway: ${n} levels: ${t?t.length:t} priorities: ${JSON.stringify(e)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let i=this.getLevelsForPathway(this.pathwayId);if(0===i.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),i=this.getLevelsForPathway(s),this.pathwayId=s}return i.length!==t.length&&this.log(`Found ${i.length}/${t.length} levels in Pathway "${this.pathwayId}"`),i}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((i=>t===i.pathwayId))}updatePathwayPriority(t){let i;this.pathwayPriority=t;const s=this.penalizedPathways,e=performance.now();Object.keys(s).forEach((t=>{e-s[t]>3e5&&delete s[t]}));for(let e=0;e<t.length;e++){const n=t[e];if(n in s)continue;if(n===this.pathwayId)return;const r=this.hls.nextLoadLevel,h=this.hls.levels[r];if(i=this.getLevelsForPathway(n),i.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,ls(i),this.hls.trigger(A.LEVELS_UPDATED,{levels:i});const t=this.hls.levels[r];h&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==h.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==h.bitrate&&this.log(`Unstable Pathways change from bitrate ${h.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=r);break}}}getPathwayForGroupId(t,i,s){const e=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<e.length;s++)if(i===Di&&e[s].hasAudioGroup(t)||i===Ci&&e[s].hasSubtitleGroup(t))return e[s].pathwayId;return s}clonePathways(t){const i=this.levels;if(!i)return;const s={},e={};t.forEach((t=>{const{ID:n,"BASE-ID":r,"URI-REPLACEMENT":h}=t;if(i.some((t=>t.pathwayId===n)))return;const o=this.getLevelsForPathway(r).map((t=>{const i=new O(t.attrs);i["PATHWAY-ID"]=n;const r=i.AUDIO&&`${i.AUDIO}_clone_${n}`,o=i.SUBTITLES&&`${i.SUBTITLES}_clone_${n}`;r&&(s[i.AUDIO]=r,i.AUDIO=r),o&&(e[i.SUBTITLES]=o,i.SUBTITLES=o);const a=nh(t.uri,i["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",h),l=new is({attrs:i,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:a,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let i=1;i<t.audioGroups.length;i++)l.addGroupId("audio",`${t.audioGroups[i]}_clone_${n}`);if(t.subtitleGroups)for(let i=1;i<t.subtitleGroups.length;i++)l.addGroupId("text",`${t.subtitleGroups[i]}_clone_${n}`);return l}));i.push(...o),eh(this.audioTracks,s,h,n),eh(this.subtitleTracks,e,h,n)}))}loadSteeringManifest(t){const i=this.hls.config,s=i.loader;let e;this.loader&&this.loader.destroy(),this.loader=new s(i);try{e=new self.URL(t)}catch(i){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==e.protocol){const t=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);e.searchParams.set("_HLS_pathway",this.pathwayId),e.searchParams.set("_HLS_throughput",""+t)}const n={responseType:"json",url:e.href},r=i.steeringManifestLoadPolicy.default,h=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},a={onSuccess:(t,i,s)=>{this.log(`Loaded steering manifest: "${e}"`);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":r,"PATHWAY-CLONES":h,"PATHWAY-PRIORITY":o}=n;if(r)try{this.uri=new self.URL(r,e).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${r}`)}this.scheduleRefresh(this.uri||s.url),h&&this.clonePathways(h);const a={steeringManifest:n,url:e.toString()};this.hls.trigger(A.STEERING_MANIFEST_LOADED,a),o&&this.updatePathwayPriority(o)},onError:(t,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${i.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${i.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||i.url,s);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const i=t.getResponseHeader("Retry-After");i&&(s=1e3*parseFloat(i))}this.log(`Steering manifest ${i.url} rate limited`)}},onTimeout:(t,i)=>{this.log(`Timeout loading steering manifest (${i.url})`),this.scheduleRefresh(this.uri||i.url)}};this.log(`Requesting steering manifest: ${e}`),this.loader.load(n,o,a)}scheduleRefresh(t,i=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var i;const s=null==(i=this.hls)?void 0:i.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),i)}}});function vh(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(vh):Object.keys(t).reduce(((i,s)=>(i[s]=vh(t[s]),i)),{}):t}let ph;class gh extends ws{constructor(t,i){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=i,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this),t.on(A.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this),t.off(A.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,i){this.resetLevels()}onManifestLoaded(t,i){const s=this.hls.config.preferManagedMediaSource,e=[],n={},r={};let h=!1,o=!1,a=!1;i.levels.forEach((t=>{var i,l;const c=t.attrs;let{audioCodec:u,videoCodec:d}=t;-1!==(null==(i=u)?void 0:i.indexOf("mp4a.40.34"))&&(ph||(ph=/chrome|firefox/i.test(navigator.userAgent)),ph&&(t.audioCodec=u=void 0)),u&&(t.audioCodec=u=fi(u,s)),0===(null==(l=d)?void 0:l.indexOf("avc1"))&&(d=t.videoCodec=function(t){const i=t.split(",");for(let t=0;t<i.length;t++){const s=i[t].split(".");if(s.length>2){let e=s.shift()+".";e+=parseInt(s.shift()).toString(16),e+=("000"+parseInt(s.shift()).toString(16)).slice(-4),i[t]=e}}return i.join(",")}(d));const{width:f,height:v,unknownCodecs:p}=t;if(h||(h=!(!f||!v)),o||(o=!!d),a||(a=!!u),null!=p&&p.length||u&&!hi(u,"audio",s)||d&&!hi(d,"video",s))return;const{CODECS:g,"FRAME-RATE":m,"HDCP-LEVEL":y,"PATHWAY-ID":w,RESOLUTION:b,"VIDEO-RANGE":k}=c,S=`${w||"."}-${t.bitrate}-${b}-${m}-${g}-${k}-${y}`;if(n[S])if(n[S].uri===t.url||t.attrs["PATHWAY-ID"])n[S].addGroupId("audio",c.AUDIO),n[S].addGroupId("text",c.SUBTITLES);else{const i=r[S]+=1;t.attrs["PATHWAY-ID"]=new Array(i+1).join(".");const s=new is(t);n[S]=s,e.push(s)}else{const i=new is(t);n[S]=i,r[S]=1,e.push(i)}})),this.filterAndSortMediaOptions(e,i,h,o,a)}filterAndSortMediaOptions(t,i,s,e,n){let r=[],h=[],o=t;if((s||e)&&n&&(o=o.filter((({videoCodec:t,videoRange:i,width:s,height:e})=>{return(!!t||!(!s||!e))&&!!(n=i)&&Qi.indexOf(n)>-1;var n}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){i.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(i.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:i.url,error:t,reason:t.message})}}));if(i.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;r=i.audioTracks.filter((i=>!i.audioCodec||hi(i.audioCodec,"audio",t))),mh(r)}i.subtitles&&(h=i.subtitles,mh(h));const a=o.slice(0);o.sort(((t,i)=>{if(t.attrs["HDCP-LEVEL"]!==i.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(i.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==i.height)return t.height-i.height;if(t.frameRate!==i.frameRate)return t.frameRate-i.frameRate;if(t.videoRange!==i.videoRange)return Qi.indexOf(t.videoRange)-Qi.indexOf(i.videoRange);if(t.videoCodec!==i.videoCodec){const s=li(t.videoCodec),e=li(i.videoCodec);if(s!==e)return e-s}if(t.uri===i.uri&&t.codecSet!==i.codecSet){const s=ci(t.codecSet),e=ci(i.codecSet);if(s!==e)return e-s}return t.averageBitrate!==i.averageBitrate?t.averageBitrate-i.averageBitrate:0}));let l=a[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==a.length))for(let t=0;t<a.length;t++)if(a[t].pathwayId===o[0].pathwayId){l=a[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===l){var c;this._firstLevel=t;const i=l.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${i}`),void 0===(null==(c=this.hls.userConfig)?void 0:c.abrEwmaDefaultEstimate)){const t=Math.min(i,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===fh.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const u={levels:o,audioTracks:r,subtitleTracks:h,sessionData:i.sessionData,sessionKeys:i.sessionKeys,firstLevel:this._firstLevel,stats:i.stats,audio:n,video:e,altAudio:!(n&&!e)&&r.some((t=>!!t.url))};this.hls.trigger(A.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 i=this._levels;if(0===i.length)return;if(t<0||t>=i.length){const s=new Error("invalid level idx"),e=t<0;if(this.hls.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:t,fatal:e,error:s,reason:s.message}),e)return;t=Math.min(t,i.length-1)}const s=this.currentLevelIndex,e=this.currentLevel,n=e?e.attrs["PATHWAY-ID"]:void 0,r=i[t],h=r.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=r,s===t&&r.details&&e&&n===h)return;this.log(`Switching to level ${t} (${r.height?r.height+"p ":""}${r.videoRange?r.videoRange+" ":""}${r.codecSet?r.codecSet+" ":""}@${r.bitrate})${h?" with Pathway "+h:""} from level ${s}${n?" with Pathway "+n:""}`),this.hls.trigger(A.LEVEL_SWITCHING,{level:t,attrs:r.attrs,details:r.details,bitrate:r.bitrate,averageBitrate:r.averageBitrate,maxBitrate:r.maxBitrate,realBitrate:r.realBitrate,width:r.width,height:r.height,codecSet:r.codecSet,audioCodec:r.audioCodec,videoCodec:r.videoCodec,audioGroups:r.audioGroups,subtitleGroups:r.subtitleGroups,loaded:r.loaded,loadError:r.loadError,fragmentError:r.fragmentError,name:r.name,id:r.id,uri:r.uri,url:r.url,urlId:0,audioGroupIds:r.audioGroupIds,textGroupIds:r.textGroupIds});const o=r.details;if(!o||o.live){const t=this.switchParams(r.uri,null==e?void 0:e.details,o);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,i){!i.fatal&&i.context&&i.context.type===xi&&i.context.level===this.level&&this.checkRetry(i)}onFragBuffered(t,{frag:i}){if(void 0!==i&&i.type===Ii){const t=i.elementaryStreams;if(!Object.keys(t).some((i=>!!t[i])))return;const s=this._levels[i.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,i){var s;const{level:e,details:n}=i,r=this._levels[e];var h;if(!r)return this.warn(`Invalid level index ${e}`),void(null!=(h=i.deliveryDirectives)&&h.skip&&(n.deltaUpdateFailed=!0));e===this.currentLevelIndex?(0===r.fragmentError&&(r.loadError=0),this.playlistLoaded(e,i,r.details)):null!=(s=i.deliveryDirectives)&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const i=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let e=s.uri;if(t)try{e=t.addDirectives(e)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const n=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${n?" Pathway "+n:""} ${e}`),this.clearTimer(),this.hls.trigger(A.LEVEL_LOADING,{url:e,level:i,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 i;const s=this._levels.filter(((i,s)=>s!==t||(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach((t=>t.level=-1))),!1)));ls(s),this._levels=s,this.currentLevelIndex>-1&&null!=(i=this.currentLevel)&&i.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(A.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:i}){this._levels=i}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:i,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(A.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function mh(t){const i={};t.forEach((t=>{const s=t.groupId||"";t.id=i[s]=i[s]||0,i[s]++}))}class yh{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[s].loader;if(e){var i;if(t&&t!==(null==(i=e.context)?void 0:i.frag.type))return;e.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[t];(i.mediaKeySessionContext||i.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[t].loader;i&&i.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,i=L.KEY_LOAD_ERROR,s,e,n){return new Ys({type:M.NETWORK_ERROR,details:i,fatal:!1,frag:t,response:n,error:s,networkDetails:e})}loadClear(t,i){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:e}=t;for(let t=0;t<i.length;t++){const n=i[t];if(e<=n.cc&&("initSegment"===s||"initSegment"===n.sn||s<n.sn)){this.emeController.selectKeySystemFormat(n).then((t=>{n.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then((i=>this.loadInternal(t,i))):this.loadInternal(t)}loadInternal(t,i){var s,e;i&&t.setKeyFormat(i);const n=t.decryptdata;if(!n){const s=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,s))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));let h=this.keyUriToKeyInfo[r];if(null!=(s=h)&&s.decryptdata.key)return n.key=h.decryptdata.key,Promise.resolve({frag:t,keyInfo:h});var o;if(null!=(e=h)&&e.keyLoadPromise)switch(null==(o=h.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return h.keyLoadPromise.then((i=>(n.key=i.keyInfo.decryptdata.key,{frag:t,keyInfo:h})))}switch(h=this.keyUriToKeyInfo[r]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(h,t):this.loadKeyEME(h,t);case"AES-128":return this.loadKeyHTTP(h,t);default:return Promise.reject(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(t,i){const s={frag:i,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(t.keyLoadPromise=i.then((i=>(t.mediaKeySessionContext=i,s)))).catch((i=>{throw t.keyLoadPromise=null,i}))}return Promise.resolve(s)}loadKeyHTTP(t,i){const s=this.config,e=new(0,s.loader)(s);return i.keyLoader=t.loader=e,t.keyLoadPromise=new Promise(((n,r)=>{const h={keyInfo:t,frag:i,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,a={onSuccess:(t,i,s,e)=>{const{frag:h,keyInfo:o,url:a}=s;if(!h.decryptdata||o!==this.keyUriToKeyInfo[a])return r(this.createKeyLoadError(h,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),e));o.decryptdata.key=h.decryptdata.key=new Uint8Array(t.data),h.keyLoader=null,o.loader=null,n({frag:h,keyInfo:o})},onError:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),e,k({url:h.url,data:void 0},t)))},onTimeout:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),e))},onAbort:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,L.INTERNAL_ABORTED,new Error("key loading aborted"),e))}};e.load(h,{loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},a)}))}resetLoader(t){const{frag:i,keyInfo:s,url:e}=t,n=s.loader;i.keyLoader===n&&(i.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[e],n&&n.destroy()}}function wh(){return self.SourceBuffer||self.WebKitSourceBuffer}function bh(){if(!ni())return!1;const t=wh();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class kh{constructor(t,i,s,e){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=i,this.fragmentTracker=s,this.hls=e}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,i){const{config:s,media:e,stalled:n}=this;if(null===e)return;const{currentTime:r,seeking:h}=e,o=this.seeking&&!h,a=!this.seeking&&h;if(this.seeking=h,r!==t){if(this.moved=!0,h||(this.nudgeRetry=0),null!==n){if(this.stallReported){const t=self.performance.now()-n;I.warn(`playback not stuck anymore @${r}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(a||o)return void(this.stalled=null);if(e.paused&&!h||e.ended||0===e.playbackRate||!js.getBuffered(e).length)return void(this.nudgeRetry=0);const l=js.bufferInfo(e,r,0),c=l.nextStart||0;if(h){const t=l.len>2,s=!c||i&&i.start<=r||c-r>2&&!this.fragmentTracker.getPartialFragment(r);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;if(!(l.len>0||c))return;const t=Math.max(c,l.start||0)-r,i=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==i||null==(u=i.details)?void 0:u.live)?2*i.details.targetduration:2,n=this.fragmentTracker.getPartialFragment(r);if(t>0&&(t<=s||n))return void(e.paused||this._trySkipBufferHole(n))}const d=self.performance.now();if(null===n)return void(this.stalled=d);const f=d-n;if(!h&&f>=250&&(this._reportStall(l),!this.media))return;const v=js.bufferInfo(e,r,s.maxBufferHole);this._tryFixBufferStall(v,f)}_tryFixBufferStall(t,i){const{config:s,fragmentTracker:e,media:n}=this;if(null===n)return;const r=n.currentTime,h=e.getPartialFragment(r);(!h||!this._trySkipBufferHole(h)&&this.media)&&(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-r<s.maxBufferHole)&&i>1e3*s.highBufferWatchdogPeriod&&(I.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:i,media:s,stallReported:e}=this;if(!e&&s){this.stallReported=!0;const e=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);I.warn(e.message),i.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:e,buffer:t.len})}}_trySkipBufferHole(t){const{config:i,hls:s,media:e}=this;if(null===e)return 0;const n=e.currentTime,r=js.bufferInfo(e,n,0),h=n<r.start?r.start:r.nextStart;if(h){const o=h-n;if(o>0&&(r.len<=i.maxBufferHole||r.len>0&&r.len<1&&e.readyState<3)){if(o>i.maxBufferHole){const{fragmentTracker:i}=this;let s=!1;if(0===n){const t=i.getAppendedFrag(0,Ii);t&&h<t.end&&(s=!0)}if(!s){const s=t||i.getAppendedFrag(n,Ii);if(s){let t=!1,e=s.end;for(;e<h;){const s=i.getPartialFragment(e);if(!s){t=!0;break}e+=s.duration}if(t)return 0}}}const r=Math.max(h+.05,n+.1);if(I.warn(`skipping hole, adjusting currentTime from ${n} to ${r}`),this.moved=!0,this.stalled=null,e.currentTime=r,t&&!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${r}`);s.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:t})}return r}}return 0}_tryNudgeBuffer(){const{config:t,hls:i,media:s,nudgeRetry:e}=this;if(null===s)return;const n=s.currentTime;if(this.nudgeRetry++,e<t.nudgeMaxRetry){const r=n+(e+1)*t.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${n} to ${r}`);I.warn(h.message),s.currentTime=r,i.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${t.nudgeMaxRetry} nudges`);I.error(s.message),i.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class Sh extends fe{constructor(t,i,s){super(t,i,s,"[stream-controller]",Ii),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(A.ERROR,this.onError,this),t.on(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(A.BUFFER_CREATED,this.onBufferCreated,this),t.on(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(A.ERROR,this.onError,this),t.off(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(A.BUFFER_CREATED,this.onBufferCreated,this),t.off(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this.loadedmetadata=!1}i>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=se,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=ie}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case de:{const{levels:t,level:i}=this,s=null==t?void 0:t[i],e=null==s?void 0:s.details;if(e&&(!e.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(e))break;this.state=se;break}if(this.hls.nextLoadLevel!==this.level){this.state=se;break}break}case re:{var t;const i=self.performance.now(),s=this.retryDate;if(!s||i>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:i}=this;this.resetStartWhenNotLoaded((null==t?void 0:t[i])||null),this.state=se}}}this.state===se&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:i,levels:s,media:e}=this;if(null===i||!e&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const n=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[n])return;const r=s[n],h=this.getMainFwdBufferInfo();if(null===h)return;const o=this.getLevelDetails();if(o&&this._streamEnded(h,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(A.BUFFER_EOS,t),void(this.state=le)}if(!this.buffering)return;t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const a=r.details;if(!a||this.state===de||a.live&&this.levelLastLoaded!==r)return this.level=n,void(this.state=de);const l=h.len,c=this.getMaxBufferLength(r.maxBitrate);if(l>=c)return;this.backtrackFragment&&this.backtrackFragment.start>h.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:h.end;let d=this.getNextFragment(u,a);if(this.couldBacktrack&&!this.fragPrevious&&d&&"initSegment"!==d.sn&&this.fragmentTracker.getState(d)!==Os){var f;const t=(null!=(f=this.backtrackFragment)?f:d).sn,i=a.fragments[t-a.startSN-1];i&&d.cc===i.cc&&(d=i,this.fragmentTracker.removeFragment(i))}else this.backtrackFragment&&h.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,u)){if(!d.gap){const t=this.audioOnly&&!this.altAudio?B:j,i=(t===j?this.videoBuffer:this.mediaBuffer)||this.media;i&&this.afterBufferFlushed(i,t,Ii)}d=this.getNextFragmentLoopLoading(d,a,h,Ii,c)}d&&(!d.initSegment||d.initSegment.data||this.bitrateTest||(d=d.initSegment),this.loadFragment(d,r,u))}loadFragment(t,i,s){const e=this.fragmentTracker.getState(t);this.fragCurrent=t,e===Is||e===Ps?"initSegment"===t.sn?this._loadInitSegment(t,i):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,i)):(this.startFragRequested=!0,super.loadFragment(t,i,s)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Ii)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:i}=this;if(null!=i&&i.readyState){let s;const e=this.getAppendedFrag(i.currentTime);e&&e.start>1&&this.flushMainBuffer(0,e.start-1);const n=this.getLevelDetails();if(null!=n&&n.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*n.targetduration)return}if(!i.paused&&t){const i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*t[this.hls.nextLoadLevel].maxBitrate/(1e3*i)+1:0}else s=0;const r=this.getBufferedFrag(i.currentTime+s);if(r){const t=this.followingBufferedFrag(r);if(t){this.abortCurrentFrag();const i=t.duration,s=Math.max(r.end,(t.maxStartPTS?t.maxStartPTS:t.start)+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,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 ee:case ne:case re:case oe:case ae:this.state=se}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,i){super.flushMainBuffer(t,i,this.altAudio?"video":null)}onMediaAttached(t,i){super.onMediaAttached(t,i);const s=i.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 kh(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,i=t?t.currentTime:null;T(i)&&this.log(`Media seeked to ${i.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(A.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,i){let s=!1,e=!1;i.levels.forEach((t=>{const i=t.audioCodec;i&&(s=s||-1!==i.indexOf("mp4a.40.2"),e=e||-1!==i.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&e&&!function(){var t;const i=wh();return"function"==typeof(null==i||null==(t=i.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=i.levels,this.startFragRequested=!1}onLevelLoading(t,i){const{levels:s}=this;if(!s||this.state!==se)return;const e=s[i.level];(!e.details||e.details.live&&this.levelLastLoaded!==e||this.waitForCdnTuneIn(e.details))&&(this.state=de)}onLevelLoaded(t,i){var s;const{levels:e}=this,n=i.level,r=i.details,h=r.totalduration;if(!e)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""}, cc [${r.startCC}, ${r.endCC}] duration:${h}`);const o=e[n],a=this.fragCurrent;!a||this.state!==ne&&this.state!==re||a.level!==i.level&&a.loader&&this.abortCurrentFrag();let l=0;if(r.live||null!=(s=o.details)&&s.live){var c;if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;l=this.alignPlaylists(r,o.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(o.details=r,this.levelLastLoaded=o,this.hls.trigger(A.LEVEL_UPDATED,{details:r,level:n}),this.state===de){if(this.waitForCdnTuneIn(r))return;this.state=se}this.startFragRequested?r.live&&this.synchronizeToLiveEdge(r):this.setStartPosition(r,l),this.tick()}_handleFragmentLoadProgress(t){var i;const{frag:s,part:e,payload:n}=t,{levels:r}=this;if(!r)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 h=r[s.level],o=h.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 a=h.videoCodec,l=o.PTSKnown||!o.live,c=null==(i=s.initSegment)?void 0:i.data,u=this._getAudioCodec(h),d=this.transmuxer=this.transmuxer||new bn(this.hls,Ii,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=e?e.index:-1,v=new _s(s.level,s.sn,s.stats.chunkCount,n.byteLength,f,-1!==f);d.push(n,c,u,a,s,e,o.totalduration,l,v,this.initPTS[s.cc])}onAudioTrackSwitching(t,i){const s=this.altAudio;if(!i.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(A.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(A.AUDIO_TRACK_SWITCHED,i)}}onAudioTrackSwitched(t,i){const s=!!this.hls.audioTracks[i.id].url;if(s){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=s,this.tick()}onBufferCreated(t,i){const s=i.tracks;let e,n,r=!1;for(const t in s){const i=s[t];if("main"===i.id){if(n=t,e=i,"video"===t){const i=s[t];i&&(this.videoBuffer=i.buffer)}}else r=!0}r&&e?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=e.buffer):this.mediaBuffer=this.media}onFragBuffered(t,i){const{frag:s,part:e}=i;if(s&&s.type!==Ii)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${e?" p: "+e.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===ae&&(this.state=se));const n=e?e.stats:s.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,e)}onError(t,i){var s;if(i.fatal)this.state=ce;else switch(i.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ii,i);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==de||(null==(s=i.context)?void 0:s.type)!==xi||(this.state=se);break;case L.BUFFER_APPEND_ERROR:case L.BUFFER_FULL_ERROR:if(!i.parent||"main"!==i.parent)return;if(i.details===L.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(i)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}checkBuffer(){const{media:t,gapController:i}=this;t&&i&&t.readyState&&(!this.loadedmetadata&&js.getBuffered(t).length||i.poll(this.lastCurrentTime,this.state!==se?this.fragCurrent:null),this.lastCurrentTime=t.currentTime)}onFragLoadEmergencyAborted(){this.state=se,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:i}){(i!==B||this.audioOnly&&!this.altAudio)&&(this.afterBufferFlushed((i===j?this.videoBuffer:this.mediaBuffer)||this.media,i,Ii),this.tick())}onLevelsUpdated(t,i){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=i.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const i=t.currentTime;let s=this.startPosition;if(s>=0&&i<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${i}`);const e=js.getBuffered(t),n=(e.length?e.start(0):0)-s;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),s+=n,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${i}`),t.currentTime=s}}_getAudioCodec(t){let i=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&i&&(this.log("Swapping audio codec"),i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),i}_loadBitrateTestFrag(t,i){t.bitrateTest=!0,this._doFragLoad(t,i).then((s=>{const{hls:e}=this;if(!s||this.fragContextChanged(t))return;i.fragmentError=0,this.state=se,this.startFragRequested=!1,this.bitrateTest=!1;const n=t.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),e.trigger(A.FRAG_LOADED,s),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var i;const s="main",{hls:e}=this,{remuxResult:n,chunkMeta:r}=t,h=this.getCurrentContext(r);if(!h)return void this.resetWhenMissingContext(r);const{frag:o,part:a,level:l}=h,{video:c,text:u,id3:d,initSegment:f}=n,{details:v}=l,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=oe,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,f.tracks,t,r),e.trigger(A.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:f.tracks})}const t=f.initPTS,i=f.timescale;T(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:i},e.trigger(A.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:i}))}if(c&&v&&"initSegment"!==o.sn){const t=v.fragments[o.sn-1-v.startSN],i=o.sn===v.startSN,s=!t||o.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:e,startDTS:n,endDTS:h}=c;if(a)a.elementaryStreams[c.type]={startPTS:t,endPTS:e,startDTS:n,endDTS:h};else if(c.firstKeyFrame&&c.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),c.dropped&&c.independent){const n=this.getMainFwdBufferInfo(),r=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole;if(!i&&r<(c.firstKeyFramePTS?c.firstKeyFramePTS:t)-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(c.type,o.start,e,o.start,h,!0)}else i&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(c.type,t,e,n,h),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,a,r,i||s)}else{if(!i&&!s)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:t,endPTS:i,startDTS:s,endDTS:e}=p;a&&(a.elementaryStreams[B]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(B,t,i,s,e),this.bufferFragmentData(p,o,a,r)}v&&null!=d&&null!=(i=d.samples)&&i.length&&e.trigger(A.FRAG_PARSING_METADATA,{id:s,frag:o,details:v,samples:d.samples}),v&&u&&e.trigger(A.FRAG_PARSING_USERDATA,{id:s,frag:o,details:v,samples:u.samples})}}_bufferInitSegment(t,i,s,e){if(this.state!==oe)return;this.audioOnly=!!i.audio&&!i.video,this.altAudio&&!this.audioOnly&&delete i.audio;const{audio:n,video:r,audiovideo:h}=i;if(n){let i=t.audioCodec;const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=n.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===s.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==n.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),t.audioCodec&&t.audioCodec!==i&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${i}"`),n.levelCodec=i,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${i||""}/${t.audioCodec||""}/${n.codec}]`)}r&&(r.levelCodec=t.videoCodec,r.id="main",this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${t.videoCodec||""}/${r.codec}]`)),h&&this.log(`Init audiovideo buffer, container:${h.container}, codecs[level/parsed]=[${t.codecs}/${h.codec}]`),this.hls.trigger(A.BUFFER_CODECS,i),Object.keys(i).forEach((t=>{const n=i[t].initSegment;null!=n&&n.byteLength&&this.hls.trigger(A.BUFFER_APPENDING,{type:t,data:n,frag:s,part:null,chunkMeta:e,parent:s.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Ii)}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=se}checkFragmentChanged(){const t=this.media;let i=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(js.isBuffered(t,s)?i=this.getAppendedFrag(s):js.isBuffered(t,s+.1)&&(i=this.getAppendedFrag(s+.1)),i){this.backtrackFragment=null;const t=this.fragPlaying,s=i.level;t&&i.sn===t.sn&&t.level===s||(this.fragPlaying=i,this.hls.trigger(A.FRAG_CHANGED,{frag:i}),t&&t.level===s||this.hls.trigger(A.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 i=t.currentTime,s=this.currentFrag;if(s&&T(i)&&T(s.programDateTime))return new Date(s.programDateTime+1e3*(i-s.start))}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 Th{static get version(){return"1.5.20"}static isMSESupported(){return bh()}static isSupported(){return function(){if(!bh())return!1;const t=ni();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((i=>t.isTypeSupported(ai(i,"video"))))||["mp4a.40.2","fLaC"].some((i=>t.isTypeSupported(ai(i,"audio")))))}()}static getMediaSource(){return ni()}static get Events(){return A}static get ErrorTypes(){return M}static get ErrorDetails(){return L}static get DefaultConfig(){return Th.defaultConfig?Th.defaultConfig:fh}static set DefaultConfig(t){Th.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 wn,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){if("object"==typeof console&&!0===t||"object"==typeof t){!function(t,...i){i.forEach((function(i){C[i]=t[i]?t[i].bind(t):function(t){const i=self.console[t];return i?i.bind(self.console,`[${t}] >`):x}(i)}))}(t,"debug","log","info","warn","error");try{C.log('Debug logs enabled for "Hls instance" in hls.js version 1.5.20')}catch(t){C=D}}else C=D}(t.debug||!1);const i=this.config=function(t,i){if((i.liveSyncDurationCount||i.liveMaxLatencyDurationCount)&&(i.liveSyncDuration||i.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==i.liveMaxLatencyDurationCount&&(void 0===i.liveSyncDurationCount||i.liveMaxLatencyDurationCount<=i.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==i.liveMaxLatencyDuration&&(void 0===i.liveSyncDuration||i.liveMaxLatencyDuration<=i.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=vh(t),e=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,r=void 0===i[n],h=[];e.forEach((e=>{const o=`${t}Loading${e}`,a=i[o];if(void 0!==a&&r){h.push(o);const t=s[n].default;switch(i[n]={default:t},e){case"TimeOut":t.maxLoadTimeMs=a,t.maxTimeToFirstByteMs=a;break;case"MaxRetry":t.errorRetry.maxNumRetry=a,t.timeoutRetry.maxNumRetry=a;break;case"RetryDelay":t.errorRetry.retryDelayMs=a,t.timeoutRetry.retryDelayMs=a;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=a,t.timeoutRetry.maxRetryDelayMs=a}}})),h.length&&I.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(i[n])}`)})),k(k({},s),i)}(Th.DefaultConfig,t);this.userConfig=t,i.progressive&&function(t){const i=t.loader;i!==ah&&i!==hh?(I.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=ah,t.progressive=!0,t.enableSoftwareAES=!0,I.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i);const{abrController:s,bufferController:e,capLevelController:n,errorController:r,fpsController:h}=i,o=new r(this),a=this.abrController=new s(this),l=this.bufferController=new e(this),c=this.capLevelController=new n(this),u=new h(this),d=new Ui(this),f=new qi(this),v=i.contentSteeringController,p=v?new v(this):null,g=this.levelController=new gh(this,p),m=new Ns(this),y=new yh(this.config),w=this.streamController=new Sh(this,m,y);c.setStreamController(w),u.setStreamController(w);const b=[d,g,w];p&&b.splice(1,0,p),this.networkControllers=b;const S=[a,l,c,u,f,m];this.audioTrackController=this.createController(i.audioTrackController,b);const T=i.audioStreamController;T&&b.push(new T(this,m,y)),this.subtitleTrackController=this.createController(i.subtitleTrackController,b);const $=i.subtitleStreamController;$&&b.push(new $(this,m,y)),this.createController(i.timelineController,S),y.emeController=this.emeController=this.createController(i.emeController,S),this.cmcdController=this.createController(i.cmcdController,S),this.latencyController=this.createController(Yi,S),this.coreComponents=S,b.push(o);const E=o.onErrorOut;"function"==typeof E&&this.on(A.ERROR,E,o)}createController(t,i){if(t){const s=new t(this);return i&&i.push(s),s}return null}on(t,i,s=this){this._emitter.on(t,i,s)}once(t,i,s=this){this._emitter.once(t,i,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,i,s=this,e){this._emitter.off(t,i,s,e)}listeners(t){return this._emitter.listeners(t)}emit(t,i,s){return this._emitter.emit(t,i,s)}trigger(t,i){if(this.config.debug)return this.emit(t,t,i);try{return this.emit(t,t,i)}catch(i){I.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.triggeringException||(this.triggeringException=!0,this.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:t===A.ERROR,event:t,error:i}),this.triggeringException=!1)}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){I.log("destroy"),this.trigger(A.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){I.log("attachMedia"),this._media=t,this.trigger(A.MEDIA_ATTACHING,{media:t})}detachMedia(){I.log("detachMedia"),this.trigger(A.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const i=this.media,s=this.url,e=this.url=w.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,I.log(`loadSource:${e}`),i&&s&&(s!==e||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(A.MANIFEST_LOADING,{url:t})}startLoad(t=-1){I.log(`startLoad(${t})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t),this.started&&this.networkControllers);i++);}stopLoad(){I.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}resumeBuffering(){I.log("resume buffering"),this.networkControllers.forEach((t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){I.log("pause buffering"),this.networkControllers.forEach((t=>{t.pauseBuffering&&t.pauseBuffering()}))}swapAudioCodec(){I.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){I.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){I.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){I.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){I.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){I.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){I.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 i=!!t;i!==this.config.capLevelToPlayerSize&&(i?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}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&&(I.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Ji.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:i}}=this;if(!t)return 0;const s=t.length;for(let e=0;e<s;e++)if(t[e].maxBitrate>=i)return e;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:i,maxHdcpLevel:s}=this;let e;if(e=-1===i&&null!=t&&t.length?t.length-1:i,s)for(let i=e;i--;){const e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=s)return i}return e}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 i;return null==(i=this.audioTrackController)?void 0:i.setAudioOption(t)}setSubtitleOption(t){var i;return null==(i=this.subtitleTrackController)||i.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 i=this.audioTrackController;i&&(i.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 i=this.subtitleTrackController;i&&(i.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const i=this.subtitleTrackController;i&&(i.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 $h(t){const i=Math.floor(t/3600),s=Math.floor(t%3600/60),e=Math.floor(t%60);return i>0?`${i}:${s.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`:`${s}:${e.toString().padStart(2,"0")}`}Th.defaultConfig=void 0;var Eh=function(t,i,s,e){var n,r=arguments.length,h=r<3?i:null===e?e=Object.getOwnPropertyDescriptor(i,s):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)h=Reflect.decorate(t,i,s,e);else for(var o=t.length-1;o>=0;o--)(n=t[o])&&(h=(r<3?n(h):r>3?n(i,s,h):n(i,s))||h);return r>3&&h&&Object.defineProperty(i,s,h),h};const Ah=class{constructor(i){t(this,i),this.apiError=e(this,"rtkApiError",7),this.statsIntervalTimer=null,this.t=r(),this.iconPack=h,this.isSupported=!0,this.playerState=a.IDLE,this.livestreamState="IDLE",this.livestreamId=null,this.audioPlaybackError=!1,this.qualityLevels=[],this.selectedQuality=-1,this.currentTime=0,this.duration=0,this.hideControls=!0,this.hideControlsTimeout=null,this.livestreamUpdateListener=t=>{this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=t},this.updateProgress=()=>{this.currentTime=this.videoRef.currentTime},this.updateHlsStatsPeriodically=()=>{var t,i;this.duration=((null===(t=this.videoRef)||void 0===t?void 0:t.currentTime)||0)+((null===(i=this.hls)||void 0===i?void 0:i.latency)||0)},this.fastForwardToLatest=()=>{this.videoRef.currentTime=this.duration-1},this.togglePlay=()=>{this.videoRef.paused?(this.videoRef.play(),this.playerState=a.PLAYING):(this.videoRef.pause(),this.playerState=a.IDLE)},this.changeQuality=t=>{this.selectedQuality=t,this.hls&&(this.hls.currentLevel=t)},this.cleanupPlayer=()=>{var t;this.playerState=a.IDLE,this.videoRef&&(null===(t=this.hls)||void 0===t||t.destroy(),this.hls=null)},this.onMouseMovePlayer=()=>{this.hideControls=!1,clearTimeout(this.hideControlsTimeout),this.hideControlsTimeout=setTimeout((()=>{this.hideControls=!0}),5e3)},this.getLoadingState=()=>{let t="",i=!1,s=!1;switch(this.livestreamState){case"IDLE":t=this.t("livestream.idle"),i=!0,s=!1;break;case"STARTING":t=this.t("livestream.starting"),i=!0,s=!0;break;case"STOPPING":t=this.t("livestream.stopping"),i=!0,s=!0;break;case"LIVESTREAMING":this.playerState!==a.PLAYING&&this.playerState!==a.PAUSED&&(t=this.t("livestream.starting"),s=!0,i=!0);break;default:i=!1,t=this.t(""),s=!0}return{isLoading:i,loadingMessage:t,showIcon:s}},this.getErrorState=()=>{var t,i;let s=!1,e="";return"LIVESTREAMING"!==this.livestreamState?(s=!1,e=this.t(""),{isError:s,errorMessage:e}):(this.isSupported||(s=!0,e=this.t("livestream.error.not_supported")),this.playbackUrl||(s=!0,e=this.t("livestream.error.not_found")),this.playerError&&(s=!0,e=this.t(null!==(i=null===(t=this.playerError)||void 0===t?void 0:t.message)&&void 0!==i?i:"livestream.error.unknown")),{isError:s,errorMessage:e})},this.initialiseAndPlayStream=async()=>{try{this.meeting.__internals__.logger.info(`rtk-livestream-player:: About to initialise HLS. VideoRef? ${!!this.videoRef} playbackUrl: ${this.playbackUrl}`),Th.isSupported()?(this.meeting.__internals__.logger.info("rtk-livestream-player:: Initialising HLS. HLS is Supported"),this.hls=new Th({lowLatencyMode:!1}),window.rtk_hls=this.hls,this.meeting.__internals__.logger.info("rtk-livestream-player:: Loading source"),this.hls.loadSource(this.playbackUrl),this.meeting.__internals__.logger.info("rtk-livestream-player:: Attaching video element to HLS"),this.hls.attachMedia(this.videoRef),this.meeting.__internals__.logger.info("rtk-livestream-player:: Waiting async for HLS manifest parsing"),this.hls.on(Th.Events.ERROR,((t,i)=>{if(i.fatal){if(this.meeting.__internals__.logger.error(`rtk-livestream-player:: fatal error: ${i.details}`,{error:i.error}),this.playbackUrl&&"LIVESTREAMING"===this.livestreamState)return void setTimeout((()=>{this.playbackUrl&&"LIVESTREAMING"===this.livestreamState&&(this.meeting.__internals__.logger.info("rtk-livestream-player:: Retrying playbackUrl"),this.hls.loadSource(this.playbackUrl))}),5e3)}else this.meeting.__internals__.logger.warn(`rtk-livestream-player:: non-fatal error: ${i.details}`,{error:i.error})})),this.hls.on(Th.Events.MEDIA_ATTACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media attached")})),this.hls.on(Th.Events.MEDIA_DETACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media detached")})),this.hls.on(Th.Events.DESTROYING,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: hls is getting destroyed")})),this.hls.on(Th.Events.MANIFEST_PARSED,(async(t,i)=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: HLS manifest parsed");const{levels:s,autoLevelChangeAllowed:e}=l({meeting:this.meeting,hlsLevels:i.levels});this.qualityLevels=s.map(((t,i)=>({level:i,resolution:t.height?`${t.height}p`:"auto"}))),e&&(this.qualityLevels=[{level:-1,resolution:"Auto"},...this.qualityLevels]),this.hls.currentLevel=this.qualityLevels[0].level;try{this.meeting.__internals__.logger.info("rtk-livestream-player:: About to start video."),await this.videoRef.play(),this.meeting.__internals__.logger.info("rtk-livestream-player:: Video has started playing."),this.playerState=a.PLAYING}catch(t){this.audioPlaybackError=!0,this.meeting.__internals__.logger.error("rtk-livestream-player:: Video couldn't start. Trying with user gesture again.",{error:t})}})),this.videoRef.addEventListener("timeupdate",this.updateProgress),this.statsIntervalTimer=setInterval(this.updateHlsStatsPeriodically,1e3)):this.isSupported=!1}catch(t){this.meeting.__internals__.logger.error("rtk-livestream-player:: HLS couldn't initialise.",{error:t})}}}async updateLivestreamId(){const t=this.meeting.livestream.playbackUrl;if(!t||"LIVESTREAMING"!==this.livestreamState)return this.playbackUrl=null,this.livestreamId=null,void this.cleanupPlayer();const i=t.split("/"),s=i.findIndex((t=>"manifest"===t));this.livestreamId=i[s-1],await this.conditionallyStartLivestreamViewer()}async conditionallyStartLivestreamViewer(){this.videoRef&&this.playbackUrl&&!this.hls&&await this.initialiseAndPlayStream()}async connectedCallback(){this.meetingChanged(this.meeting)}disconnectedCallback(){this.meeting.livestream.removeListener("livestreamUpdate",this.livestreamUpdateListener),this.videoRef.removeEventListener("timeupdate",this.updateProgress),clearInterval(this.statsIntervalTimer),this.videoRef=null,this.hls&&this.hls.destroy(),window.rtk_hls=null}meetingChanged(t){null!=t&&(this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=this.meeting.livestream.state,this.meeting.livestream.on("livestreamUpdate",this.livestreamUpdateListener))}render(){var t,e;if(!o(this.meeting))return;const{isError:n,errorMessage:r}=this.getErrorState(),{isLoading:h,loadingMessage:l,showIcon:c}=this.getLoadingState();return i(s,null,i("div",{class:"player-container h-full max-h-full min-h-full w-full min-w-full max-w-full"},i("div",{ref:async t=>{this.videoContainerRef=t},class:"video-container relative flex h-full w-full flex-col items-center justify-center pb-20"},i("video",{onMouseMove:this.onMouseMovePlayer,ref:async t=>{this.videoRef=t,await this.conditionallyStartLivestreamViewer()},id:"livestream-video",style:{height:`${null===(t=this.el)||void 0===t?void 0:t.clientHeight}px`},controls:!1,onPlay:()=>{this.playerState===a.PAUSED&&(this.playerState=a.PLAYING)},onPause:()=>this.playerState=a.PAUSED}),this.playerState!==a.IDLE&&!this.hideControls&&i("div",{class:"control-bar",style:{width:`${null===(e=this.videoRef)||void 0===e?void 0:e.clientWidth}px`}},i("div",{class:"control-groups"},i("rtk-icon",{id:"playPause",onClick:this.togglePlay,size:"lg",class:"control-btn",icon:this.playerState===a.PLAYING?this.iconPack.pause:this.iconPack.play}),i("rtk-icon",{size:"lg",class:"control-btn",icon:this.iconPack.fastForward,onClick:this.fastForwardToLatest}),i("span",{class:"timings"},$h(this.currentTime)," /"," ",$h(this.duration))),i("div",{class:"control-groups"},i("select",{class:"level-select",onChange:t=>this.changeQuality(parseInt(t.target.value))},this.qualityLevels.map((t=>i("option",{value:t.level,selected:this.selectedQuality===t.level},t.resolution)))),i("rtk-fullscreen-toggle",{id:"fullscreen",class:"control-btn fullscreen-btn",targetElement:this.videoContainerRef,size:"sm",iconPack:this.iconPack,t:this.t,ref:t=>{var i;const s=document.createElement("style");s.textContent="\n rtk-controlbar-button {\n display: contents;\n background-color: var(--bg-brand-500);\n color: var(--text-text-on-brand);\n }\n ",null===(i=null==t?void 0:t.shadowRoot)||void 0===i||i.appendChild(s)}})))),this.audioPlaybackError&&i("div",{class:"unmute-popup"},i("h3",null,this.t("audio_playback.title")),i("p",null,this.t("audio_playback.description")),i("rtk-button",{kind:"wide",onClick:()=>{this.audioPlaybackError=!1,this.videoRef&&(this.videoRef.muted=!1,this.videoRef.play(),this.playerState=a.PLAYING)},title:this.t("audio_playback")},this.t("audio_playback"))),n&&i("div",{class:"loader"},i("rtk-icon",{icon:this.iconPack.warning}),i("p",null,r)),!n&&h&&i("div",{class:"loader"},c&&i("rtk-spinner",{id:"icon",part:"spinner",iconPack:this.iconPack,size:"md"}),i("p",null,l))))}get el(){return n(this)}static get watchers(){return{livestreamState:["updateLivestreamId"],meeting:["meetingChanged"]}}};Eh([c()],Ah.prototype,"meeting",void 0),Eh([c()],Ah.prototype,"size",void 0),Eh([c()],Ah.prototype,"t",void 0),Eh([c()],Ah.prototype,"iconPack",void 0),Ah.style=":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{display:flex;height:100%;max-height:100%;min-height:100%;width:100%;min-width:100%;max-width:100%;border-radius:var(--rtk-border-radius-md, 8px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity))}.player-container{position:relative;margin:var(--rtk-space-4, 16px);display:flex;flex-grow:1;align-items:center;justify-content:center;border-radius:var(--rtk-border-radius-md, 8px)}.loader{position:absolute;z-index:10;height:100%;width:100%;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity));display:flex;flex-direction:column;align-items:center;justify-content:center}p{margin-top:var(--rtk-space-1, 4px);margin-bottom:var(--rtk-space-1, 4px);font-size:16px;color:rgb(var(--rtk-colors-text-700, 255 255 255 / 0.64))}.unmute-popup{position:absolute;z-index:30 !important;display:flex;width:var(--rtk-space-72, 288px);flex-direction:column;border-radius:var(--rtk-border-radius-md, 8px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-800, 30 30 30) / var(--tw-bg-opacity));padding:var(--rtk-space-4, 16px);text-align:center;max-width:70%}.unmute-popup h3{margin:var(--rtk-space-0, 0px);font-size:16px;font-weight:500}.unmute-popup p{margin-top:var(--rtk-space-3, 12px);margin-bottom:var(--rtk-space-3, 12px);font-size:14px}.control-bar{position:absolute;bottom:0;display:flex;height:auto;justify-content:space-between;align-items:center;padding:10px 10px 0px 10px;z-index:10;}.timings{color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)))}.control-btn{border:none;margin-right:var(--rtk-space-2, 8px);border-radius:var(--rtk-border-radius-sm, 4px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)));cursor:pointer;font-size:24px;height:30px;width:30px}.fullscreen-btn{margin-right:20px;height:30px}.control-btn:hover{opacity:0.8}.control-btn:focus{outline:none}.control-groups{display:flex;align-items:center;justify-content:space-around}#livestream-video{aspect-ratio:16/9;max-width:100%;min-width:100%;left:var(--rtk-space-0, 0px);z-index:20;aspect-ratio:16 / 9;width:auto;border-radius:var(--rtk-border-radius-md, 8px);border-width:0px}.level-select{border-radius:var(--rtk-border-radius-sm, 4px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)));border:none;padding:5px 10px;font-size:14px;height:30px;cursor:pointer;border-radius:5px;margin-right:10px}.level-select:focus{outline:none}.level-select option{border-radius:var(--rtk-border-radius-sm, 4px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)))}.volume-control-holder{display:flex;justify-content:center;align-items:center}";var Mh=function(t,i,s,e){var n,r=arguments.length,h=r<3?i:null===e?e=Object.getOwnPropertyDescriptor(i,s):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)h=Reflect.decorate(t,i,s,e);else for(var o=t.length-1;o>=0;o--)(n=t[o])&&(h=(r<3?n(h):r>3?n(i,s,h):n(i,s))||h);return r>3&&h&&Object.defineProperty(i,s,h),h};const Lh=class{constructor(i){t(this,i),this.variant="primary",this.iconPack=h,this.t=r(),this.viewerCount=0,this.disconnectMeeting=t=>{var i;null!=t&&null!=this.countListener&&(null===(i=t.livestream)||void 0===i||i.removeListener("viewerCountUpdate",this.countListener))}}connectedCallback(){this.meetingChanged(this.meeting)}disconnectedCallback(){this.disconnectMeeting(this.meeting)}meetingChanged(t,i){var s;this.disconnectMeeting(i),null!=t&&(this.countListener=()=>{var i;this.viewerCount=null===(i=t.livestream)||void 0===i?void 0:i.viewerCount},this.countListener(),null===(s=t.livestream)||void 0===s||s.addListener("viewerCountUpdate",this.countListener))}render(){return o(this.meeting)?i(s,{tabIndex:0,role:"log","aria-label":`${this.viewerCount} ${this.t("viewers")}`},i("rtk-icon",{icon:this.iconPack.viewers,tabIndex:-1,"aria-hidden":!0,part:"icon"}),this.viewerCount," ",this.t("viewers")):i(s,{"data-hidden":!0})}static get watchers(){return{meeting:["meetingChanged"]}}};Mh([c()],Lh.prototype,"meeting",void 0),Mh([c()],Lh.prototype,"iconPack",void 0),Mh([c()],Lh.prototype,"t",void 0),Lh.style=":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{display:inline-flex;height:var(--rtk-space-10, 40px);-webkit-user-select:none;-moz-user-select:none;user-select:none;align-items:center;font-size:14px}:host([data-hidden]){display:none}:host([size='sm']){font-size:12px}rtk-icon{margin-right:var(--rtk-space-1, 4px);height:var(--rtk-space-5, 20px);width:var(--rtk-space-5, 20px)}:host([size='sm']) rtk-icon{height:var(--rtk-space-4, 16px);width:var(--rtk-space-4, 16px)}:host([variant='embedded']){--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-1000, 8 8 8) / var(--tw-bg-opacity));opacity:0.5;margin-top:var(--rtk-space-1, 4px);margin-left:var(--rtk-space-1, 4px);height:var(--rtk-space-5, 20px);border-radius:var(--rtk-border-radius-sm, 4px);padding-left:var(--rtk-space-2, 8px);padding-right:var(--rtk-space-2, 8px);font-size:12px}:host([variant='embedded']) rtk-icon{height:var(--rtk-space-4, 16px);width:var(--rtk-space-4, 16px)}";export{d as rtk_livestream_indicator,Ah as rtk_livestream_player,Lh as rtk_viewer_count}
|
|
1
|
+
import{r as t,h as i,H as s,c as e,a as n}from"./p-0ee570cd.js";import{c as r,a as h,s as o,P as a,t as l}from"./p-d3bf4348.js";import{S as c}from"./p-dac97779.js";var u=function(t,i,s,e){var n,r=arguments.length,h=r<3?i:null===e?e=Object.getOwnPropertyDescriptor(i,s):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)h=Reflect.decorate(t,i,s,e);else for(var o=t.length-1;o>=0;o--)(n=t[o])&&(h=(r<3?n(h):r>3?n(i,s,h):n(i,s))||h);return r>3&&h&&Object.defineProperty(i,s,h),h};const d=class{constructor(i){t(this,i),this.t=r(),this.iconPack=h,this.setIsLivestreaming=t=>{this.isLivestreaming="LIVESTREAMING"===t}}connectedCallback(){this.meetingChanged(this.meeting)}disconnectedCallback(){var t,i;null===(i=null===(t=this.meeting)||void 0===t?void 0:t.livestream)||void 0===i||i.removeListener("livestreamUpdate",this.setIsLivestreaming)}meetingChanged(t){var i,s;null!=t&&(this.setIsLivestreaming(null===(i=this.meeting.livestream)||void 0===i?void 0:i.state),null===(s=this.meeting.livestream)||void 0===s||s.on("livestreamUpdate",this.setIsLivestreaming))}render(){return o(this.meeting)&&this.isLivestreaming?i(s,null,i("div",{class:"indicator","aria-label":this.t("livestream.indicator"),part:"indicator"},i("rtk-icon",{icon:this.iconPack.start_livestream,size:this.size}),i("span",null,this.t("LIVE")))):i(s,{"data-hidden":!0})}static get watchers(){return{meeting:["meetingChanged"]}}};function f(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}u([c()],d.prototype,"meeting",void 0),u([c()],d.prototype,"size",void 0),u([c()],d.prototype,"t",void 0),u([c()],d.prototype,"iconPack",void 0),d.style=":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{margin-left:var(--rtk-space-2, 8px);margin-right:var(--rtk-space-2, 8px);display:flex}:host([data-hidden]){display:none}:host[size='sm']{margin-left:var(--rtk-space-1, 4px);margin-right:var(--rtk-space-1, 4px)}.indicator{display:flex;flex-direction:row;align-items:center;font-size:14px;--tw-text-opacity:1;color:rgba(var(--rtk-colors-danger, 255 45 45) / var(--tw-text-opacity))}rtk-icon{margin-right:var(--rtk-space-1, 4px);height:var(--rtk-space-5, 20px);width:var(--rtk-space-5, 20px);animation:blink 4s linear infinite}:host([size='sm']) rtk-icon{height:var(--rtk-space-4, 16px);width:var(--rtk-space-4, 16px)}:host([size='sm']) .indicator span{display:none}@keyframes blink{0%,10%{opacity:0}11%,100%{opacity:1}}";var v,p,g,m,y;v=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,p=/^(?=([^\/?#]*))\1([^]*)$/,g=/(?:\/|^)\.(?=\/)/g,m=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;var w={exports:{}}.exports=y={buildAbsoluteURL:function(t,i,s){if(s=s||{},t=t.trim(),!(i=i.trim())){if(!s.alwaysNormalize)return t;var e=y.parseURL(t);if(!e)throw new Error("Error trying to parse base URL.");return e.path=y.normalizePath(e.path),y.buildURLFromParts(e)}var n=y.parseURL(i);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=y.normalizePath(n.path),y.buildURLFromParts(n)):i;var r=y.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");if(!r.netLoc&&r.path&&"/"!==r.path[0]){var h=p.exec(r.path);r.netLoc=h[1],r.path=h[2]}r.netLoc&&!r.path&&(r.path="/");var o={scheme:r.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(o.netLoc=r.netLoc,"/"!==n.path[0]))if(n.path){var a=r.path,l=a.substring(0,a.lastIndexOf("/")+1)+n.path;o.path=y.normalizePath(l)}else o.path=r.path,n.params||(o.params=r.params,n.query||(o.query=r.query));return null===o.path&&(o.path=s.alwaysNormalize?y.normalizePath(n.path):n.path),y.buildURLFromParts(o)},parseURL:function(t){var i=v.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(g,"");t.length!==(t=t.replace(m,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};function b(t,i){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var e=Object.getOwnPropertySymbols(t);i&&(e=e.filter((function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable}))),s.push.apply(s,e)}return s}function k(t){for(var i=1;i<arguments.length;i++){var s=null!=arguments[i]?arguments[i]:{};i%2?b(Object(s),!0).forEach((function(i){var e,n,r;e=t,r=s[i],(n=function(t){var i=function(t,i){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var e=s.call(t,i||"default");if("object"!=typeof e)return e;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===i?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:String(i)}(n=i))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):b(Object(s)).forEach((function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(s,i))}))}return t}function S(){return S=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var s=arguments[i];for(var e in s)Object.prototype.hasOwnProperty.call(s,e)&&(t[e]=s[e])}return t},S.apply(this,arguments)}const T=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},$=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=E},E=Number.MAX_SAFE_INTEGER||9007199254740991;let A=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),M=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),L=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const x=function(){},D={trace:x,debug:x,log:x,warn:x,info:x,error:x};let C=D;const I=C,R=/^(\d+)x(\d+)$/,P=/(.+?)=(".*?"|.*?)(?:,|$)/g;class O{constructor(t){"string"==typeof t&&(t=O.parseAttrList(t)),S(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const i=parseInt(this[t],10);return i>Number.MAX_SAFE_INTEGER?1/0:i}hexadecimalInteger(t){if(this[t]){let i=(this[t]||"0x").slice(2);i=(1&i.length?"0":"")+i;const s=new Uint8Array(i.length/2);for(let t=0;t<i.length/2;t++)s[t]=parseInt(i.slice(2*t,2*t+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const i=parseInt(this[t],16);return i>Number.MAX_SAFE_INTEGER?1/0:i}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,i){const s=this[t];return s?parseFloat(s):i}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const i=R.exec(this[t]);if(null!==i)return{width:parseInt(i[1],10),height:parseInt(i[2],10)}}static parseAttrList(t){let i;const s={};for(P.lastIndex=0;null!==(i=P.exec(t));){let t=i[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1)),s[i[1].trim()]=t}return s}}function N(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class U{constructor(t,i){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,i){const s=i.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==s[i]){I.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=S(new O({}),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"]);T(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(T(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&&T(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class F{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 B="audio",j="video",_="audiovideo";class G{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[B]:null,[j]:null,[_]:null},this.baseurl=t}setByteRange(t,i){const s=t.split("@",2);let e;e=1===s.length?(null==i?void 0:i.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[e,parseInt(s[0])+e]}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=w.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class H extends G{constructor(t,i){super(i),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 F,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(!T(this.programDateTime))return null;const t=T(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),i=t.length;if(i>1||1===i&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const i=this.levelkeys[t];i&&!this._decryptdata&&(this._decryptdata=i.getDecryptData(this.sn))}}abortRequests(){var t,i;null==(t=this.loader)||t.abort(),null==(i=this.keyLoader)||i.abort()}setElementaryStreamInfo(t,i,s,e,n,r=!1){const{elementaryStreams:h}=this,o=h[t];o?(o.startPTS=Math.min(o.startPTS,i),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,e),o.endDTS=Math.max(o.endDTS,n)):h[t]={startPTS:i,endPTS:s,startDTS:e,endDTS:n,partial:r}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[B]=null,t[j]=null,t[_]=null}}class K extends G{constructor(t,i,s,e,n){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 F,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=i,this.index=e;const r=t.enumeratedString("BYTERANGE");r&&this.setByteRange(r,n),n&&(this.fragOffset=n.fragOffset+n.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 V{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 i=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!i||!this.live,this.advanced=this.endSN>t.endSN||i>0||0===i&&s>0,this.misses=this.updated||this.advanced?Math.floor(.6*t.misses):t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&T(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t: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 z(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function W(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const X="undefined"!=typeof self?self:void 0;var q={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Y="org.w3.clearkey",J="com.apple.streamingkeydelivery",Q="com.microsoft.playready",Z="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function tt(t){switch(t){case J:return q.FAIRPLAY;case Q:return q.PLAYREADY;case Z:return q.WIDEVINE;case Y:return q.CLEARKEY}}function it(t){return"edef8ba979d64acea3c827dcd51d21ed"===t?q.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===t?q.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===t||"e2719d58a985b3c9781ab030af78d30e"===t?q.CLEARKEY:void 0}function st(t){switch(t){case q.FAIRPLAY:return J;case q.PLAYREADY:return Q;case q.WIDEVINE:return Z;case q.CLEARKEY:return Y}}function et(t){const{drmSystems:i,widevineLicenseUrl:s}=t,e=i?[q.FAIRPLAY,q.WIDEVINE,q.PLAYREADY,q.CLEARKEY].filter((t=>!!i[t])):[];return!e[q.WIDEVINE]&&s&&e.push(q.WIDEVINE),e}const nt=null!=X&&null!=(rt=X.navigator)&&rt.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var rt;function ht(t){const i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),s=String.fromCharCode.apply(null,Array.from(i)),e=s.substring(s.indexOf("<"),s.length),n=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const i=z(t).subarray(0,16);return function(t){const i=function(t,i,s){const e=t[i];t[i]=t[s],t[s]=e};i(t,0,3),i(t,1,2),i(t,4,5),i(t,6,7)}(i),i}}return null}function ot(t,i,s){return Uint8Array.prototype.slice?t.slice(i,s):new Uint8Array(Array.prototype.slice.call(t,i,s))}const at=(t,i)=>i+10<=t.length&&73===t[i]&&68===t[i+1]&&51===t[i+2]&&t[i+3]<255&&t[i+4]<255&&t[i+6]<128&&t[i+7]<128&&t[i+8]<128&&t[i+9]<128,lt=(t,i)=>i+10<=t.length&&51===t[i]&&68===t[i+1]&&73===t[i+2]&&t[i+3]<255&&t[i+4]<255&&t[i+6]<128&&t[i+7]<128&&t[i+8]<128&&t[i+9]<128,ct=(t,i)=>{const s=i;let e=0;for(;at(t,i);)e+=10,e+=ut(t,i+6),lt(t,i+10)&&(e+=10),i+=e;if(e>0)return t.subarray(s,s+e)},ut=(t,i)=>{let s=0;return s=(127&t[i])<<21,s|=(127&t[i+1])<<14,s|=(127&t[i+2])<<7,s|=127&t[i+3],s},dt=(t,i)=>at(t,i)&&ut(t,i+6)+10<=t.length-i,ft=t=>{const i=gt(t);for(let t=0;t<i.length;t++){const s=i[t];if(vt(s))return kt(s)}},vt=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,pt=t=>{const i=String.fromCharCode(t[0],t[1],t[2],t[3]),s=ut(t,4);return{type:i,size:s,data:t.subarray(10,10+s)}},gt=t=>{let i=0;const s=[];for(;at(t,i);){const e=ut(t,i+6);i+=10;const n=i+e;for(;i+8<n;){const e=pt(t.subarray(i)),n=mt(e);n&&s.push(n),i+=e.size+10}lt(t,i)&&(i+=10)}return s},mt=t=>"PRIV"===t.type?yt(t):"W"===t.type[0]?bt(t):wt(t),yt=t=>{if(t.size<2)return;const i=St(t.data,!0),s=new Uint8Array(t.data.subarray(i.length+1));return{key:t.type,info:i,data:s.buffer}},wt=t=>{if(t.size<2)return;if("TXXX"===t.type){let i=1;const s=St(t.data.subarray(i),!0);i+=s.length+1;const e=St(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=St(t.data.subarray(1));return{key:t.type,data:i}},bt=t=>{if("WXXX"===t.type){if(t.size<2)return;let i=1;const s=St(t.data.subarray(i),!0);i+=s.length+1;const e=St(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=St(t.data);return{key:t.type,data:i}},kt=t=>{if(8===t.data.byteLength){const i=new Uint8Array(t.data);let s=(i[4]<<23)+(i[5]<<15)+(i[6]<<7)+i[7];return s/=45,1&i[3]&&(s+=47721858.84),Math.round(s)}},St=(t,i=!1)=>{const s=$t();if(s){const e=s.decode(t);if(i){const t=e.indexOf("\0");return-1!==t?e.substring(0,t):e}return e.replace(/\0/g,"")}const e=t.length;let n,r,h,o="",a=0;for(;a<e;){if(n=t[a++],0===n&&i)return o;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(n);break;case 12:case 13:r=t[a++],o+=String.fromCharCode((31&n)<<6|63&r);break;case 14:r=t[a++],h=t[a++],o+=String.fromCharCode((15&n)<<12|(63&r)<<6|63&h)}}return o};let Tt;function $t(){if(!navigator.userAgent.includes("PlayStation 4"))return Tt||void 0===self.TextDecoder||(Tt=new self.TextDecoder("utf-8")),Tt}const Et=function(t){let i="";for(let s=0;s<t.length;s++){let e=t[s].toString(16);e.length<2&&(e="0"+e),i+=e}return i},At=Math.pow(2,32)-1,Mt=[].push,Lt={video:1,audio:2,id3:3,text:4};function xt(t){return String.fromCharCode.apply(null,t)}function Dt(t,i){const s=t[i]<<8|t[i+1];return s<0?65536+s:s}function Ct(t,i){const s=Rt(t,i);return s<0?4294967296+s:s}function It(t,i){let s=Ct(t,i);return s*=Math.pow(2,32),s+=Ct(t,i+4),s}function Rt(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function Pt(t,i,s){t[i]=s>>24,t[i+1]=s>>16&255,t[i+2]=s>>8&255,t[i+3]=255&s}function Ot(t,i){const s=[];if(!i.length)return s;const e=t.byteLength;for(let n=0;n<e;){const r=Ct(t,n),h=r>1?n+r:e;if(xt(t.subarray(n+4,n+8))===i[0])if(1===i.length)s.push(t.subarray(n+8,h));else{const e=Ot(t.subarray(n+8,h),i.slice(1));e.length&&Mt.apply(s,e)}n=h}return s}function Nt(t){const i=[],s=t[0];let e=8;const n=Ct(t,e);e+=4;let r=0,h=0;0===s?(r=Ct(t,e),h=Ct(t,e+4),e+=8):(r=It(t,e),h=It(t,e+8),e+=16),e+=2;let o=t.length+h;const a=Dt(t,e);e+=2;for(let s=0;s<a;s++){let s=e;const r=Ct(t,s);s+=4;const h=2147483647&r;if(1==(2147483648&r)>>>31)return I.warn("SIDX has hierarchical references (not supported)"),null;const a=Ct(t,s);s+=4,i.push({referenceSize:h,subsegmentDuration:a,info:{duration:a/n,start:o,end:o+h-1}}),o+=h,s+=4,e=s}return{earliestPresentationTime:r,timescale:n,version:s,referencesCount:a,references:i}}function Ut(t){const i=[],s=Ot(t,["moov","trak"]);for(let t=0;t<s.length;t++){const e=s[t],n=Ot(e,["tkhd"])[0];if(n){let t=n[0];const s=Ct(n,0===t?12:20),r=Ot(e,["mdia","mdhd"])[0];if(r){t=r[0];const n=Ct(r,0===t?12:20),h=Ot(e,["mdia","hdlr"])[0];if(h){const t=xt(h.subarray(8,12)),r={soun:B,vide:j}[t];if(r){const t=Ft(Ot(e,["mdia","minf","stbl","stsd"])[0]);i[s]={timescale:n,type:r},i[r]=k({timescale:n,id:s},t)}}}}}return Ot(t,["moov","mvex","trex"]).forEach((t=>{const s=Ct(t,4),e=i[s];e&&(e.default={duration:Ct(t,12),flags:Ct(t,20)})})),i}function Ft(t){const i=t.subarray(8),s=i.subarray(86),e=xt(i.subarray(4,8));let n=e;const r="enca"===e||"encv"===e;if(r){const t=Ot(i,[e])[0];Ot(t.subarray("enca"===e?28:78),["sinf"]).forEach((t=>{const i=Ot(t,["schm"])[0];if(i){const s=xt(i.subarray(4,8));if("cbcs"===s||"cenc"===s){const i=Ot(t,["frma"])[0];i&&(n=xt(i))}}}))}switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Ot(s,["avcC"])[0];n+="."+jt(t[1])+jt(t[2])+jt(t[3]);break}case"mp4a":{const t=Ot(i,[e])[0],s=Ot(t.subarray(28),["esds"])[0];if(s&&s.length>12){let t=4;if(3!==s[t++])break;t=Bt(s,t),t+=2;const i=s[t++];if(128&i&&(t+=2),64&i&&(t+=s[t++]),4!==s[t++])break;t=Bt(s,t);const e=s[t++];if(64!==e)break;if(n+="."+jt(e),t+=12,5!==s[t++])break;t=Bt(s,t);const r=s[t++];let h=(248&r)>>3;31===h&&(h+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+h}break}case"hvc1":case"hev1":{const t=Ot(s,["hvcC"])[0],i=t[1],e=["","A","B","C"][i>>6],r=31&i,h=Ct(t,2),o=(32&i)>>5?"H":"L",a=t[12],l=t.subarray(6,12);n+="."+e+r,n+="."+h.toString(16).toUpperCase(),n+="."+o+a;let c="";for(let t=l.length;t--;){const i=l[t];(i||c)&&(c="."+i.toString(16).toUpperCase()+c)}n+=c;break}case"dvh1":case"dvhe":{const t=Ot(s,["dvcC"])[0],i=t[2]<<5&32|t[3]>>3&31;n+="."+_t(t[2]>>1&127)+"."+_t(i);break}case"vp09":{const t=Ot(s,["vpcC"])[0],i=t[5],e=t[6]>>4&15;n+="."+_t(t[4])+"."+_t(i)+"."+_t(e);break}case"av01":{const t=Ot(s,["av1C"])[0],i=t[1]>>>5,e=t[2]>>>7?"H":"M",r=(64&t[2])>>6,h=2===i&&r?(32&t[2])>>5?12:10:r?10:8,o=(16&t[2])>>4,a=(8&t[2])>>3,l=(4&t[2])>>2,c=3&t[2],u=1,d=1,f=1,v=0;n+="."+i+"."+_t(31&t[1])+e+"."+_t(h)+"."+o+"."+a+l+c+"."+_t(u)+"."+_t(d)+"."+_t(f)+"."+v;break}}return{codec:n,encrypted:r}}function Bt(t,i){const s=i+5;for(;128&t[i++]&&i<s;);return i}function jt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function _t(t){return(t<10?"0":"")+t}function Gt(t){const i=Ot(t,["schm"])[0];if(i){const s=xt(i.subarray(4,8));if("cbcs"===s||"cenc"===s)return Ot(t,["schi","tenc"])[0]}return null}function Ht(t){const i=Ct(t,0);let s=8;1&i&&(s+=4),4&i&&(s+=4);let e=0;const n=Ct(t,4);for(let r=0;r<n;r++)256&i&&(e+=Ct(t,s),s+=4),512&i&&(s+=4),1024&i&&(s+=4),2048&i&&(s+=4);return e}function Kt(t,i){const s=new Uint8Array(t.length+i.length);return s.set(t),s.set(i,t.length),s}function Vt(t,i){const s=[],e=i.samples,n=i.timescale,r=i.id;let h=!1;return Ot(e,["moof"]).map((o=>{const a=o.byteOffset-8;Ot(o,["traf"]).map((o=>{const l=Ot(o,["tfdt"]).map((t=>{const i=t[0];let s=Ct(t,4);return 1===i&&(s*=Math.pow(2,32),s+=Ct(t,8)),s/n}))[0];return void 0!==l&&(t=l),Ot(o,["tfhd"]).map((l=>{const c=Ct(l,4),u=16777215&Ct(l,0);let d=0;const f=!!(16&u);let v=0;const p=!!(32&u);let g=8;c===r&&(!!(1&u)&&(g+=8),!!(2&u)&&(g+=4),!!(8&u)&&(d=Ct(l,g),g+=4),f&&(v=Ct(l,g),g+=4),p&&(g+=4),"video"===i.type&&(h=function(t){if(!t)return!1;const i=t.indexOf("."),s=i<0?t:t.substring(0,i);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(i.codec)),Ot(o,["trun"]).map((r=>{const o=r[0],l=16777215&Ct(r,0),c=!!(1&l);let u=0;const f=!!(4&l),p=!!(256&l);let g=0;const m=!!(512&l);let y=0;const w=!!(1024&l),b=!!(2048&l);let k=0;const S=Ct(r,4);let T=8;c&&(u=Ct(r,T),T+=4),f&&(T+=4);let $=u+a;for(let a=0;a<S;a++){if(p?(g=Ct(r,T),T+=4):g=d,m?(y=Ct(r,T),T+=4):y=v,w&&(T+=4),b&&(k=0===o?Ct(r,T):Rt(r,T),T+=4),i.type===j){let i=0;for(;i<y;){const r=Ct(e,$);$+=4,zt(h,e[$])&&Wt(e.subarray($,$+r),h?2:1,t+k/n,s),$+=r,i+=r+4}}t+=g/n}})))}))}))})),s}function zt(t,i){if(t){const t=i>>1&63;return 39===t||40===t}return 6==(31&i)}function Wt(t,i,s,e){const n=Xt(t);let r=0;r+=i;let h=0,o=0,a=0;for(;r<n.length;){h=0;do{if(r>=n.length)break;a=n[r++],h+=a}while(255===a);o=0;do{if(r>=n.length)break;a=n[r++],o+=a}while(255===a);const t=n.length-r;let i=r;if(o<t)r+=o;else if(o>t){I.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===h){if(181===n[i++]){const t=Dt(n,i);if(i+=2,49===t){const t=Ct(n,i);if(i+=4,1195456820===t){const t=n[i++];if(3===t){const r=n[i++],o=64&r,a=o?2+3*(31&r):0,l=new Uint8Array(a);if(o){l[0]=r;for(let t=1;t<a;t++)l[t]=n[i++]}e.push({type:t,payloadType:h,pts:s,bytes:l})}}}}}else if(5===h&&o>16){const t=[];for(let s=0;s<16;s++){const e=n[i++].toString(16);t.push(1==e.length?"0"+e:e),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const r=o-16,a=new Uint8Array(r);for(let t=0;t<r;t++)a[t]=n[i++];e.push({payloadType:h,pts:s,uuid:t.join(""),userData:St(a),userDataBytes:a})}}}function Xt(t){const i=t.byteLength,s=[];let e=1;for(;e<i-2;)0===t[e]&&0===t[e+1]&&3===t[e+2]?(s.push(e+2),e+=2):e++;if(0===s.length)return t;const n=i-s.length,r=new Uint8Array(n);let h=0;for(e=0;e<n;h++,e++)h===s[0]&&(h++,s.shift()),r[e]=t[h];return r}function qt(t){const i=t.getUint32(0),s=t.byteOffset,e=t.byteLength;if(e<i)return{offset:s,size:e};if(1886614376!==t.getUint32(4))return{offset:s,size:i};const n=t.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:s,size:i};const r=t.buffer,h=Et(new Uint8Array(r,s+12,16)),o=t.getUint32(28);let a=null,l=null;if(0===n){if(i-32<o||o<22)return{offset:s,size:i};l=new Uint8Array(r,s+32,o)}else if(1===n){if(!o||e<s+32+16*o+16)return{offset:s,size:i};a=[];for(let t=0;t<o;t++)a.push(new Uint8Array(r,s+32+16*t,16))}return{version:n,systemId:h,kids:a,data:l,offset:s,size:i}}let Yt={};class Jt{static clearKeyUriToKeyIdMap(){Yt={}}constructor(t,i,s,e=[1],n=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=i,this.keyFormat=s,this.keyFormatVersions=e,this.iv=n,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case J:case Z:case Q:case Y:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||I.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const i=function(t){const i=new Uint8Array(16);for(let s=12;s<16;s++)i[s]=t>>8*(15-s)&255;return i}(t);return new Jt(this.method,this.uri,"identity",this.keyFormatVersions,i)}const i=function(t){const i=t.split(":");let s=null;if("data"===i[0]&&2===i.length){const t=i[1].split(";"),e=t[t.length-1].split(",");if(2===e.length){const i=e[1];"base64"===e[0]?(t.splice(-1,1),s=z(i)):s=function(t){const i=W(t).subarray(0,16),s=new Uint8Array(16);return s.set(i,16-i.length),s}(i)}}return s}(this.uri);if(i)switch(this.keyFormat){case Z:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case Q:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(t,i,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let e,n,r;if(i){e=1,n=new Uint8Array(16*i.length);for(let t=0;t<i.length;t++){const s=i[t];if(16!==s.byteLength)throw new RangeError("Invalid key");n.set(s,16*t)}}else e=0,n=new Uint8Array;e>0?(r=new Uint8Array(4),i.length>0&&new DataView(r.buffer).setUint32(0,i.length,!1)):r=new Uint8Array;const h=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(h.buffer).setUint32(0,s.byteLength,!1),function(t,...i){const s=i.length;let e=8,n=s;for(;n--;)e+=i[n].byteLength;const r=new Uint8Array(e);for(r[0]=e>>24&255,r[1]=e>>16&255,r[2]=e>>8&255,r[3]=255&e,r.set(t,4),n=0,e=8;n<s;n++)r.set(i[n],e),e+=i[n].byteLength;return r}([112,115,115,104],new Uint8Array([e,0,0,0]),t,r,n,h,s||new Uint8Array)}(t,null,i),this.keyId=ht(i);break}default:{let t=i.subarray(0,16);if(16!==t.length){const i=new Uint8Array(16);i.set(t,16-t.length),t=i}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=Yt[this.uri];if(!t){const i=Object.keys(Yt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16),new DataView(t.buffer,12,4).setUint32(0,i),Yt[this.uri]=t}this.keyId=t}return this}}const Qt=/\{\$([a-zA-Z0-9-_]+)\}/g;function Zt(t){return Qt.test(t)}function ti(t,i,s){if(null!==t.variableList||t.hasVariableRefs)for(let e=s.length;e--;){const n=s[e],r=i[n];r&&(i[n]=ii(t,r))}}function ii(t,i){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return i.replace(Qt,(i=>{const e=i.substring(2,i.length-1),n=null==s?void 0:s[e];return void 0===n?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${e}"`)),i):n}))}return i}function si(t,i,s){let e,n,r=t.variableList;if(r||(t.variableList=r={}),"QUERYPARAM"in i){e=i.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(e))throw new Error(`"${e}" does not match any query parameter in URI: "${s}"`);n=t.get(e)}catch(i){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${i.message}`))}}else e=i.NAME,n=i.VALUE;e in r?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${e}"`)):r[e]=n||""}function ei(t,i,s){const e=i.IMPORT;if(s&&e in s){let i=t.variableList;i||(t.variableList=i={}),i[e]=s[e]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${e}"`))}function ni(t=!0){if("undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const ri={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 hi(t,i,s=!0){return!t.split(",").some((t=>!oi(t,i,s)))}function oi(t,i,s=!0){var e;const n=ni(s);return null!=(e=null==n?void 0:n.isTypeSupported(ai(t,i)))&&e}function ai(t,i){return`${i}/mp4;codecs="${t}"`}function li(t){if(t){const i=t.substring(0,4);return ri.video[i]}return 2}function ci(t){return t.split(",").reduce(((t,i)=>{const s=ri.video[i];return s?(2*s+t)/(t?3:2):(ri.audio[i]+t)/(t?2:1)}),0)}const ui={},di=/flac|opus/i;function fi(t,i=!0){return t.replace(di,(t=>function(t,i=!0){if(ui[t])return ui[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let e=0;e<s.length;e++)if(oi(s[e],"audio",i))return ui[t]=s[e],s[e];return t}(t.toLowerCase(),i)))}function vi(t,i){return t&&"mp4a"!==t?t:i?i.split(",")[0]:i}const pi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,gi=/#EXT-X-MEDIA:(.*)/g,mi=/^#EXT(?:INF|-X-TARGETDURATION):/m,yi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),wi=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class bi{static findGroup(t,i){for(let s=0;s<t.length;s++){const e=t[s];if(e.id===i)return e}}static resolve(t,i){return w.buildAbsoluteURL(i,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return mi.test(t)}static parseMasterPlaylist(t,i){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Zt(t)},e=[];let n;for(pi.lastIndex=0;null!=(n=pi.exec(t));)if(n[1]){var r;const t=new O(n[1]);ti(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const h=ii(s,n[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:bi.resolve(h,i)},a=t.decimalResolution("RESOLUTION");a&&(o.width=a.width,o.height=a.height),Ti(t.CODECS,o),null!=(r=o.unknownCodecs)&&r.length||e.push(o),s.levels.push(o)}else if(n[3]){const t=n[4];switch(n[3]){case"SESSION-DATA":{const i=new O(t);ti(s,i,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=i["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=i);break}case"SESSION-KEY":{const e=ki(t,i,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):I.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${t}"`);break}case"DEFINE":{const e=new O(t);ti(s,e,["NAME","VALUE","QUERYPARAM"]),si(s,e,i)}break;case"CONTENT-STEERING":{const e=new O(t);ti(s,e,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:bi.resolve(e["SERVER-URI"],i),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Si(t)}}return s.levels=e.length>0&&e.length<s.levels.length?e:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,i,s){let e;const n={},r=s.levels,h={AUDIO:r.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:r.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(gi.lastIndex=0;null!==(e=gi.exec(t));){const t=new O(e[1]),r=t.TYPE;if(r){const e=h[r],a=n[r]||[];n[r]=a,ti(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const l=t.LANGUAGE,c=t["ASSOC-LANGUAGE"],u=t.CHANNELS,d=t.CHARACTERISTICS,f=t["INSTREAM-ID"],v={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:r,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?bi.resolve(t.URI,i):""};if(c&&(v.assocLang=c),u&&(v.channels=u),d&&(v.characteristics=d),f&&(v.instreamId=f),null!=e&&e.length){const t=bi.findGroup(e,v.groupId)||e[0];$i(v,t,"audioCodec"),$i(v,t,"textCodec")}a.push(v)}}return n}static parseLevelPlaylist(t,i,s,e,n,r){const h=new V(i),o=h.fragments;let a,l,c,u=null,d=0,f=0,v=0,p=0,g=null,m=new H(e,i),y=-1,w=!1,b=null;for(yi.lastIndex=0,h.m3u8=t,h.hasVariableRefs=Zt(t);null!==(a=yi.exec(t));){w&&(w=!1,m=new H(e,i),m.start=v,m.sn=d,m.cc=p,m.level=s,u&&(m.initSegment=u,m.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,b&&(m.setByteRange(b),b=null)));const t=a[1];if(t){m.duration=parseFloat(t);const i=(" "+a[2]).slice(1);m.title=i||null,m.tagList.push(i?["INF",t,i]:["INF",t])}else if(a[3]){if(T(m.duration)){m.start=v,c&&Mi(m,c,h),m.sn=d,m.level=s,m.cc=p,o.push(m);const t=(" "+a[3]).slice(1);m.relurl=ii(h,t),Ei(m,g),g=m,v+=m.duration,d++,f=0,w=!0}}else if(a[4]){const t=(" "+a[4]).slice(1);g?m.setByteRange(t,g):m.setByteRange(t)}else if(a[5])m.rawProgramDateTime=(" "+a[5]).slice(1),m.tagList.push(["PROGRAM-DATE-TIME",m.rawProgramDateTime]),-1===y&&(y=o.length);else{if(a=a[0].match(wi),!a){I.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<a.length&&void 0===a[l];l++);const t=(" "+a[l]).slice(1),n=(" "+a[l+1]).slice(1),v=a[l+2]?(" "+a[l+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":h.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":d=h.startSN=parseInt(n);break;case"SKIP":{const t=new O(n);ti(h,t,["RECENTLY-REMOVED-DATERANGES"]);const i=t.decimalInteger("SKIPPED-SEGMENTS");if(T(i)){h.skippedSegments=i;for(let t=i;t--;)o.unshift(null);d+=i}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(h.recentlyRemovedDateranges=s.split("\t"));break}case"TARGETDURATION":h.targetduration=Math.max(parseInt(n),1);break;case"VERSION":h.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":h.live=!1;break;case"#":(n||v)&&m.tagList.push(v?[n,v]:[n]);break;case"DISCONTINUITY":p++,m.tagList.push(["DIS"]);break;case"GAP":m.gap=!0,m.tagList.push([t]);break;case"BITRATE":m.tagList.push([t,n]);break;case"DATERANGE":{const t=new O(n);ti(h,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),ti(h,t,t.clientAttrs);const i=new U(t,h.dateRanges[t.ID]);i.isValid||h.skippedSegments?h.dateRanges[i.id]=i:I.warn(`Ignoring invalid DATERANGE tag: "${n}"`),m.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new O(n);ti(h,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?ei(h,t,r):si(h,t,i)}break;case"DISCONTINUITY-SEQUENCE":p=parseInt(n);break;case"KEY":{const t=ki(n,i,h);if(t.isSupported()){if("NONE"===t.method){c=void 0;break}c||(c={}),c[t.keyFormat]&&(c=S({},c)),c[t.keyFormat]=t}else I.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${n}"`);break}case"START":h.startTimeOffset=Si(n);break;case"MAP":{const t=new O(n);if(ti(h,t,["BYTERANGE","URI"]),m.duration){const n=new H(e,i);Ai(n,t,s,c),u=n,m.initSegment=u,u.rawProgramDateTime&&!m.rawProgramDateTime&&(m.rawProgramDateTime=u.rawProgramDateTime)}else{const i=m.byteRangeEndOffset;if(i){const t=m.byteRangeStartOffset;b=`${i-t}@${t}`}else b=null;Ai(m,t,s,c),u=m,w=!0}break}case"SERVER-CONTROL":{const t=new O(n);h.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),h.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new O(n);h.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=h.partList;t||(t=h.partList=[]);const s=f>0?t[t.length-1]:void 0,e=f++,r=new O(n);ti(h,r,["BYTERANGE","URI"]);const o=new K(r,m,i,e,s);t.push(o),m.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new O(n);ti(h,t,["URI"]),h.preloadHint=t;break}case"RENDITION-REPORT":{const t=new O(n);ti(h,t,["URI"]),h.renditionReports=h.renditionReports||[],h.renditionReports.push(t);break}default:I.warn(`line parsed but not handled: ${a}`)}}}g&&!g.relurl?(o.pop(),v-=g.duration,h.partList&&(h.fragmentHint=g)):h.partList&&(Ei(m,g),m.cc=p,h.fragmentHint=m,c&&Mi(m,c,h));const k=o.length,$=o[0],E=o[k-1];if(v+=h.skippedSegments*h.targetduration,v>0&&k&&E){h.averagetargetduration=v/k;const t=E.sn;h.endSN="initSegment"!==t?t:0,h.live||(E.endList=!0),$&&(h.startCC=$.cc)}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(v+=h.fragmentHint.duration),h.totalduration=v,h.endCC=p,y>0&&function(t,i){let s=t[i];for(let e=i;e--;){const i=t[e];if(!i)return;i.programDateTime=s.programDateTime-1e3*i.duration,s=i}}(o,y),h}}function ki(t,i,s){var e,n;const r=new O(t);ti(s,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const h=null!=(e=r.METHOD)?e:"",o=r.URI,a=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,c=null!=(n=r.KEYFORMAT)?n:"identity";o&&r.IV&&!a&&I.error(`Invalid IV: ${r.IV}`);const u=o?bi.resolve(o,i):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Jt(h,u,c,d,a)}function Si(t){const i=new O(t).decimalFloatingPoint("TIME-OFFSET");return T(i)?i:null}function Ti(t,i){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const e=s.filter((i=>function(t,i){const s=ri[i];return!!s&&!!s[t.slice(0,4)]}(i,t)));e.length&&(i[`${t}Codec`]=e.join(","),s=s.filter((t=>-1===e.indexOf(t))))})),i.unknownCodecs=s}function $i(t,i,s){const e=i[s];e&&(t[s]=e)}function Ei(t,i){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=i&&i.programDateTime&&(t.programDateTime=i.endProgramDateTime),T(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Ai(t,i,s,e){t.relurl=i.URI,i.BYTERANGE&&t.setByteRange(i.BYTERANGE),t.level=s,t.sn="initSegment",e&&(t.levelkeys=e),t.initSegment=null}function Mi(t,i,s){t.levelkeys=i;const{encryptedFragments:e}=s;e.length&&e[e.length-1].levelkeys===i||!Object.keys(i).some((t=>i[t].isCommonEncryption))||e.push(t)}var Li="manifest",xi="level",Di="audioTrack",Ci="subtitleTrack",Ii="main",Ri="audio",Pi="subtitle";function Oi(t){const{type:i}=t;switch(i){case Di:return Ri;case Ci:return Pi;default:return Ii}}function Ni(t,i){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=i.url),s}class Ui{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(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(A.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.LEVEL_LOADING,this.onLevelLoading,this),t.off(A.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(A.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const i=this.hls.config,s=new(i.pLoader||i.loader)(i);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const i=this.loaders[t];i&&i.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,i){const{url:s}=i;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Li,url:s,deliveryDirectives:null})}onLevelLoading(t,i){const{id:s,level:e,pathwayId:n,url:r,deliveryDirectives:h}=i;this.load({id:s,level:e,pathwayId:n,responseType:"text",type:xi,url:r,deliveryDirectives:h})}onAudioTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:Di,url:n,deliveryDirectives:r})}onSubtitleTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:Ci,url:n,deliveryDirectives:r})}load(t){var i;const s=this.hls.config;let e,n=this.getInternalLoader(t);if(n){const i=n.context;if(i&&i.url===t.url&&i.level===t.level)return void I.trace("[playlist-loader]: playlist request ongoing");I.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(e=t.type===Li?s.manifestLoadPolicy.default:S({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),T(null==(i=t.deliveryDirectives)?void 0:i.part)){let i;if(t.type===xi&&null!==t.level?i=this.hls.levels[t.level].details:t.type===Di&&null!==t.id?i=this.hls.audioTracks[t.id].details:t.type===Ci&&null!==t.id&&(i=this.hls.subtitleTracks[t.id].details),i){const t=i.partTarget,s=i.targetduration;if(t&&s){const i=1e3*Math.max(3*t,.8*s);e=S({},e,{maxTimeToFirstByteMs:Math.min(i,e.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(i,e.maxTimeToFirstByteMs)})}}}const r=e.errorRetry||e.timeoutRetry||{},h={onSuccess:(t,i,s,e)=>{const n=this.getInternalLoader(s);this.resetInternalLoader(s.type);const r=t.data;0===r.indexOf("#EXTM3U")?(i.parsing.start=performance.now(),bi.isMediaPlaylist(r)?this.handleTrackOrLevelPlaylist(t,i,s,e||null,n):this.handleMasterPlaylist(t,i,s,e)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),e||null,i)},onError:(t,i,s,e)=>{this.handleNetworkError(i,s,!1,t,e)},onTimeout:(t,i,s)=>{this.handleNetworkError(i,s,!0,void 0,t)}};n.load(t,{loadPolicy:e,timeout:e.maxLoadTimeMs,maxRetry:r.maxNumRetry||0,retryDelay:r.retryDelayMs||0,maxRetryDelay:r.maxRetryDelayMs||0},h)}handleMasterPlaylist(t,i,s,e){const n=this.hls,r=t.data,h=Ni(t,s),o=bi.parseMasterPlaylist(r,h);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,e,i);const{contentSteering:a,levels:l,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f}=o;this.variableList=f;const{AUDIO:v=[],SUBTITLES:p,"CLOSED-CAPTIONS":g}=bi.parseMasterPlaylistMedia(r,h,o);v.length&&(v.some((t=>!t.url))||!l[0].audioCodec||l[0].attrs.AUDIO||(I.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new O({}),bitrate:0,url:""}))),n.trigger(A.MANIFEST_LOADED,{levels:l,audioTracks:v,subtitles:p,captions:g,contentSteering:a,url:h,stats:i,networkDetails:e,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,i,s,e,n){const r=this.hls,{id:h,level:o,type:a}=s,l=Ni(t,s),c=T(o)?o:T(h)?h:0,u=Oi(s),d=bi.parseLevelPlaylist(t.data,l,c,u,0,this.variableList);if(a===Li){const t={attrs:new O({}),bitrate:0,details:d,name:"",url:l};r.trigger(A.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:l,stats:i,networkDetails:e,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=d,this.handlePlaylistLoaded(d,t,i,s,e,n)}handleManifestParsingError(t,i,s,e,n){this.hls.trigger(A.ERROR,{type:M.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:i.type===Li,url:t.url,err:s,error:s,reason:s.message,response:t,context:i,networkDetails:e,stats:n})}handleNetworkError(t,i,s=!1,e,n){let r=`A network ${s?"timeout":"error"+(e?" (status "+e.code+")":"")} occurred while loading ${t.type}`;t.type===xi?r+=`: ${t.level} id: ${t.id}`:t.type!==Di&&t.type!==Ci||(r+=` id: ${t.id} group-id: "${t.groupId}"`);const h=new Error(r);I.warn(`[playlist-loader]: ${r}`);let o=L.UNKNOWN,a=!1;const l=this.getInternalLoader(t);switch(t.type){case Li:o=s?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,a=!0;break;case xi:o=s?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,a=!1;break;case Di:o=s?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,a=!1;break;case Ci:o=s?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,a=!1}l&&this.resetInternalLoader(t.type);const c={type:M.NETWORK_ERROR,details:o,fatal:a,url:t.url,loader:l,context:t,error:h,networkDetails:i,stats:n};e&&(c.response=k({url:(null==i?void 0:i.url)||t.url,data:void 0},e)),this.hls.trigger(A.ERROR,c)}handlePlaylistLoaded(t,i,s,e,n,r){const h=this.hls,{type:o,level:a,id:l,groupId:c,deliveryDirectives:u}=e,d=Ni(i,e),f=Oi(e),v="number"==typeof e.level&&f===Ii?a:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void h.trigger(A.ERROR,{type:M.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:t,reason:t.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const p=t.playlistParsingError;if(p)h.trigger(A.ERROR,{type:M.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:p,reason:p.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s});else switch(t.live&&r&&(r.getCacheAge&&(t.ageHeader=r.getCacheAge()||0),r.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Li:case xi:h.trigger(A.LEVEL_LOADED,{details:t,level:v||0,id:l||0,stats:s,networkDetails:n,deliveryDirectives:u});break;case Di:h.trigger(A.AUDIO_TRACK_LOADED,{details:t,id:l||0,groupId:c||"",stats:s,networkDetails:n,deliveryDirectives:u});break;case Ci:h.trigger(A.SUBTITLE_TRACK_LOADED,{details:t,id:l||0,groupId:c||"",stats:s,networkDetails:n,deliveryDirectives:u})}}}function Fi(t,i){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,i.dispatchEvent(s)}function Bi(t,i){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(i.id))try{if(t.addCue(i),!t.cues.getCueById(i.id))throw new Error(`addCue is failed for: ${i}`)}catch(s){I.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(i.startTime,i.endTime,i.text);s.id=i.id,t.addCue(s)}catch(t){I.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function ji(t){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function _i(t,i,s,e){const n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0){const n=function(t,i,s){const e=[],n=function(t,i){if(i<t[0].startTime)return 0;const s=t.length-1;if(i>t[s].endTime)return-1;let e=0,n=s;for(;e<=n;){const r=Math.floor((n+e)/2);if(i<t[r].startTime)n=r-1;else{if(!(i>t[r].startTime&&e<s))return r;e=r+1}}return t[e].startTime-i<i-t[n].startTime?e:n}(t,i);if(n>-1)for(let r=n,h=t.length;r<h;r++){const n=t[r];if(n.startTime>=i&&n.endTime<=s)e.push(n);else if(n.startTime>s)return e}return e}(t.cues,i,s);for(let i=0;i<n.length;i++)e&&!e(n[i])||t.removeCue(n[i])}"disabled"===n&&(t.mode=n)}function Gi(t){const i=[];for(let s=0;s<t.length;s++){const e=t[s];"subtitles"!==e.kind&&"captions"!==e.kind||!e.label||i.push(t[s])}return i}var Hi="org.id3",Ki="https://aomedia.org/emsg/ID3";function Vi(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function zi(t,i,s,e,n){let r=new t(i,s,"");try{r.value=e,n&&(r.type=n)}catch(h){r=new t(i,s,JSON.stringify(n?k({type:n},e):e))}return r}const Wi=(()=>{const t=Vi();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Xi(t,i){return t.getTime()/1e3-i}class qi{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(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,i){this.media=i.media}onMediaDetaching(){this.id3Track&&(ji(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const i=this.getID3Track(t.textTracks);return i.mode="hidden",i}getID3Track(t){if(this.media){for(let i=0;i<t.length;i++){const s=t[i];if("metadata"===s.kind&&"id3"===s.label)return Fi(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,i){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:e}}}=this;if(!s&&!e)return;const{samples:n}=i;this.id3Track||(this.id3Track=this.createTrack(this.media));const r=Vi();if(r)for(let t=0;t<n.length;t++){const i=n[t].type;if(i===Ki&&!s||!e)continue;const h=gt(n[t].data);if(h){const s=n[t].pts;let e=s+n[t].duration;e>Wi&&(e=Wi),e-s<=0&&(e=s+.25);for(let t=0;t<h.length;t++){const n=h[t];if(!vt(n)){this.updateId3CueEnds(s,i);const t=zi(r,s,e,n,i);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,i){var s;const e=null==(s=this.id3Track)?void 0:s.cues;if(e)for(let s=e.length;s--;){const n=e[s];n.type===i&&n.startTime<t&&n.endTime===Wi&&(n.endTime=t)}}onBufferFlushing(t,{startOffset:i,endOffset:s,type:e}){const{id3Track:n,hls:r}=this;if(!r)return;const{config:{enableEmsgMetadataCues:h,enableID3MetadataCues:o}}=r;if(n&&(h||o)){let t;t="audio"===e?t=>t.type===Hi&&o:"video"===e?t=>t.type===Ki&&h:t=>t.type===Hi&&o||t.type===Ki&&h,_i(n,i,s,t)}}onLevelUpdated(t,{details:i}){if(!this.media||!i.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:e}=this,{dateRanges:n}=i,r=Object.keys(n);if(e){const t=Object.keys(s).filter((t=>!r.includes(t)));for(let i=t.length;i--;){const n=t[i];Object.keys(s[n].cues).forEach((t=>{e.removeCue(s[n].cues[t])})),delete s[n]}}const h=i.fragments[i.fragments.length-1];if(0===r.length||!T(null==h?void 0:h.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=h.programDateTime/1e3-h.start,a=Vi();for(let t=0;t<r.length;t++){const i=r[t],e=n[i],h=Xi(e.startDate,o),c=s[i],u=(null==c?void 0:c.cues)||{};let d=(null==c?void 0:c.durationKnown)||!1,f=Wi;const v=e.endDate;if(v)f=Xi(v,o),d=!0;else if(e.endOnNext&&!d){const t=r.reduce(((t,i)=>{if(i!==e.id){const s=n[i];if(s.class===e.class&&s.startDate>e.startDate&&(!t||e.startDate<t.startDate))return s}return t}),null);t&&(f=Xi(t.startDate,o),d=!0)}const p=Object.keys(e.attr);for(let t=0;t<p.length;t++){const s=p[t];if("ID"===(l=s)||"CLASS"===l||"START-DATE"===l||"DURATION"===l||"END-DATE"===l||"END-ON-NEXT"===l)continue;const n=u[s];if(n)d&&!c.durationKnown&&(n.endTime=f);else if(a){let t=e.attr[s];N(s)&&(t=Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const n=zi(a,h,f,{key:s,data:t},"com.apple.quicktime.HLS");n&&(n.id=i,this.id3Track.addCue(n),u[s]=n)}}s[i]={cues:u,dateRange:e,durationKnown:d}}var l}}class Yi{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:i}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:i,partHoldBack:s,targetduration:e}=t,{liveSyncDuration:n,liveSyncDurationCount:r,lowLatencyMode:h}=this.config,o=this.hls.userConfig;let a=h&&s||i;return(o.liveSyncDuration||o.liveSyncDurationCount||0===a)&&(a=void 0!==n?n:r*e),a+Math.min(1*this.stallCount,e)}get liveSyncPosition(){const t=this.estimateLiveEdge(),i=this.targetLatency,s=this.levelDetails;if(null===t||null===i||null===s)return null;const e=s.edge,n=e-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(e-s.totalduration,t-i-this.edgeStalled),n)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;return null===t?0:Math.max(t.age-3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration),0)}get forwardBufferLength(){const{media:t,levelDetails:i}=this;if(!t||!i)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):i.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(A.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(A.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(A.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(A.ERROR,this.onError,this)}onMediaAttached(t,i){this.media=i.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:i}){this.levelDetails=i,i.advanced&&this.timeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,i){var s;i.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&I.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:i}=this;if(!t||!i)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:e,maxLiveSyncPlaybackRate:n}=this.config;if(!e||1===n||!i.live)return;const r=this.targetLatency;if(null===r)return;const h=s-r;if(h<Math.min(this.maxLatency,r+i.targetduration)&&h>.05&&this.forwardBufferLength>1){const i=Math.min(2,Math.max(1,n)),s=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20;t.playbackRate=Math.min(i,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 Ji=["NONE","TYPE-0","TYPE-1",null],Qi=["SDR","PQ","HLG"];function Zi(t){const{canSkipUntil:i,canSkipDateRanges:s,age:e}=t;return i&&e<i/2?s?"v2":"YES":""}class ts{constructor(t,i,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=i,this.skip=s}addDirectives(t){const i=new self.URL(t);return void 0!==this.msn&&i.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&i.searchParams.set("_HLS_part",this.part.toString()),this.skip&&i.searchParams.set("_HLS_skip",this.skip),i.href}}class is{constructor(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!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,i){if(i)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(i)&&t.push(i)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(i)&&t.push(i)}}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,i){return!(!i||!t)&&-1!==t.indexOf(i)}function es(t,i){const s=i.startPTS;if(T(s)){let e,n=0;i.sn>t.sn?(n=s-t.start,e=t):(n=t.start-s,e=i),e.duration!==n&&(e.duration=n)}else i.start=i.sn>t.sn?t.cc===i.cc&&t.minEndPTS?t.start+(t.minEndPTS-t.start):t.start+t.duration:Math.max(t.start-i.duration,0)}function ns(t,i,s,e,n,r){e-s<=0&&(I.warn("Fragment should have a positive duration",i),e=s+i.duration,r=n+i.duration);let h=s,o=e;const a=i.startPTS,l=i.endPTS;if(T(a)){const t=Math.abs(a-s);i.deltaPTS=T(i.deltaPTS)?Math.max(t,i.deltaPTS):t,h=Math.max(s,a),s=Math.min(s,a),n=Math.min(n,i.startDTS),o=Math.min(e,l),e=Math.max(e,l),r=Math.max(r,i.endDTS)}const c=s-i.start;0!==i.start&&(i.start=s),i.duration=e-i.start,i.startPTS=s,i.maxStartPTS=h,i.startDTS=n,i.endPTS=e,i.minEndPTS=o,i.endDTS=r;const u=i.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let d;const f=u-t.startSN,v=t.fragments;for(v[f]=i,d=f;d>0;d--)es(v[d],v[d-1]);for(d=f;d<v.length-1;d++)es(v[d],v[d+1]);return t.fragmentHint&&es(v[v.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function rs(t,i){const s=i.startSN+i.skippedSegments-t.startSN,e=t.fragments;s<0||s>=e.length||hs(i,e[s].start)}function hs(t,i){if(i){const s=t.fragments;for(let e=t.skippedSegments;e<s.length;e++)s[e].start+=i;t.fragmentHint&&(t.fragmentHint.start+=i)}}function os(t,i,s){var e;return null!=t&&t.details?as(null==(e=t.details)?void 0:e.partList,i,s):null}function as(t,i,s){if(t)for(let e=t.length;e--;){const n=t[e];if(n.index===s&&n.fragment.sn===i)return n}return null}function ls(t){t.forEach(((t,i)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach((t=>{t.level=i}))}))}function cs(t){switch(t.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function us(t,i){const s=cs(i);return t.default[(s?"timeout":"error")+"Retry"]}function ds(t,i){const s="linear"===t.backoff?1:Math.pow(2,i);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function fs(t){return k(k({},t),{errorRetry:null,timeoutRetry:null})}function vs(t,i,s,e){if(!t)return!1;const n=i<t.maxNumRetry&&(0===(r=null==e?void 0:e.code)&&!1===navigator.onLine||!!r&&(r<400||r>499)||!!s);var r;return t.shouldRetry?t.shouldRetry(t,i,s,e,n):n}const ps=function(t,i){let s=0,e=t.length-1,n=null,r=null;for(;s<=e;){n=(s+e)/2|0,r=t[n];const h=i(r);if(h>0)s=n+1;else{if(!(h<0))return r;e=n-1}}return null};function gs(t,i,s=0,e=0,n=.005){let r=null;if(t){r=i[t.sn-i[0].sn+1]||null;const e=t.endDTS-s;e>0&&e<15e-7&&(s+=15e-7)}else 0===s&&0===i[0].start&&(r=i[0]);if(r&&((!t||t.level===r.level)&&0===ms(s,e,r)||function(t,i,s){if(i&&0===i.start&&i.level<t.level&&(i.endPTS||0)>0){const e=i.tagList.reduce(((t,i)=>("INF"===i[0]&&(t+=parseFloat(i[1])),t)),s);return t.start<=e}return!1}(r,t,Math.min(n,e))))return r;const h=ps(i,ms.bind(null,s,e));return!h||h===t&&r?r:h}function ms(t=0,i=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const e=Math.min(i,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-e<=t?1:s.start-e>t&&s.start?-1:0}function ys(t,i,s){const e=1e3*Math.min(i,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-e>t}class ws{constructor(t,i){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=I.log.bind(I,`${i}:`),this.warn=I.warn.bind(I,`${i}:`),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,i,s){const e=null==i?void 0:i.renditionReports;if(e){let n=-1;for(let s=0;s<e.length;s++){const r=e[s];let h;try{h=new self.URL(r.URI,i.url).href}catch(t){I.warn(`Could not construct new URL for Rendition Report: ${t}`),h=r.URI||""}if(h===t){n=s;break}h===t.substring(0,h.length)&&(n=s)}if(-1!==n){const t=e[n],r=parseInt(t["LAST-MSN"])||(null==i?void 0:i.lastPartSn);let h=parseInt(t["LAST-PART"])||(null==i?void 0:i.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(i.age-i.partTarget,i.targetduration);h>=0&&t>i.partTarget&&(h+=1)}const o=s&&Zi(s);return new ts(r,h>=0?h: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,i,s){const{details:e,stats:n}=i,r=self.performance.now(),h=n.loading.first?Math.max(0,r-n.loading.first):0;if(e.advancedDateTime=Date.now()-h,e.live||null!=s&&s.live){if(e.reloaded(s),s&&this.log(`live playlist ${t} ${e.advanced?"REFRESHED "+e.lastPartSn+"-"+e.lastPartIndex:e.updated?"UPDATED":"MISSED"}`),s&&e.fragments.length>0&&function(t,i){let s=null;const e=t.fragments;for(let t=e.length-1;t>=0;t--){const i=e[t].initSegment;if(i){s=i;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,i,s){const e=i.skippedSegments,n=Math.max(t.startSN,i.startSN)-i.startSN,r=(t.fragmentHint?1:0)+(e?i.endSN:Math.min(t.endSN,i.endSN))-i.startSN,h=i.startSN-t.startSN,o=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments,a=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=n;t<=r;t++){const n=a[h+t];let r=o[t];e&&!r&&t<e&&(r=i.fragments[t]=n),n&&r&&s(n,r,t,o)}}(t,i,((t,e,r,h)=>{if(i.skippedSegments&&e.cc!==t.cc){const i=t.cc-e.cc;for(let t=r;t<h.length;t++)h[t].cc+=i}T(t.startPTS)&&T(t.endPTS)&&(e.start=e.startPTS=t.startPTS,e.startDTS=t.startDTS,e.maxStartPTS=t.maxStartPTS,e.endPTS=t.endPTS,e.endDTS=t.endDTS,e.minEndPTS=t.minEndPTS,e.duration=t.endPTS-t.startPTS,e.duration&&(n=e),i.PTSKnown=i.alignedSliding=!0),e.elementaryStreams=t.elementaryStreams,e.loader=t.loader,e.stats=t.stats,t.initSegment&&(e.initSegment=t.initSegment,s=t.initSegment)}));const r=i.fragments;if(s&&(i.fragmentHint?r.concat(i.fragmentHint):r).forEach((t=>{var i;!t||t.initSegment&&t.initSegment.relurl!==(null==(i=s)?void 0:i.relurl)||(t.initSegment=s)})),i.skippedSegments){if(i.deltaUpdateFailed=r.some((t=>!t)),i.deltaUpdateFailed){I.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=i.skippedSegments;t--;)r.shift();i.startSN=r[0].sn}else i.canSkipDateRanges&&(i.dateRanges=function(t,i,s){const e=S({},t);return s&&s.forEach((t=>{delete e[t]})),Object.keys(i).forEach((t=>{const s=new U(i[t].attr,e[t]);s.isValid?e[t]=s:I.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(i[t].attr)}"`)})),e}(t.dateRanges,i.dateRanges,i.recentlyRemovedDateranges));i.startCC=i.fragments[0].cc,i.endCC=r[r.length-1].cc}!function(t,i,s){if(t&&i){let e=0;for(let n=0,r=t.length;n<=r;n++){const r=t[n],h=i[n+e];r&&h&&r.index===h.index&&r.fragment.sn===h.fragment.sn?s(r,h):e--}}}(t.partList,i.partList,((t,i)=>{i.elementaryStreams=t.elementaryStreams,i.stats=t.stats})),n?ns(i,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):rs(t,i),r.length&&(i.totalduration=i.edge-r[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const h=i.advancedDateTime;if(i.advanced&&h){const t=i.edge;i.driftStart||(i.driftStartTime=h,i.driftStart=t),i.driftEndTime=h,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime}(s,e),!this.canLoad||!e.live)return;let h,o,a;if(e.canBlockReload&&e.endSN&&e.advanced){const t=this.hls.config.lowLatencyMode,n=e.lastPartSn,r=e.endSN,l=e.lastPartIndex,c=n===r;-1!==l?(o=c?r+1:n,a=c?t?0:l:l+1):o=r+1;const u=e.age;let d=Math.min(u+e.ageHeader-e.partTarget,1.5*e.targetduration);if(d>0){if(s&&d>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${d} with playlist age: ${e.age}`),d=0;else{const t=Math.floor(d/e.targetduration);o+=t,void 0!==a&&(a+=Math.round(d%e.targetduration/e.partTarget)),this.log(`CDN Tune-in age: ${e.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${d} skip sn ${t} to part ${a}`)}e.tuneInGoal=d}if(h=this.getDeliveryDirectives(e,i.deliveryDirectives,o,a),t||!c)return void this.loadPlaylist(h)}else(e.canBlockReload||e.canSkipUntil)&&(h=this.getDeliveryDirectives(e,i.deliveryDirectives,o,a));const l=this.hls.mainForwardBufferInfo,c=function(t,i=1/0){let s=1e3*t.targetduration;if(t.updated){const e=t.fragments;if(e.length&&4*s>i){const t=1e3*e[e.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}(e,1e3*(e.edge-(l?l.end-l.len:0)));e.updated&&r>this.requestScheduled+c&&(this.requestScheduled=n.loading.start),void 0!==o&&e.canBlockReload?this.requestScheduled=n.loading.first+c-(1e3*e.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+c<r?this.requestScheduled=r:this.requestScheduled-r<=0&&(this.requestScheduled+=c);let u=this.requestScheduled-r;u=Math.max(0,u),this.log(`reload live playlist ${t} in ${Math.round(u)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(h)),u)}else this.clearTimer()}getDeliveryDirectives(t,i,s,e){let n=Zi(t);return null!=i&&i.skip&&t.deltaUpdateFailed&&(s=i.msn,e=i.part,n=""),new ts(s,e,n)}checkRetry(t){const i=t.details,s=cs(t),e=t.errorAction,{action:n,retryCount:r=0,retryConfig:h}=e||{},o=!!e&&!!h&&(5===n||!e.resolved&&2===n);if(o){var a;if(this.requestScheduled=-1,r>=h.maxNumRetry)return!1;if(s&&null!=(a=t.context)&&a.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${h.maxNumRetry} after "${i}" without delivery-directives`),this.loadPlaylist();else{const t=ds(h,r);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${r+1}/${h.maxNumRetry} after "${i}" in ${t}ms`)}t.levelRetry=!0,e.resolved=!0}return o}}class bs{constructor(t,i=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_=i,this.totalWeight_=s}sample(t,i){const s=Math.pow(this.alpha_,t);this.estimate_=i*(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 ks{constructor(t,i,s,e=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 bs(t),this.fast_=new bs(i),this.defaultTTFB_=e,this.ttfb_=new bs(t)}update(t,i){const{slow_:s,fast_:e,ttfb_:n}=this;s.halfLife!==t&&(this.slow_=new bs(t,s.getEstimate(),s.getTotalWeight())),e.halfLife!==i&&(this.fast_=new bs(i,e.getEstimate(),e.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new bs(t,n.getEstimate(),n.getTotalWeight()))}sample(t,i){const s=(t=Math.max(t,this.minDelayMs_))/1e3,e=8*i/s;this.fast_.sample(s,e),this.slow_.sample(s,e)}sampleTTFB(t){const i=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(i,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 Ss={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Ts={};function $s(t,i,s,e,n,r){const h=t.audioCodec?t.audioGroups:null,o=null==r?void 0:r.audioCodec,a=null==r?void 0:r.channels,l=a?parseInt(a):o?1/0:2;let c=null;if(null!=h&&h.length)try{c=1===h.length&&h[0]?i.groups[h[0]].channels:h.reduce(((t,s)=>{if(s){const e=i.groups[s];if(!e)throw new Error(`Audio track group ${s} not found`);Object.keys(e.channels).forEach((i=>{t[i]=(t[i]||0)+e.channels[i]}))}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(e,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(n,8e6))||!!c&&T(l)&&Object.keys(c).some((t=>parseInt(t)>l))}function Es(t,i,s){const e=t.videoCodec,n=t.audioCodec;if(!e||!n||!s)return Promise.resolve(Ss);const r={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},h=t.videoRange;"SDR"!==h&&(r.transferFunction=h.toLowerCase());const o=e.split(",").map((t=>({type:"media-source",video:k(k({},r),{},{contentType:ai(t,"video")})})));return n&&t.audioGroups&&t.audioGroups.forEach((t=>{var s;t&&(null==(s=i.groups[t])||s.tracks.forEach((i=>{if(i.groupId===t){const t=parseFloat(i.channels||"");T(t)&&t>2&&o.push.apply(o,n.split(",").map((i=>({type:"media-source",audio:{contentType:ai(i,"audio"),channels:""+t}}))))}})))})),Promise.all(o.map((t=>{const i=function(t){const{audio:i,video:s}=t,e=s||i;if(e){const t=e.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(i)return`c${i.channels}${i.spatialRendering?"s":"n"}_${t}`}return""}(t);return Ts[i]||(Ts[i]=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 As(t,i){I.log(`[abr] start candidates with "${t}" ignored because ${i}`)}function Ms(t,i,s){if("attrs"in t){const s=i.indexOf(t);if(-1!==s)return s}for(let e=0;e<i.length;e++)if(Ls(t,i[e],s))return e;return-1}function Ls(t,i,s){const{groupId:e,name:n,lang:r,assocLang:h,default:o}=t,a=t.forced;return(void 0===e||i.groupId===e)&&(void 0===n||i.name===n)&&(void 0===r||i.lang===r)&&(void 0===r||i.assocLang===h)&&(void 0===o||i.default===o)&&(void 0===a||i.forced===a)&&(!("characteristics"in t)||function(t,i=""){const s=t.split(","),e=i.split(",");return s.length===e.length&&!s.some((t=>-1===e.indexOf(t)))}(t.characteristics||"",i.characteristics))&&(void 0===s||s(t,i))}function xs(t,i){const{audioCodec:s,channels:e}=t;return!(void 0!==s&&(i.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==e&&e!==(i.channels||"2"))}function Ds(t,i,s){for(let e=i;e>-1;e--)if(s(t[e]))return e;for(let e=i+1;e<t.length;e++)if(s(t[e]))return e;return-1}class Cs{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var Is="NOT_LOADED",Rs="APPENDING",Ps="PARTIAL",Os="OK";class Ns{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(A.BUFFER_APPENDED,this.onBufferAppended,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this),t.on(A.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.BUFFER_APPENDED,this.onBufferAppended,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this),t.off(A.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,i){const s=this.activePartLists[i];if(s)for(let i=s.length;i--;){const e=s[i];if(!e)break;const n=e.end;if(e.start<=t&&null!==n&&t<=n)return e}return this.getBufferedFrag(t,i)}getBufferedFrag(t,i){const{fragments:s}=this,e=Object.keys(s);for(let n=e.length;n--;){const r=s[e[n]];if((null==r?void 0:r.body.type)===i&&r.buffered){const i=r.body;if(i.start<=t&&t<=i.end)return i}}return null}detectEvictedFragments(t,i,s,e){this.timeRanges&&(this.timeRanges[t]=i);const n=(null==e?void 0:e.fragment.sn)||-1;Object.keys(this.fragments).forEach((e=>{const r=this.fragments[e];if(!r)return;if(n>=r.body.sn)return;if(!r.buffered&&!r.loaded)return void(r.body.type===s&&this.removeFragment(r.body));const h=r.range[t];h&&h.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,i);return s&&this.removeFragment(r.body),s}))}))}detectPartialFragments(t){const i=this.timeRanges,{frag:s,part:e}=t;if(!i||"initSegment"===s.sn)return;const n=Fs(s),r=this.fragments[n];if(!r||r.buffered&&s.gap)return;const h=!s.relurl;Object.keys(i).forEach((t=>{const n=s.elementaryStreams[t];n&&(r.range[t]=this.getBufferedTimes(s,e,h||!0===n.partial,i[t]))})),r.loaded=null,Object.keys(r.range).length?(r.buffered=!0,(r.body.endList=s.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),Us(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}removeParts(t,i){const s=this.activePartLists[i];s&&(this.activePartLists[i]=s.filter((i=>i.fragment.sn>=t)))}fragBuffered(t,i){const s=Fs(t);let e=this.fragments[s];!e&&i&&(e=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),e&&(e.loaded=null,e.buffered=!0)}getBufferedTimes(t,i,s,e){const n={time:[],partial:s},r=t.start,h=t.end,o=t.minEndPTS||h,a=t.maxStartPTS||r;for(let t=0;t<e.length;t++){const i=e.start(t)-this.bufferPadding,s=e.end(t)+this.bufferPadding;if(a>=i&&o<=s){n.time.push({startPTS:Math.max(r,e.start(t)),endPTS:Math.min(h,e.end(t))});break}if(r<s&&h>i){const i=Math.max(r,e.start(t)),s=Math.min(h,e.end(t));s>i&&(n.partial=!0,n.time.push({startPTS:i,endPTS:s}))}else if(h<=i)break}return n}getPartialFragment(t){let i,s,e,n=null,r=0;const{bufferPadding:h,fragments:o}=this;return Object.keys(o).forEach((a=>{const l=o[a];l&&Us(l)&&(s=l.body.start-h,e=l.body.end+h,t>=s&&t<=e&&(i=Math.min(t-s,e-t),r<=i&&(n=l.body,r=i)))})),n}isEndListAppended(t){const i=this.endListFragments[t];return void 0!==i&&(i.buffered||Us(i))}getState(t){const i=Fs(t),s=this.fragments[i];return s?s.buffered?Us(s)?Ps:Os:Rs:Is}isTimeBuffered(t,i,s){let e,n;for(let r=0;r<s.length;r++){if(e=s.start(r)-this.bufferPadding,n=s.end(r)+this.bufferPadding,t>=e&&i<=n)return!0;if(i<=e)return!1}return!1}onFragLoaded(t,i){const{frag:s,part:e}=i;if("initSegment"===s.sn||s.bitrateTest)return;const n=e?null:i,r=Fs(s);this.fragments[r]={body:s,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(t,i){const{frag:s,part:e,timeRanges:n}=i;if("initSegment"===s.sn)return;const r=s.type;if(e){let t=this.activePartLists[r];t||(this.activePartLists[r]=t=[]),t.push(e)}this.timeRanges=n,Object.keys(n).forEach((t=>{this.detectEvictedFragments(t,n[t],r,e)}))}onFragBuffered(t,i){this.detectPartialFragments(i)}hasFragment(t){const i=Fs(t);return!!this.fragments[i]}hasParts(t){var i;return!(null==(i=this.activePartLists[t])||!i.length)}removeFragmentsInRange(t,i,s,e,n){e&&!this.hasGaps||Object.keys(this.fragments).forEach((r=>{const h=this.fragments[r];if(!h)return;const o=h.body;o.type!==s||e&&!o.gap||o.start<i&&o.end>t&&(h.buffered||n)&&this.removeFragment(o)}))}removeFragment(t){const i=Fs(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const i=t.sn;this.activePartLists[t.type]=s.filter((t=>t.fragment.sn!==i))}delete this.fragments[i],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 Us(t){var i,s,e;return t.buffered&&(t.body.gap||(null==(i=t.range.video)?void 0:i.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(e=t.range.audiovideo)?void 0:e.partial))}function Fs(t){return`${t.type}_${t.level}_${t.sn}`}const Bs={length:0,start:()=>0,end:()=>0};class js{static isBuffered(t,i){try{if(t){const s=js.getBuffered(t);for(let t=0;t<s.length;t++)if(i>=s.start(t)&&i<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,i,s){try{if(t){const e=js.getBuffered(t),n=[];let r;for(r=0;r<e.length;r++)n.push({start:e.start(r),end:e.end(r)});return this.bufferedInfo(n,i,s)}}catch(t){}return{len:0,start:i,end:i,nextStart:void 0}}static bufferedInfo(t,i,s){i=Math.max(0,i),t.sort((function(t,i){return t.start-i.start||i.end-t.end}));let e=[];if(s)for(let i=0;i<t.length;i++){const n=e.length;if(n){const r=e[n-1].end;t[i].start-r<s?t[i].end>r&&(e[n-1].end=t[i].end):e.push(t[i])}else e.push(t[i])}else e=t;let n,r=0,h=i,o=i;for(let t=0;t<e.length;t++){const a=e[t].start,l=e[t].end;if(i+s>=a&&i<l)h=a,o=l,r=o-i;else if(i+s<a){n=a;break}}return{len:r,start:h||0,end:o||0,nextStart:n}}static getBuffered(t){try{return t.buffered}catch(t){return I.log("failed to get media.buffered",t),Bs}}}class _s{constructor(t,i,s,e=0,n=-1,r=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=i,this.id=s,this.size=e,this.part=n,this.partial=r}}function Gs(t,i){for(let e=0,n=t.length;e<n;e++){var s;if((null==(s=t[e])?void 0:s.cc)===i)return t[e]}return null}function Hs(t,i){if(t){const s=t.start+i;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Ks(t,i){const s=i.fragments;for(let i=0,e=s.length;i<e;i++)Hs(s[i],t);i.fragmentHint&&Hs(i.fragmentHint,t),i.alignedSliding=!0}function Vs(t,i){if(!t.hasProgramDateTime||!i.hasProgramDateTime)return;const s=t.fragments,e=i.fragments;if(!s.length||!e.length)return;let n,r;const h=Math.min(i.endCC,t.endCC);i.startCC<h&&t.startCC<h&&(n=Gs(e,h),r=Gs(s,h)),n&&r||(n=e[Math.floor(e.length/2)],r=Gs(s,n.cc)||s[Math.floor(s.length/2)]);const o=n.programDateTime,a=r.programDateTime;o&&a&&Ks((a-o)/1e3-(r.start-n.start),t)}const zs=Math.pow(2,17);class Ws{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,i){const s=t.url;if(!s)return Promise.reject(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const e=this.config,n=e.fLoader,r=e.loader;return new Promise(((h,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(qs(t));t.gap=!1}const a=this.loader=t.loader=n?new n(e):new r(e),l=Xs(t),c=fs(e.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:zs};t.stats=a.stats,a.load(l,u,{onSuccess:(i,s,e,n)=>{this.resetLoader(t,a);let r=i.data;e.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(r.slice(0,16)),r=r.slice(16)),h({frag:t,part:null,payload:r,networkDetails:n})},onError:(i,e,n,r)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:k({url:s,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:n,stats:r}))},onAbort:(i,s,e)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:e,stats:i}))},onTimeout:(i,s,e)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:e,stats:i}))},onProgress:(s,e,n,r)=>{i&&i({frag:t,part:null,payload:n,networkDetails:r})}})}))}loadPart(t,i,s){this.abort();const e=this.config,n=e.fLoader,r=e.loader;return new Promise(((h,o)=>{if(this.loader&&this.loader.destroy(),t.gap||i.gap)return void o(qs(t,i));const a=this.loader=t.loader=n?new n(e):new r(e),l=Xs(t,i),c=fs(e.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zs};i.stats=a.stats,a.load(l,u,{onSuccess:(e,n,r,o)=>{this.resetLoader(t,a),this.updateStatsFromPart(t,i);const l={frag:t,part:i,payload:e.data,networkDetails:o};s(l),h(l)},onError:(s,e,n,r)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:i,response:k({url:l.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:n,stats:r}))},onAbort:(s,e,n)=>{t.stats.aborted=i.stats.aborted,this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:t,part:i,error:new Error("Aborted"),networkDetails:n,stats:s}))},onTimeout:(s,e,n)=>{this.resetLoader(t,a),o(new Ys({type:M.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:i,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:n,stats:s}))}})}))}updateStatsFromPart(t,i){const s=t.stats,e=i.stats,n=e.total;if(s.loaded+=e.loaded,n){const e=Math.round(t.duration/i.duration),r=Math.min(Math.round(s.loaded/n),e),h=(e-r)*Math.round(s.loaded/r);s.total=s.loaded+h}else s.total=Math.max(s.loaded,s.total);const r=s.loading,h=e.loading;r.start?r.first+=h.first-h.start:(r.start=h.start,r.first=h.first),r.end=h.end}resetLoader(t,i){t.loader=null,this.loader===i&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),i.destroy()}}function Xs(t,i=null){const s=i||t,e={frag:t,part:i,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=s.byteRangeStartOffset,r=s.byteRangeEndOffset;if(T(n)&&T(r)){var h;let i=n,s=r;if("initSegment"===t.sn&&"AES-128"===(null==(h=t.decryptdata)?void 0:h.method)){const t=r-n;t%16&&(s=r+(16-t%16)),0!==n&&(e.resetIV=!0,i=n-16)}e.rangeStart=i,e.rangeEnd=s}return e}function qs(t,i){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),e={type:M.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return i&&(e.part=i),(i||t).stats.aborted=!0,new Ys(e)}class Ys extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Js{constructor(t,i){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=i}decrypt(t,i){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},i,t)}}class Qs{constructor(t,i){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=i}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Zs{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 i=new DataView(t),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=i.getUint32(4*t);return s}initTable(){const t=this.sBox,i=this.invSBox,s=this.subMix,e=s[0],n=s[1],r=s[2],h=s[3],o=this.invSubMix,a=o[0],l=o[1],c=o[2],u=o[3],d=new Uint32Array(256);let f=0,v=0,p=0;for(p=0;p<256;p++)d[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let s=v^v<<1^v<<2^v<<3^v<<4;s=s>>>8^255&s^99,t[f]=s,i[s]=f;const o=d[f],p=d[o],g=d[p];let m=257*d[s]^16843008*s;e[f]=m<<24|m>>>8,n[f]=m<<16|m>>>16,r[f]=m<<8|m>>>24,h[f]=m,m=16843009*g^65537*p^257*o^16843008*f,a[s]=m<<24|m>>>8,l[s]=m<<16|m>>>16,c[s]=m<<8|m>>>24,u[s]=m,f?(f=o^d[d[d[g^o]]],v^=d[d[v]]):f=v=1}}expandKey(t){const i=this.uint8ArrayToUint32Array_(t);let s=!0,e=0;for(;e<i.length&&s;)s=i[e]===this.key[e],e++;if(s)return;this.key=i;const n=this.keySize=i.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);const r=this.ksRows=4*(n+6+1);let h,o;const a=this.keySchedule=new Uint32Array(r),l=this.invKeySchedule=new Uint32Array(r),c=this.sBox,u=this.rcon,d=this.invSubMix,f=d[0],v=d[1],p=d[2],g=d[3];let m,y;for(h=0;h<r;h++)h<n?m=a[h]=i[h]:(y=m,h%n==0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=u[h/n|0]<<24):n>6&&h%n==4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),a[h]=m=(a[h-n]^y)>>>0);for(o=0;o<r;o++)h=r-o,y=3&o?a[h]:a[h-4],l[o]=o<4||h<=4?y:f[c[y>>>24]]^v[c[y>>>16&255]]^p[c[y>>>8&255]]^g[c[255&y]],l[o]=l[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,i,s){const e=this.keySize+6,n=this.invKeySchedule,r=this.invSBox,h=this.invSubMix,o=h[0],a=h[1],l=h[2],c=h[3],u=this.uint8ArrayToUint32Array_(s);let d=u[0],f=u[1],v=u[2],p=u[3];const g=new Int32Array(t),m=new Int32Array(g.length);let y,w,b,k,S,T,$,E,A,M,L,x,D,C;const I=this.networkToHostOrderSwap;for(;i<g.length;){for(A=I(g[i]),M=I(g[i+1]),L=I(g[i+2]),x=I(g[i+3]),S=A^n[0],T=x^n[1],$=L^n[2],E=M^n[3],D=4,C=1;C<e;C++)y=o[S>>>24]^a[T>>16&255]^l[$>>8&255]^c[255&E]^n[D],w=o[T>>>24]^a[$>>16&255]^l[E>>8&255]^c[255&S]^n[D+1],b=o[$>>>24]^a[E>>16&255]^l[S>>8&255]^c[255&T]^n[D+2],k=o[E>>>24]^a[S>>16&255]^l[T>>8&255]^c[255&$]^n[D+3],S=y,T=w,$=b,E=k,D+=4;y=r[S>>>24]<<24^r[T>>16&255]<<16^r[$>>8&255]<<8^r[255&E]^n[D],w=r[T>>>24]<<24^r[$>>16&255]<<16^r[E>>8&255]<<8^r[255&S]^n[D+1],b=r[$>>>24]<<24^r[E>>16&255]<<16^r[S>>8&255]<<8^r[255&T]^n[D+2],k=r[E>>>24]<<24^r[S>>16&255]<<16^r[T>>8&255]<<8^r[255&$]^n[D+3],m[i]=I(y^d),m[i+1]=I(k^f),m[i+2]=I(b^v),m[i+3]=I(w^p),d=A,f=M,v=L,p=x,i+=4}return m.buffer}}class te{constructor(t,{removePKCS7Padding:i=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=i,i)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:i}=this;if(!t||i)return this.reset(),null;const s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const i=t.byteLength,s=i&&new DataView(t.buffer).getUint8(i-1);return s?ot(t,0,i-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,i,s){return this.useSoftware?new Promise(((e,n)=>{this.softwareDecrypt(new Uint8Array(t),i,s);const r=this.flush();r?e(r.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),i,s)}softwareDecrypt(t,i,s){const{currentIV:e,currentResult:n,remainderData:r}=this;this.logOnce("JS AES decrypt"),r&&(t=Kt(r,t),this.remainderData=null);const h=this.getValidChunk(t);if(!h.length)return null;e&&(s=e);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new Zs),o.expandKey(i);const a=n;return this.currentResult=o.decrypt(h.buffer,0,s),this.currentIV=ot(h,-16).buffer,a||null}webCryptoDecrypt(t,i,s){if(this.key!==i||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,i,s));this.key=i,this.fastAesKey=new Qs(this.subtle,i)}return this.fastAesKey.expandKey().then((i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Js(this.subtle,new Uint8Array(s)).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized")))).catch((e=>(I.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${e.name}: ${e.message}`),this.onWebCryptoError(t,i,s))))}onWebCryptoError(t,i,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,i,s);const e=this.flush();if(e)return e.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let i=t;const s=t.length-t.length%16;return s!==t.length&&(i=ot(t,0,s),this.remainderData=ot(t,s)),i}logOnce(t){this.logEnabled&&(I.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ie="STOPPED",se="IDLE",ee="KEY_LOADING",ne="FRAG_LOADING",re="FRAG_LOADING_WAITING_RETRY",he="WAITING_TRACK",oe="PARSING",ae="PARSED",le="ENDED",ce="ERROR",ue="WAITING_INIT_PTS",de="WAITING_LEVEL";class fe extends Cs{constructor(t,i,s,e,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ie,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=e,this.log=I.log.bind(I,`${e}:`),this.warn=I.warn.bind(I,`${e}:`),this.hls=t,this.fragmentLoader=new Ws(t.config),this.keyLoader=s,this.fragmentTracker=i,this.config=t.config,this.decrypter=new te(t.config),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ie}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}_streamEnded(t,i){if(i.live||t.nextStart||!t.end||!this.media)return!1;const s=i.partList;if(null!=s&&s.length){const t=s[s.length-1];return js.isBuffered(this.media,t.start+t.duration/2)}return this.fragmentTracker.isEndListAppended(i.fragments[i.fragments.length-1].type)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,i){const s=this.media=this.mediaBuffer=i.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const e=this.config;this.levels&&e.autoStartLoad&&this.state===ie&&this.startLoad(e.startPosition)}onMediaDetaching(){const t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:i,media:s,mediaBuffer:e,state:n}=this,r=s?s.currentTime:0,h=js.bufferInfo(e||s,r,t.maxBufferHole);if(this.log(`media seeking to ${T(r)?r.toFixed(3):r}, state: ${n}`),this.state===le)this.resetLoadingState();else if(i){const s=t.maxFragLookUpTolerance,e=i.start-s,n=i.start+i.duration+s;if(!h.len||n<h.start||e>h.end){const t=r>n;(r<e||t)&&(t&&i.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),i.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,this.playlistType,!0),this.lastCurrentTime=r),this.loadedmetadata||h.len||(this.nextLoadPosition=this.startPosition=r),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,i){this.startTimeOffset=i.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=ie,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,i,s){this._loadFragForPlayback(t,i,s)}_loadFragForPlayback(t,i,s){this._doFragLoad(t,i,s,(i=>{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${i.part?" p: "+i.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(i)})).then((i=>{if(!i)return;const s=this.state;this.fragContextChanged(t)?(s===ne||!this.fragCurrent&&s===oe)&&(this.fragmentTracker.removeFragment(t),this.state=se):("payload"in i&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(A.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i))})).catch((i=>{this.state!==ie&&this.state!==ce&&(this.warn(`Frag error: ${(null==i?void 0:i.message)||i}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var i;const{fragmentTracker:s}=this;if(s.getState(t)===Rs){const i=this.getFwdBufferInfo(this.mediaBuffer,t.type),e=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1==(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(e,t.duration))&&s.removeFragment(t)}else 0===(null==(i=this.mediaBuffer)?void 0:i.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===Ps&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const i=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,i,s=null){t-i&&this.hls.trigger(A.BUFFER_FLUSHING,{startOffset:t,endOffset:i,type:s})}_loadInitSegment(t,i){this._doFragLoad(t,i).then((i=>{if(!i||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return i})).then((i=>{const{hls:s}=this,{payload:e}=i,n=t.decryptdata;if(e&&e.byteLength>0&&null!=n&&n.key&&n.iv&&"AES-128"===n.method){const r=self.performance.now();return this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer).catch((i=>{throw s.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:i,reason:i.message,frag:t}),i})).then((e=>{const n=self.performance.now();return s.trigger(A.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:r,tdecrypt:n}}),i.payload=e,this.completeInitSegmentLoad(i)}))}return this.completeInitSegmentLoad(i)})).catch((i=>{this.state!==ie&&this.state!==ce&&(this.warn(i),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:i}=this;if(!i)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=se,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:i}=this;return!t||!i||t.sn!==i.sn||t.level!==i.level}fragBufferedComplete(t,i){var s,e,n,r;const h=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${i?" part: "+i.index:""} of ${this.playlistType===Ii?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(e=t.endPTS)?e:NaN).toFixed(3)}] > buffer:${h?function(t){let i="";const s=t.length;for(let e=0;e<s;e++)i+=`[${t.start(e).toFixed(3)}-${t.end(e).toFixed(3)}]`;return i}(js.getBuffered(h)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==Pi){const i=t.elementaryStreams;if(!Object.keys(i).some((t=>!!i[t])))return void(this.state=se)}const i=null==(o=this.levels)?void 0:o[t.level];null!=i&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=se,h&&(!this.loadedmetadata&&t.type==Ii&&h.buffered.length&&(null==(n=this.fragCurrent)?void 0:n.sn)===(null==(r=this.fragPrevious)?void 0:r.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:i}=this;if(!i)return;const{frag:s,part:e,partsLoaded:n}=t,r=!n||0===n.length||n.some((t=>!t)),h=new _s(s.level,s.sn,s.stats.chunkCount+1,0,e?e.index:-1,!r);i.flush(h)}_handleFragmentLoadProgress(t){}_doFragLoad(t,i,s=null,e){var n;const r=null==i?void 0:i.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);let h=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key?!t.encrypted&&r.encryptedFragments.length&&this.keyLoader.loadClear(t,r.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${r.startSN}-${r.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=ee,this.fragCurrent=t,h=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(A.KEY_LOADED,t),this.state===ee&&(this.state=se),t})),this.hls.trigger(A.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(h=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 n=r.partList;if(n&&e){s>t.end&&r.fragmentHint&&(t=r.fragmentHint);const o=this.getNextPart(n,t,s);if(o>-1){const a=n[o];let l;return this.log(`Loading part sn: ${t.sn} p: ${a.index} cc: ${t.cc} of playlist [${r.startSN}-${r.endSN}] parts [0-${o}-${n.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=a.start+a.duration,this.state=ne,l=h?h.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,a,i,e))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,a,i,e).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(A.FRAG_LOADING,{frag:t,part:a,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):l}if(!t.url||this.loadedEndOfParts(n,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${r?"of ["+r.startSN+"-"+r.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),T(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ne;const o=this.config.progressive;let a;return a=o&&h?h.then((i=>!i||this.fragContextChanged(null==i?void 0:i.frag)?null:this.fragmentLoader.load(t,e))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?e:void 0),h]).then((([t])=>(!o&&t&&e&&e(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(A.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):a}doFragPartsLoad(t,i,s,e){return new Promise(((n,r)=>{var h;const o=[],a=null==(h=s.details)?void 0:h.partList,l=i=>{this.fragmentLoader.loadPart(t,i,e).then((e=>{o[i.index]=e;const r=e.part;this.hls.trigger(A.FRAG_LOADED,e);const h=os(s,t.sn,i.index+1)||as(a,t.sn,i.index+1);if(!h)return n({frag:t,part:r,partsLoaded:o});l(h)})).catch(r)};l(i)}))}handleFragLoadError(t){if("data"in t){const i=t.data;t.data&&i.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(i.frag,i.part):this.hls.trigger(A.ERROR,i)}else this.hls.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const i=this.getCurrentContext(t);if(!i||this.state!==oe)return void(this.fragCurrent||this.state===ie||this.state===ce||(this.state=se));const{frag:s,part:e,level:n}=i,r=self.performance.now();s.stats.parsing.end=r,e&&(e.stats.parsing.end=r),this.updateLevelTiming(s,e,n,t.partial)}getCurrentContext(t){const{levels:i,fragCurrent:s}=this,{level:e,sn:n,part:r}=t;if(null==i||!i[e])return this.warn(`Levels object was unset while buffering fragment ${n} of level ${e}. The current chunk will not be buffered.`),null;const h=i[e],o=r>-1?os(h,n,r):null,a=o?o.fragment:function(t,i,s){if(null==t||!t.details)return null;const e=t.details;let n=e.fragments[i-e.startSN];return n||(n=e.fragmentHint,n&&n.sn===i?n:i<e.startSN&&s&&s.sn===i?s:null)}(h,n,s);return a?(s&&s!==a&&(a.stats=s.stats),{frag:a,part:o,level:h}):null}bufferFragmentData(t,i,s,e,n){var r;if(!t||this.state!==oe)return;const{data1:h,data2:o}=t;let a=h;if(h&&o&&(a=Kt(h,o)),null!=(r=a)&&r.length&&(this.hls.trigger(A.BUFFER_APPENDING,{type:t.type,frag:i,part:s,chunkMeta:e,parent:i.type,data:a}),t.dropped&&t.independent&&!s)){if(n)return;this.flushBufferGap(i)}}flushBufferGap(t){const i=this.media;if(!i)return;if(!js.isBuffered(i,i.currentTime))return void this.flushMainBuffer(0,t.start);const s=i.currentTime,e=js.bufferInfo(i,s,0),n=Math.min(2*this.config.maxFragLookUpTolerance,.25*t.duration),r=Math.max(Math.min(t.start-n,e.end-n),s+n);t.start-r>n&&this.flushMainBuffer(r,t.start)}getFwdBufferInfo(t,i){const s=this.getLoadPosition();return T(s)?this.getFwdBufferInfoAtPos(t,s,i):null}getFwdBufferInfoAtPos(t,i,s){const{config:{maxBufferHole:e}}=this,n=js.bufferInfo(t,i,e);if(0===n.len&&void 0!==n.nextStart){const r=this.fragmentTracker.getBufferedFrag(i,s);if(r&&n.nextStart<r.end)return js.bufferInfo(t,i,Math.max(n.nextStart,e))}return n}getMaxBufferLength(t){const{config:i}=this;let s;return s=t?Math.max(8*i.maxBufferSize/t,i.maxBufferLength):i.maxBufferLength,Math.min(s,i.maxMaxBufferLength)}reduceMaxBufferLength(t,i){const s=this.config,e=Math.max(Math.min(t-i,s.maxBufferLength),i),n=Math.max(t-3*i,s.maxMaxBufferLength/2,e);return n>=e&&(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0)}getAppendedFrag(t,i=Ii){const s=this.fragmentTracker.getAppendedFrag(t,Ii);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,i){const s=i.fragments,e=s.length;if(!e)return null;const{config:n}=this,r=s[0].start;let h;if(i.live){const o=n.initialLiveManifestSize;if(e<o)return this.warn(`Not enough fragments to start playback (have: ${e}, need: ${o})`),null;(!i.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<r)&&(h=this.getInitialLiveFragment(i,s),this.startPosition=this.nextLoadPosition=h?this.hls.liveSyncPosition||h.start:t)}else t<=r&&(h=s[0]);return h||(h=this.getFragmentAtPosition(t,n.lowLatencyMode?i.partEnd:i.fragmentEnd,i)),this.mapToInitFragWhenRequired(h)}isLoopLoading(t,i){const s=this.fragmentTracker.getState(t);return(s===Os||s===Ps&&!!t.gap)&&this.nextLoadPosition>i}getNextFragmentLoopLoading(t,i,s,e,n){const r=t.gap,h=this.getNextFragment(this.nextLoadPosition,i);if(null===h)return h;if(t=h,r&&t&&!t.gap&&s.nextStart){const i=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,e);if(null!==i&&s.len+i.len>=n)return this.log(`buffer full after gaps in "${e}" 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,i,s){let e=-1,n=!1,r=!0;for(let h=0,o=t.length;h<o;h++){const o=t[h];if(r=r&&!o.independent,e>-1&&s<o.start)break;const a=o.loaded;a?e=-1:(n||o.independent||r)&&o.fragment===i&&(e=h),n=a}return e}loadedEndOfParts(t,i){const s=t[t.length-1];return s&&i>s.start&&s.loaded}getInitialLiveFragment(t,i){const s=this.fragPrevious;let e=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),e=function(t,i,s){if(null===i||!Array.isArray(t)||!t.length||!T(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let e=0;e<t.length;++e){const n=t[e];if(ys(i,s,n))return n}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!e){const n=s.sn+1;if(n>=t.startSN&&n<=t.endSN){const r=i[n-t.startSN];s.cc===r.cc&&(e=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${e.sn}`))}e||(e=function(t,i){return ps(t,(t=>t.cc<i?1:t.cc>i?-1:0))}(i,s.cc),e&&this.log(`Live playlist, switching playlist, load frag with same CC: ${e.sn}`))}}else{const i=this.hls.liveSyncPosition;null!==i&&(e=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return e}getFragmentAtPosition(t,i,s){const{config:e}=this;let{fragPrevious:n}=this,{fragments:r,endSN:h}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:a}=e,l=s.partList,c=!!(e.lowLatencyMode&&null!=l&&l.length&&o);let u;if(c&&o&&!this.bitrateTest&&(r=r.concat(o),h=o.sn),u=t<i?gs(n,r,t,t>i-a?0:a):r[r.length-1],u){const t=u.sn-s.startSN,i=this.fragmentTracker.getState(u);if((i===Os||i===Ps&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!c||l[0].fragment.sn>u.sn)&&n&&u.level===n.level){const i=r[t+1];u=u.sn<h&&this.fragmentTracker.getState(i)!==Os?i:null}}return u}synchronizeToLiveEdge(t){const{config:i,media:s}=this;if(!s)return;const e=this.hls.liveSyncPosition,n=s.currentTime,r=t.edge,h=n>=t.fragments[0].start-i.maxFragLookUpTolerance&&n<=r;null!==e&&s.duration>e&&(n<e||!h)&&(!h&&s.readyState<4||n<r-(void 0!==i.liveMaxLatencyDuration?i.liveMaxLatencyDuration:i.liveMaxLatencyDurationCount*t.targetduration))&&(this.loadedmetadata||(this.nextLoadPosition=e),s.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${r}, reset currentTime to : ${e.toFixed(3)}`),s.currentTime=e))}alignPlaylists(t,i,s){const e=t.fragments.length;if(!e)return this.warn("No fragments in live playlist"),0;const n=t.fragments[0].start,r=!i,h=t.alignedSliding&&T(n);if(r||!h&&!n){const{fragPrevious:n}=this;!function(t,i,s){i&&(function(t,i,s){if(function(t,i,s){return!(!i||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,i)){const t=function(t,i){const s=t.fragments,e=i.fragments;if(!e.length||!s.length)return void I.log("No fragments to align");const n=Gs(s,e[0].cc);if(n&&(!n||n.startPTS))return n;I.log("No frag in previous level to align on")}(s,i);t&&T(t.start)&&(I.log(`Adjusting PTS using last level due to CC increase within current level ${i.url}`),Ks(t.start,i))}}(t,s,i),!s.alignedSliding&&i&&Vs(s,i),s.alignedSliding||!i||s.skippedSegments||rs(i,s))}(n,s,t);const r=t.fragments[0].start;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${i?i.startSN:"na"}->${t.startSN} prev-sn: ${n?n.sn:"na"} fragments: ${e}`),r}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,i){let s=this.startPosition;if(s<i&&(s=-1),-1===s||-1===this.lastCurrentTime){const e=null!==this.startTimeOffset,n=e?this.startTimeOffset:t.startTimeOffset;null!==n&&T(n)?(s=i+n,n<0&&(s+=t.totalduration),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Start time offset ${n} found in ${e?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||i:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:t}=this;let i=0;return this.loadedmetadata&&t?i=t.currentTime:this.nextLoadPosition&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,i){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===re)||(this.state=se)}onFragmentOrKeyLoadError(t,i){if(i.chunkMeta&&!i.frag){const t=this.getCurrentContext(i.chunkMeta);t&&(i.frag=t.frag)}const s=i.frag;if(!s||s.type!==t||!this.levels)return;var e;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(e=this.fragCurrent)?void 0:e.url}`);const n=i.details===L.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const r=i.errorAction,{action:h,retryCount:o=0,retryConfig:a}=r||{};if(r&&5===h&&a){this.resetStartWhenNotLoaded(this.levelLastLoaded);const e=ds(a,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${i.details}, retrying loading ${o+1}/${a.maxNumRetry} in ${e}ms`),r.resolved=!0,this.retryDate=self.performance.now()+e,this.state=re}else if(a&&r){if(this.resetFragmentErrors(t),!(o<a.maxNumRetry))return void I.warn(`${i.details} reached or exceeded max retry (${o})`);n||3===h||(r.resolved=!0)}else this.state=2===(null==r?void 0:r.action)?de:ce;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===oe||this.state===ae){const i=t.frag,s=t.parent,e=this.getFwdBufferInfo(this.mediaBuffer,s),n=e&&e.len>.5;n&&this.reduceMaxBufferLength(e.len,(null==i?void 0:i.duration)||10);const r=!n;return r&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),i&&(this.fragmentTracker.removeFragment(i),this.nextLoadPosition=i.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(t){t===Ri&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ie&&(this.state=se)}afterBufferFlushed(t,i,s){if(!t)return;const e=js.getBuffered(t);this.fragmentTracker.detectEvictedFragments(i,e,s),this.state===le&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=se}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const i=t?t.details:null;null!=i&&i.live?(this.startPosition=-1,this.setStartPosition(i,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,i,s,e){var n;const r=s.details;if(r){if(!Object.keys(t.elementaryStreams).reduce(((i,n)=>{const h=t.elementaryStreams[n];if(h){const o=h.endPTS-h.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),i||!1;const a=e?0:ns(r,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(A.LEVEL_PTS_UPDATED,{details:r,level:s,drift:a,type:n,frag:t,start:h.startPTS,end:h.endPTS}),!0}return i}),!1)&&null===(null==(n=this.transmuxer)?void 0:n.error)){const i=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(i.message),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=ae,this.hls.trigger(A.FRAG_PARSED,{frag:t,part:i})}else this.warn("level.details undefined")}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 i=this._state;i!==t&&(this._state=t,this.log(`${i}->${t}`))}get state(){return this._state}}class ve{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:i}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,i){const s=new Uint8Array(i);let e=0;for(let i=0;i<t.length;i++){const n=t[i];s.set(n,e),e+=n.length}return s}(t,i),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function pe(t="",i=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:i,sequenceNumber:-1,samples:[],dropped:0}}class ge{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,i,s,e){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,i){return!1}appendFrame(t,i,s){}demux(t,i){this.cachedData&&(t=Kt(this.cachedData,t),this.cachedData=null);let s,e=ct(t,0),n=e?e.length:0;const r=this._audioTrack,h=this._id3Track,o=e?ft(e):void 0,a=t.length;for((null===this.basePTS||0===this.frameIndex&&T(o))&&(this.basePTS=me(o,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),e&&e.length>0&&h.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:e,type:Hi,duration:Number.POSITIVE_INFINITY});n<a;){if(this.canParse(t,n)){const i=this.appendFrame(r,t,n);i?(this.frameIndex++,this.lastPTS=i.sample.pts,n+=i.length,s=n):n=a}else dt(t,n)?(e=ct(t,n),h.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:e,type:Hi,duration:Number.POSITIVE_INFINITY}),n+=e.length,s=n):n++;if(n===a&&s!==a){const i=ot(t,s);this.cachedData=this.cachedData?Kt(this.cachedData,i):i}}return{audioTrack:r,videoTrack:pe(),id3Track:h,textTrack:pe()}}demuxSampleAes(t,i,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const i=this.cachedData;return i&&(this.cachedData=null,this.demux(i,0)),{audioTrack:this._audioTrack,videoTrack:pe(),id3Track:this._id3Track,textTrack:pe()}}destroy(){}}const me=(t,i,s)=>T(t)?90*t:9e4*i+(s?9e4*s.baseTime/s.timescale:0);function ye(t,i){return 255===t[i]&&240==(246&t[i+1])}function we(t,i){return 1&t[i+1]?7:9}function be(t,i){return(3&t[i+3])<<11|t[i+4]<<3|(224&t[i+5])>>>5}function ke(t,i){return i+1<t.length&&ye(t,i)}function Se(t,i){if(ke(t,i)){const s=we(t,i);if(i+s>=t.length)return!1;const e=be(t,i);if(e<=s)return!1;const n=i+e;return n===t.length||ke(t,n)}return!1}function Te(t,i,s,e,n){if(!t.samplerate){const r=function(t,i,s,e){let n,r,h,o;const a=navigator.userAgent.toLowerCase(),l=e,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=1+((192&i[s+2])>>>6);const u=(60&i[s+2])>>>2;if(!(u>c.length-1))return h=(1&i[s+2])<<2,h|=(192&i[s+3])>>>6,I.log(`manifest codec:${e}, ADTS type:${n}, samplingIndex:${u}`),/firefox/i.test(a)?u>=6?(n=5,o=new Array(4),r=u-3):(n=2,o=new Array(2),r=u):-1!==a.indexOf("android")?(n=2,o=new Array(2),r=u):(n=5,o=new Array(4),e&&(-1!==e.indexOf("mp4a.40.29")||-1!==e.indexOf("mp4a.40.5"))||!e&&u>=6?r=u-3:((e&&-1!==e.indexOf("mp4a.40.2")&&(u>=6&&1===h||/vivaldi/i.test(a))||!e&&1===h)&&(n=2,o=new Array(2)),r=u)),o[0]=n<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=h<<3,5===n&&(o[1]|=(14&r)>>1,o[2]=(1&r)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[u],channelCount:h,codec:"mp4a.40."+n,manifestCodec:l};{const i=new Error(`invalid ADTS sampling index:${u}`);t.emit(A.ERROR,A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:i,reason:i.message})}}(i,s,e,n);if(!r)return;t.config=r.config,t.samplerate=r.samplerate,t.channelCount=r.channelCount,t.codec=r.codec,t.manifestCodec=r.manifestCodec,I.log(`parsed codec:${t.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function $e(t){return 9216e4/t}function Ee(t,i,s,e,n){const r=e+n*$e(t.samplerate),h=function(t,i){const s=we(t,i);if(i+s<=t.length){const e=be(t,i)-s;if(e>0)return{headerLength:s,frameLength:e}}}(i,s);let o;if(h){const{frameLength:e,headerLength:n}=h,a=n+e,l=Math.max(0,s+a-i.length);l?(o=new Uint8Array(a-n),o.set(i.subarray(s+n,i.length),0)):o=i.subarray(s+n,s+a);const c={unit:o,pts:r};return l||t.samples.push(c),{sample:c,length:a,missing:l}}const a=i.length-s;return o=new Uint8Array(a),o.set(i.subarray(s,i.length),0),{sample:{unit:o,pts:r},length:a,missing:-1}}let Ae=null;const Me=[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],Le=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],xe=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],De=[0,1,1,4];function Ce(t,i,s,e,n){if(s+24>i.length)return;const r=Ie(i,s);if(r&&s+r.frameLength<=i.length){const h=e+n*(9e4*r.samplesPerFrame/r.sampleRate),o={unit:i.subarray(s,s+r.frameLength),pts:h,dts:h};return t.config=[],t.channelCount=r.channelCount,t.samplerate=r.sampleRate,t.samples.push(o),{sample:o,length:r.frameLength,missing:0}}}function Ie(t,i){const s=t[i+1]>>3&3,e=t[i+1]>>1&3,n=t[i+2]>>4&15,r=t[i+2]>>2&3;if(1!==s&&0!==n&&15!==n&&3!==r){const h=t[i+3]>>6,o=1e3*Me[14*(3===s?3-e:3===e?3:4)+n-1],a=Le[3*(3===s?0:2===s?1:2)+r],l=3===h?1:2,c=xe[s][e],u=De[e],d=8*c*u,f=Math.floor(c*o/a+(t[i+2]>>1&1))*u;if(null===Ae){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ae=t?parseInt(t[1]):0}return!!Ae&&Ae<=87&&2===e&&o>=224e3&&0===h&&(t[i+3]=128|t[i+3]),{sampleRate:a,channelCount:l,frameLength:f,samplesPerFrame:d}}}function Re(t,i){return!(255!==t[i]||224&~t[i+1]||!(6&t[i+1]))}function Pe(t,i){return i+1<t.length&&Re(t,i)}function Oe(t,i){if(i+1<t.length&&Re(t,i)){const s=4,e=Ie(t,i);let n=s;null!=e&&e.frameLength&&(n=e.frameLength);const r=i+n;return r===t.length||Pe(t,r)}return!1}const Ne=/\/emsg[-/]ID3/i,Ue=(t,i)=>{let s=0,e=5;i+=e;const n=new Uint32Array(1),r=new Uint32Array(1),h=new Uint8Array(1);for(;e>0;){h[0]=t[i];const o=Math.min(e,8),a=8-o;r[0]=4278190080>>>24+a<<a,n[0]=(h[0]&r[0])>>a,s=s?s<<o|n[0]:n[0],i+=1,e-=o}return s};function Fe(t,i,s,e,n){if(s+8>i.length)return-1;if(11!==i[s]||119!==i[s+1])return-1;const r=i[s+4]>>6;if(r>=3)return-1;const h=[48e3,44100,32e3][r],o=63&i[s+4],a=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+r];if(s+a>i.length)return-1;const l=i[s+6]>>5;let c=0;2===l?c+=2:(1&l&&1!==l&&(c+=2),4&l&&(c+=2));const u=(i[s+6]<<8|i[s+7])>>12-c&1,d=[2,1,2,3,3,4,4,5][l]+u,f=7&i[s+5],v=new Uint8Array([r<<6|i[s+5]>>3<<1|f>>2,(3&f)<<6|l<<3|u<<2|o>>4,o<<4&224]),p=e+n*(1536/h*9e4),g=i.subarray(s,s+a);return t.config=v,t.channelCount=d,t.samplerate=h,t.samples.push({unit:g,pts:p}),a}class Be{constructor(){this.VideoSample=null}createVideoSample(t,i,s,e){return{key:t,frame:!1,pts:i,dts:s,units:[],debug:e,length:0}}getLastNalUnit(t){var i;let s,e=this.VideoSample;if(e&&0!==e.units.length||(e=t[t.length-1]),null!=(i=e)&&i.units){const t=e.units;s=t[t.length-1]}return s}pushAccessUnit(t,i){if(t.units.length&&t.frame){if(void 0===t.pts){const s=i.samples,e=s.length;if(!e)return void i.dropped++;{const i=s[e-1];t.pts=i.pts,t.dts=i.dts}}i.samples.push(t)}t.debug.length&&I.log(t.pts+"/"+t.dts+":"+t.debug)}}class je{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,i=this.bytesAvailable,s=t.byteLength-i,e=new Uint8Array(4),n=Math.min(4,i);if(0===n)throw new Error("no bytes available");e.set(t.subarray(s,s+n)),this.word=new DataView(e.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}skipBits(t){let i;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(i=(t-=this.bitsAvailable)>>3,t-=i<<3,this.bytesAvailable-=i,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let i=Math.min(this.bitsAvailable,t);const s=this.word>>>32-i;if(t>32&&I.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=i,this.bitsAvailable>0)this.word<<=i;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return i=t-i,i>0&&this.bitsAvailable?s<<i|this.readBits(i):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>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 i,s=8,e=8;for(let n=0;n<t;n++)0!==e&&(i=this.readEG(),e=(s+i+256)%256),s=0===e?s:e}readSPS(){let t,i,s,e=0,n=0,r=0,h=0;const o=this.readUByte.bind(this),a=this.readBits.bind(this),l=this.readUEG.bind(this),c=this.readBoolean.bind(this),u=this.skipBits.bind(this),d=this.skipEG.bind(this),f=this.skipUEG.bind(this),v=this.skipScalingList.bind(this);o();const p=o();if(a(5),u(3),o(),f(),100===p||110===p||122===p||244===p||44===p||83===p||86===p||118===p||128===p){const t=l();if(3===t&&u(1),f(),f(),u(1),c())for(i=3!==t?8:12,s=0;s<i;s++)c()&&v(s<6?16:64)}f();const g=l();if(0===g)l();else if(1===g)for(u(1),d(),d(),t=l(),s=0;s<t;s++)d();f(),u(1);const m=l(),y=l(),w=a(1);0===w&&u(1),u(1),c()&&(e=l(),n=l(),r=l(),h=l());let b=[1,1];if(c()&&c())switch(o()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[o()<<8|o(),o()<<8|o()]}return{width:Math.ceil(16*(m+1)-2*e-2*n),height:(2-w)*(y+1)*16-(w?2:4)*(r+h),pixelRatio:b}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class _e extends Be{parseAVCPES(t,i,s,e,n){const r=this.parseAVCNALu(t,s.data);let h,o=this.VideoSample,a=!1;s.data=null,o&&r.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),r.forEach((e=>{var r;switch(e.type){case 1:{let i=!1;h=!0;const n=e.data;if(a&&n.length>4){const t=new je(n).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(i=!0)}var l;i&&null!=(l=o)&&l.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=i;break}case 5:h=!0,null!=(r=o)&&r.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:h=!0,Wt(e.data,1,s.pts,i.samples);break;case 7:{var c,u;h=!0,a=!0;const i=e.data,s=new je(i).readSPS();if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(c=t.pixelRatio)?void 0:c[0])!==s.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[i],t.duration=n;const e=i.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let i=e[t].toString(16);i.length<2&&(i="0"+i),r+=i}t.codec=r}break}case 8:h=!0,t.pps=[e.data];break;case 9:h=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:h=!0;break;default:h=!1,o&&(o.debug+="unknown NAL "+e.type+" ")}o&&h&&o.units.push(e)})),e&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,i){const s=i.byteLength;let e=t.naluState||0;const n=e,r=[];let h,o,a,l=0,c=-1,u=0;for(-1===e&&(c=0,u=31&i[0],e=0,l=1);l<s;)if(h=i[l++],e)if(1!==e)if(h)if(1===h){if(o=l-e-1,c>=0){const t={data:i.subarray(c,o),type:u};r.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(n&&l<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),o>0&&(s.data=Kt(s.data,i.subarray(0,o)),s.state=0))}l<s?(a=31&i[l],c=l,u=a,e=0):e=-1}else e=0;else e=3;else e=h?0:2;else e=h?0:1;if(c>=0&&e>=0){const t={data:i.subarray(c,s),type:u,state:e};r.push(t)}if(0===r.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Kt(s.data,i))}return t.naluState=e,r}}class Ge{constructor(t,i,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new te(i,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,i,s){const e=t[i].unit;if(e.length<=16)return;const n=e.subarray(16,e.length-e.length%16),r=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(r).then((n=>{const r=new Uint8Array(n);e.set(r,16),this.decrypter.isSync()||this.decryptAacSamples(t,i+1,s)}))}decryptAacSamples(t,i,s){for(;;i++){if(i>=t.length)return void s();if(!(t[i].unit.length<32||(this.decryptAacSample(t,i,s),this.decrypter.isSync())))return}}getAvcEncryptedData(t){const i=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(i);let e=0;for(let i=32;i<t.length-16;i+=160,e+=16)s.set(t.subarray(i,i+16),e);return s}getAvcDecryptedUnit(t,i){const s=new Uint8Array(i);let e=0;for(let i=32;i<t.length-16;i+=160,e+=16)t.set(s.subarray(e,e+16),i);return t}decryptAvcSample(t,i,s,e,n){const r=Xt(n.data),h=this.getAvcEncryptedData(r);this.decryptBuffer(h.buffer).then((h=>{n.data=this.getAvcDecryptedUnit(r,h),this.decrypter.isSync()||this.decryptAvcSamples(t,i,s+1,e)}))}decryptAvcSamples(t,i,s,e){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;i++,s=0){if(i>=t.length)return void e();const n=t[i].units;for(;!(s>=n.length);s++){const r=n[s];if(!(r.data.length<=48||1!==r.type&&5!==r.type||(this.decryptAvcSample(t,i,s,e,r),this.decrypter.isSync())))return}}}}const He=188;class Ke{constructor(t,i,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=i,this.typeSupported=s,this.videoParser=new _e}static probe(t){const i=Ke.syncOffset(t);return i>0&&I.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const i=t.length;let s=Math.min(940,i-He)+1,e=0;for(;e<s;){let n=!1,r=-1,h=0;for(let o=e;o<i;o+=He){if(71!==t[o]||i-o!==He&&71!==t[o+He]){if(h)return-1;break}if(h++,-1===r&&(r=o,0!==r&&(s=Math.min(r+18612,t.length-He)+1)),n||(n=0===Ve(t,o)),n&&h>1&&(0===r&&h>2||o+He>s))return r}e++}return-1}static createTrack(t,i){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Lt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?i:void 0}}resetInitSegment(t,i,s,e){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ke.createTrack("video"),this._audioTrack=Ke.createTrack("audio",e),this._id3Track=Ke.createTrack("id3"),this._txtTrack=Ke.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=s,this._duration=e}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:i,_id3Track:s}=this;t&&(t.pesData=null),i&&(i.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,i,s=!1,e=!1){let n;s||(this.sampleAes=null);const r=this._videoTrack,h=this._audioTrack,o=this._id3Track,a=this._txtTrack;let l=r.pid,c=r.pesData,u=h.pid,d=o.pid,f=h.pesData,v=o.pesData,p=null,g=this.pmtParsed,m=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=Kt(this.remainderData,t)).length,this.remainderData=null),y<He&&!e)return this.remainderData=t,{audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};const w=Math.max(0,Ke.syncOffset(t));y-=(y-w)%He,y<t.byteLength&&!e&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let b=0;for(let i=w;i<y;i+=He)if(71===t[i]){const e=!!(64&t[i+1]),y=Ve(t,i);let b;if((48&t[i+3])>>4>1){if(b=i+5+t[i+4],b===i+He)continue}else b=i+4;switch(y){case l:e&&(c&&(n=Ye(c))&&this.videoParser.parseAVCPES(r,a,n,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(t.subarray(b,i+He)),c.size+=i+He-b);break;case u:if(e){if(f&&(n=Ye(f)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,n);break;case"mp3":this.parseMPEGPES(h,n);break;case"ac3":this.parseAC3PES(h,n)}f={data:[],size:0}}f&&(f.data.push(t.subarray(b,i+He)),f.size+=i+He-b);break;case d:e&&(v&&(n=Ye(v))&&this.parseID3PES(o,n),v={data:[],size:0}),v&&(v.data.push(t.subarray(b,i+He)),v.size+=i+He-b);break;case 0:e&&(b+=t[b]+1),m=this._pmtId=ze(t,b);break;case m:{e&&(b+=t[b]+1);const n=We(t,b,this.typeSupported,s,this.observer);l=n.videoPid,l>0&&(r.pid=l,r.segmentCodec=n.segmentVideoCodec),u=n.audioPid,u>0&&(h.pid=u,h.segmentCodec=n.segmentAudioCodec),d=n.id3Pid,d>0&&(o.pid=d),null===p||g||(I.warn(`MPEG-TS PMT found at ${i} after unknown PID '${p}'. Backtracking to sync byte @${w} to parse all TS packets.`),p=null,i=w-188),g=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=y}}else b++;b>0&&Xe(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`)),r.pesData=c,h.pesData=f,o.pesData=v;const k={audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};return e&&this.extractRemainingSamples(k),k}flush(){const{remainderData:t}=this;let i;return this.remainderData=null,i=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t){const{audioTrack:i,videoTrack:s,id3Track:e,textTrack:n}=t,r=s.pesData,h=i.pesData,o=e.pesData;let a;if(r&&(a=Ye(r))?(this.videoParser.parseAVCPES(s,n,a,!0,this._duration),s.pesData=null):s.pesData=r,h&&(a=Ye(h))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,a);break;case"mp3":this.parseMPEGPES(i,a);break;case"ac3":this.parseAC3PES(i,a)}i.pesData=null}else null!=h&&h.size&&I.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=h;o&&(a=Ye(o))?(this.parseID3PES(e,a),e.pesData=null):e.pesData=o}demuxSampleAes(t,i,s){const e=this.demux(t,s,!0,!this.config.progressive),n=this.sampleAes=new Ge(this.observer,this.config,i);return this.decrypt(e,n)}decrypt(t,i){return new Promise((s=>{const{audioTrack:e,videoTrack:n}=t;e.samples&&"aac"===e.segmentCodec?i.decryptAacSamples(e.samples,0,(()=>{n.samples?i.decryptAvcSamples(n.samples,0,0,(()=>{s(t)})):s(t)})):n.samples&&i.decryptAvcSamples(n.samples,0,0,(()=>{s(t)}))}))}destroy(){this._duration=0}parseAACPES(t,i){let s=0;const e=this.aacOverFlow;let n,r,h,o=i.data;if(e){this.aacOverFlow=null;const i=e.missing,n=e.sample.unit.byteLength;if(-1===i)o=Kt(e.sample.unit,o);else{const r=n-i;e.sample.unit.set(o.subarray(0,i),r),t.samples.push(e.sample),s=e.missing}}for(n=s,r=o.length;n<r-1&&!ke(o,n);n++);if(n!==s){let t;const i=n<r-1;if(t=i?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",Xe(this.observer,new Error(t),i),!i)return}if(Te(t,this.observer,o,n,this.audioCodec),void 0!==i.pts)h=i.pts;else{if(!e)return void I.warn("[tsdemuxer]: AAC PES unknown PTS");{const i=$e(t.samplerate);h=e.sample.pts+i}}let a,l=0;for(;n<r;){if(a=Ee(t,o,n,h,l),n+=a.length,a.missing){this.aacOverFlow=a;break}for(l++;n<r-1&&!ke(o,n);n++);}}parseMPEGPES(t,i){const s=i.data,e=s.length;let n=0,r=0;const h=i.pts;if(void 0!==h)for(;r<e;)if(Pe(s,r)){const i=Ce(t,s,r,h,n);if(!i)break;r+=i.length,n++}else r++;else I.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,i){{const s=i.data,e=i.pts;if(void 0===e)return void I.warn("[tsdemuxer]: AC3 PES unknown PTS");const n=s.length;let r,h=0,o=0;for(;o<n&&(r=Fe(t,s,o,e,h++))>0;)o+=r}}parseID3PES(t,i){if(void 0===i.pts)return void I.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=S({},i,{type:this._videoTrack?Ki:Hi,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function Ve(t,i){return((31&t[i+1])<<8)+t[i+2]}function ze(t,i){return(31&t[i+10])<<8|t[i+11]}function We(t,i,s,e,n){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=i+3+((15&t[i+1])<<8|t[i+2])-4;for(i+=12+((15&t[i+10])<<8|t[i+11]);i<h;){const h=Ve(t,i),o=(15&t[i+3])<<8|t[i+4];switch(t[i]){case 207:if(!e){qe("ADTS AAC");break}case 15:-1===r.audioPid&&(r.audioPid=h);break;case 21:-1===r.id3Pid&&(r.id3Pid=h);break;case 219:if(!e){qe("H.264");break}case 27:-1===r.videoPid&&(r.videoPid=h,r.segmentVideoCodec="avc");break;case 3:case 4:s.mpeg||s.mp3?-1===r.audioPid&&(r.audioPid=h,r.segmentAudioCodec="mp3"):I.log("MPEG audio found, not supported in this browser");break;case 193:if(!e){qe("AC-3");break}case 129:s.ac3?-1===r.audioPid&&(r.audioPid=h,r.segmentAudioCodec="ac3"):I.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===r.audioPid&&o>0){let e=i+5,n=o;for(;n>2;){106===t[e]&&(!0!==s.ac3?I.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=h,r.segmentAudioCodec="ac3"));const i=t[e+1]+2;e+=i,n-=i}}break;case 194:case 135:return Xe(n,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return Xe(n,new Error("Unsupported HEVC in M2TS found")),r}i+=o+5}return r}function Xe(t,i,s){I.warn(`parsing error: ${i.message}`),t.emit(A.ERROR,A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:i,reason:i.message})}function qe(t){I.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ye(t){let i,s,e,n,r,h=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Kt(o[0],o[1]),o.splice(1,1);if(i=o[0],1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>t.size-6)return null;const a=i[7];192&a&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&a?(r=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-r>54e5&&(I.warn(`${Math.round((n-r)/9e4)}s delta between PTS and DTS, align them`),n=r)):r=n),e=i[8];let l=e+9;if(t.size<=l)return null;t.size-=l;const c=new Uint8Array(t.size);for(let t=0,s=o.length;t<s;t++){i=o[t];let s=i.byteLength;if(l){if(l>s){l-=s;continue}i=i.subarray(l),s-=l,l=0}c.set(i,h),h+=s}return s&&(s-=e+3),{data:c,pts:n,dts:r,len:s}}return null}class Je{static getSilentFrame(t,i){if("mp4a.40.2"===t){if(1===i)return new Uint8Array([0,200,0,128,35,128]);if(2===i)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===i)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===i)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===i)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===i)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===i)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===i)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===i)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 Qe=Math.pow(2,32)-1;class Ze{static init(){let t;for(t in Ze.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:[]},Ze.types)Ze.types.hasOwnProperty(t)&&(Ze.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const i=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]);Ze.HDLR_TYPES={video:i,audio:s};const e=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);Ze.STTS=Ze.STSC=Ze.STCO=n,Ze.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ze.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ze.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ze.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const r=new Uint8Array([105,115,111,109]),h=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Ze.FTYP=Ze.box(Ze.types.ftyp,r,o,r,h),Ze.DINF=Ze.box(Ze.types.dinf,Ze.box(Ze.types.dref,e))}static box(t,...i){let s=8,e=i.length;const n=e;for(;e--;)s+=i[e].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=255&s,r.set(t,4),e=0,s=8;e<n;e++)r.set(i[e],s),s+=i[e].byteLength;return r}static hdlr(t){return Ze.box(Ze.types.hdlr,Ze.HDLR_TYPES[t])}static mdat(t){return Ze.box(Ze.types.mdat,t)}static mdhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),e=Math.floor(i%(Qe+1));return Ze.box(Ze.types.mdhd,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,e>>24,e>>16&255,e>>8&255,255&e,85,196,0,0]))}static mdia(t){return Ze.box(Ze.types.mdia,Ze.mdhd(t.timescale,t.duration),Ze.hdlr(t.type),Ze.minf(t))}static mfhd(t){return Ze.box(Ze.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return Ze.box(Ze.types.minf,"audio"===t.type?Ze.box(Ze.types.smhd,Ze.SMHD):Ze.box(Ze.types.vmhd,Ze.VMHD),Ze.DINF,Ze.stbl(t))}static moof(t,i,s){return Ze.box(Ze.types.moof,Ze.mfhd(t),Ze.traf(s,i))}static moov(t){let i=t.length;const s=[];for(;i--;)s[i]=Ze.trak(t[i]);return Ze.box.apply(null,[Ze.types.moov,Ze.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(Ze.mvex(t)))}static mvex(t){let i=t.length;const s=[];for(;i--;)s[i]=Ze.trex(t[i]);return Ze.box.apply(null,[Ze.types.mvex,...s])}static mvhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),e=Math.floor(i%(Qe+1)),n=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,e>>24,e>>16&255,e>>8&255,255&e,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 Ze.box(Ze.types.mvhd,n)}static sdtp(t){const i=t.samples||[],s=new Uint8Array(4+i.length);let e,n;for(e=0;e<i.length;e++)n=i[e].flags,s[e+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return Ze.box(Ze.types.sdtp,s)}static stbl(t){return Ze.box(Ze.types.stbl,Ze.stsd(t),Ze.box(Ze.types.stts,Ze.STTS),Ze.box(Ze.types.stsc,Ze.STSC),Ze.box(Ze.types.stsz,Ze.STSZ),Ze.box(Ze.types.stco,Ze.STCO))}static avc1(t){let i,s,e,n=[],r=[];for(i=0;i<t.sps.length;i++)s=t.sps[i],e=s.byteLength,n.push(e>>>8&255),n.push(255&e),n=n.concat(Array.prototype.slice.call(s));for(i=0;i<t.pps.length;i++)s=t.pps[i],e=s.byteLength,r.push(e>>>8&255),r.push(255&e),r=r.concat(Array.prototype.slice.call(s));const h=Ze.box(Ze.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),o=t.width,a=t.height,l=t.pixelRatio[0],c=t.pixelRatio[1];return Ze.box(Ze.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,a>>8&255,255&a,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]),h,Ze.box(Ze.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ze.box(Ze.types.pasp,new Uint8Array([l>>24,l>>16&255,l>>8&255,255&l,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const i=t.config.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([i]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const i=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,i>>8&255,255&i,0,0])}static mp4a(t){return Ze.box(Ze.types.mp4a,Ze.audioStsd(t),Ze.box(Ze.types.esds,Ze.esds(t)))}static mp3(t){return Ze.box(Ze.types[".mp3"],Ze.audioStsd(t))}static ac3(t){return Ze.box(Ze.types["ac-3"],Ze.audioStsd(t),Ze.box(Ze.types.dac3,t.config))}static stsd(t){return Ze.box(Ze.types.stsd,Ze.STSD,"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?Ze.mp3(t):"ac3"===t.segmentCodec?Ze.ac3(t):Ze.mp4a(t):Ze.avc1(t))}static tkhd(t){const i=t.id,s=t.duration*t.timescale,e=t.width,n=t.height,r=Math.floor(s/(Qe+1)),h=Math.floor(s%(Qe+1));return Ze.box(Ze.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,h>>24,h>>16&255,h>>8&255,255&h,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,e>>8&255,255&e,0,0,n>>8&255,255&n,0,0]))}static traf(t,i){const s=Ze.sdtp(t),e=t.id,n=Math.floor(i/(Qe+1)),r=Math.floor(i%(Qe+1));return Ze.box(Ze.types.traf,Ze.box(Ze.types.tfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e])),Ze.box(Ze.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r])),Ze.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,Ze.box(Ze.types.trak,Ze.tkhd(t),Ze.mdia(t))}static trex(t){const i=t.id;return Ze.box(Ze.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,i){const s=t.samples||[],e=s.length,n=12+16*e,r=new Uint8Array(n);let h,o,a,l,c,u;for(r.set(["video"===t.type?1:0,0,15,1,e>>>24&255,e>>>16&255,e>>>8&255,255&e,(i+=8+n)>>>24&255,i>>>16&255,i>>>8&255,255&i],0),h=0;h<e;h++)o=s[h],a=o.duration,l=o.size,c=o.flags,u=o.cts,r.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,l>>>24&255,l>>>16&255,l>>>8&255,255&l,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*h);return Ze.box(Ze.types.trun,r)}static initSegment(t){Ze.types||Ze.init();const i=Ze.moov(t);return Kt(Ze.FTYP,i)}}Ze.types=void 0,Ze.HDLR_TYPES=void 0,Ze.STTS=void 0,Ze.STSC=void 0,Ze.STCO=void 0,Ze.STSZ=void 0,Ze.VMHD=void 0,Ze.SMHD=void 0,Ze.STSD=void 0,Ze.FTYP=void 0,Ze.DINF=void 0;function tn(t,i,s=1,e=!1){const n=t*i*s;return e?Math.round(n):n}function sn(t,i=!1){return tn(t,1e3,1/9e4,i)}let en,nn=null,rn=null;class hn{constructor(t,i,s,e=""){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=i,this.typeSupported=s,this.ISGenerated=!1,null===nn){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);nn=t?parseInt(t[1]):0}if(null===rn){const t=navigator.userAgent.match(/Safari\/(\d+)/i);rn=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){I.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){I.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){I.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let i=!1;const s=t[0].pts,e=t.reduce(((t,e)=>{let n=e.pts,r=n-t;return r<-4294967296&&(i=!0,n=on(n,s),r=n-t),r>0?t:n}),s);return i&&I.debug("PTS rollover detected"),e}remux(t,i,s,e,n,r,h,o){let a,l,c,u,d,f,v=n,p=n;const g=i.pid>-1,m=i.samples.length,y=t.samples.length>0,w=h&&m>0||m>1;if((!(t.pid>-1)||y)&&(!g||w)||this.ISGenerated||h){if(this.ISGenerated){var b,k,S,T;const t=this.videoTrackConfig;!t||i.width===t.width&&i.height===t.height&&(null==(b=i.pixelRatio)?void 0:b[0])===(null==(k=t.pixelRatio)?void 0:k[0])&&(null==(S=i.pixelRatio)?void 0:S[1])===(null==(T=t.pixelRatio)?void 0:T[1])||this.resetInitSegment()}else c=this.generateIS(t,i,n,r);const s=this.isVideoContiguous;let e,h=-1;if(w&&(h=function(t){for(let i=0;i<t.length;i++)if(t[i].key)return i;return-1}(i.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,h>0){I.warn(`[mp4-remuxer]: Dropped ${h} out of ${m} video samples due to a missing keyframe`);const t=this.getVideoStartPts(i.samples);i.samples=i.samples.slice(h),i.dropped+=h,p+=(i.samples[0].pts-t)/i.inputTimeScale,e=p}else-1===h&&(I.warn(`[mp4-remuxer]: No keyframe found out of ${m} video samples`),f=!1);if(this.ISGenerated){if(y&&w){const s=this.getVideoStartPts(i.samples),e=(on(t.samples[0].pts,s)-s)/i.inputTimeScale;v+=Math.max(0,e),p+=Math.max(0,-e)}if(y){if(t.samplerate||(I.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(t,i,n,r)),l=this.remuxAudio(t,v,this.isAudioContiguous,r,g||w||o===Ri?p:void 0),w){const e=l?l.endPTS-l.startPTS:0;i.inputTimeScale||(I.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(t,i,n,r)),a=this.remuxVideo(i,p,s,e)}}else w&&(a=this.remuxVideo(i,p,s,0));a&&(a.firstKeyFrame=h,a.independent=-1!==h,a.firstKeyFramePTS=e)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(d=an(s,n,this._initPTS,this._initDTS)),e.samples.length&&(u=ln(e,n,this._initPTS))),{audio:l,video:a,initSegment:c,independent:f,text:u,id3:d}}generateIS(t,i,s,e){const n=t.samples,r=i.samples,h=this.typeSupported,o={},a=this._initPTS;let l,c,u,d=!a||e,f="audio/mp4";if(d&&(l=c=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):Ze.initSegment([t]),metadata:{channelCount:t.channelCount}},d&&(u=t.inputTimeScale,a&&u===a.timescale?d=!1:l=c=n[0].pts-Math.round(u*s))}if(i.sps&&i.pps&&r.length){if(i.timescale=i.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:i.codec,initSegment:Ze.initSegment([i]),metadata:{width:i.width,height:i.height}},d)if(u=i.inputTimeScale,a&&u===a.timescale)d=!1;else{const t=this.getVideoStartPts(r),i=Math.round(u*s);c=Math.min(c,on(r[0].dts,t)-i),l=Math.min(l,t-i)}this.videoTrackConfig={width:i.width,height:i.height,pixelRatio:i.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:l,timescale:u},this._initDTS={baseTime:c,timescale:u}):l=u=void 0,{tracks:o,initPTS:l,timescale:u}}remuxVideo(t,i,s,e){const n=t.inputTimeScale,r=t.samples,h=[],o=r.length,a=this._initPTS;let l,c,u=this.nextAvcDts,d=8,f=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,g=!1;if(!s||null===u){const t=i*n,e=r[0].pts-on(r[0].dts,r[0].pts);nn&&null!==u&&Math.abs(t-e-u)<15e3?s=!0:u=t-e}const m=a.baseTime*n/a.timescale;for(let t=0;t<o;t++){const i=r[t];i.pts=on(i.pts-m,u),i.dts=on(i.dts-m,u),i.dts<r[t>0?t-1:t].dts&&(g=!0)}g&&r.sort((function(t,i){return t.dts-i.dts||t.pts-i.pts})),l=r[0].dts,c=r[r.length-1].dts;const y=c-l,w=y?Math.round(y/(o-1)):f||t.inputTimeScale/30;if(s){const t=l-u,s=t>w,e=t<-1;if((s||e)&&(I.warn(s?`AVC: ${sn(t,!0)} ms (${t}dts) hole between fragments detected at ${i.toFixed(3)}`:`AVC: ${sn(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${i.toFixed(3)}`),!e||u>=r[0].pts||nn)){l=u;const i=r[0].pts-t;if(s)r[0].dts=l,r[0].pts=i;else for(let s=0;s<r.length&&!(r[s].dts>i);s++)r[s].dts-=t,r[s].pts-=t;I.log(`Video: Initial PTS/DTS adjusted: ${sn(i,!0)}/${sn(l,!0)}, delta: ${sn(t,!0)} ms`)}}l=Math.max(0,l);let b=0,k=0,T=l;for(let t=0;t<o;t++){const i=r[t],s=i.units,e=s.length;let n=0;for(let t=0;t<e;t++)n+=s[t].data.length;k+=n,b+=e,i.length=n,i.dts<T?(i.dts=T,T+=w/4|0||1):T=i.dts,v=Math.min(i.pts,v),p=Math.max(i.pts,p)}c=r[o-1].dts;const $=k+4*b+8;let E;try{E=new Uint8Array($)}catch(t){return void this.observer.emit(A.ERROR,A.ERROR,{type:M.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:$,reason:`fail allocating video mdat ${$}`})}const x=new DataView(E.buffer);x.setUint32(0,$),E.set(Ze.types.mdat,4);let D=!1,C=Number.POSITIVE_INFINITY,R=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const i=r[t],s=i.units;let a,l=0;for(let t=0,i=s.length;t<i;t++){const i=s[t],e=i.data,n=i.data.byteLength;x.setUint32(d,n),d+=4,E.set(e,d),d+=n,l+=4+n}if(t<o-1)f=r[t+1].dts-i.dts,a=r[t+1].pts-i.pts;else{const s=this.config,h=t>0?i.dts-r[t-1].dts:w;if(a=t>0?i.pts-r[t-1].pts:w,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*n),r=(e?v+e*n:this.nextAudioPts)-i.pts;r>t?(f=r-h,f<0?f=h:D=!0,I.log(`[mp4-remuxer]: It is approximately ${r/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=h}else f=h}const c=Math.round(i.pts-i.dts);C=Math.min(C,f),P=Math.max(P,f),R=Math.min(R,a),O=Math.max(O,a),h.push(new cn(i.key,f,l,c))}if(h.length)if(nn){if(nn<70){const t=h[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(rn&&O-R<P-C&&w/P<.025&&0===h[0].cts){I.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=l;for(let i=0,s=h.length;i<s;i++){const e=t+h[i].duration;h[i].duration=i<s-1?e+h[i+1].cts-(t+h[i].cts):i?h[i-1].duration:w,h[i].cts=0,t=e}}f=D||!f?w:f,this.nextAvcDts=u=c+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const N={data1:Ze.moof(t.sequenceNumber++,l,S({},t,{samples:h})),data2:E,startPTS:v/n,endPTS:(p+f)/n,startDTS:l/n,endDTS:u/n,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,i,s,e,n){const r=t.inputTimeScale,h=r/(t.samplerate?t.samplerate:r),o=this.getSamplesPerFrame(t),a=o*h,l=this._initPTS,c="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],d=void 0!==n;let f=t.samples,v=c?0:8,p=this.nextAudioPts||-1;const g=i*r,m=l.baseTime*r/l.timescale;if(this.isAudioContiguous=s=s||f.length&&p>0&&(e&&Math.abs(g-p)<9e3||Math.abs(on(f[0].pts-m,g)-p)<20*a),f.forEach((function(t){t.pts=on(t.pts-m,g)})),!s||p<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;p=0===n?0:e&&!d?Math.max(0,g):f[0].pts}if("aac"===t.segmentCodec){const i=this.config.maxAudioFramesDrift;for(let s=0,e=p;s<f.length;s++){const n=f[s],h=n.pts,o=h-e,l=Math.abs(1e3*o/r);if(o<=-i*a&&d)0===s&&(I.warn(`Audio frame @ ${(h/r).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/r)} ms.`),this.nextAudioPts=p=e=h);else if(o>=i*a&&l<1e4&&d){let i=Math.round(o/a);e=h-i*a,e<0&&(i--,e+=a),0===s&&(this.nextAudioPts=p=e),I.warn(`[mp4-remuxer]: Injecting ${i} audio frame @ ${(e/r).toFixed(3)}s due to ${Math.round(1e3*o/r)} ms gap.`);for(let r=0;r<i;r++){const i=Math.max(e,0);let r=Je.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);r||(I.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),r=n.unit.subarray()),f.splice(s,0,{unit:r,pts:i}),e+=a,s++}}n.pts=e,e+=a}}let y,w=null,b=null,k=0,T=f.length;for(;T--;)k+=f[T].unit.byteLength;for(let i=0,e=f.length;i<e;i++){const e=f[i],n=e.unit;let r=e.pts;if(null!==b)u[i-1].duration=Math.round((r-b)/h);else{if(s&&"aac"===t.segmentCodec&&(r=p),w=r,!(k>0))return;k+=v;try{y=new Uint8Array(k)}catch(t){return void this.observer.emit(A.ERROR,A.ERROR,{type:M.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:`fail allocating audio mdat ${k}`})}c||(new DataView(y.buffer).setUint32(0,k),y.set(Ze.types.mdat,4))}y.set(n,v);const a=n.byteLength;v+=a,u.push(new cn(!0,o,a,0)),b=r}const $=u.length;if(!$)return;this.nextAudioPts=p=b+h*u[u.length-1].duration;const E=c?new Uint8Array(0):Ze.moof(t.sequenceNumber++,w/h,S({},t,{samples:u}));t.samples=[];const x=w/r,D=p/r,C={data1:E,data2:y,startPTS:x,endPTS:D,startDTS:x,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:$};return this.isAudioContiguous=!0,C}remuxEmptyAudio(t,i,s,e){const n=t.inputTimeScale,r=this.nextAudioPts,h=this._initDTS,o=9e4*h.baseTime/h.timescale,a=(null!==r?r:e.startDTS*n)+o,l=n/(t.samplerate?t.samplerate:n)*1024,c=Math.ceil((e.endDTS*n+o-a)/l),u=Je.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(I.warn("[mp4-remuxer]: remux empty Audio"),!u)return void I.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const d=[];for(let t=0;t<c;t++){const i=a+t*l;d.push({unit:u,pts:i,dts:i})}return t.samples=d,this.remuxAudio(t,i,s,!1)}}function on(t,i){let s;if(null===i)return t;for(s=i<t?-8589934592:8589934592;Math.abs(t-i)>4294967296;)t+=s;return t}function an(t,i,s,e){const n=t.samples.length;if(!n)return;const r=t.inputTimeScale;for(let h=0;h<n;h++){const n=t.samples[h];n.pts=on(n.pts-s.baseTime*r/s.timescale,i*r)/r,n.dts=on(n.dts-e.baseTime*r/e.timescale,i*r)/r}const h=t.samples;return t.samples=[],{samples:h}}function ln(t,i,s){const e=t.samples.length;if(!e)return;const n=t.inputTimeScale;for(let r=0;r<e;r++){const e=t.samples[r];e.pts=on(e.pts-s.baseTime*n/s.timescale,i*n)/n}t.samples.sort(((t,i)=>t.pts-i.pts));const r=t.samples;return t.samples=[],{samples:r}}class cn{constructor(t,i,s,e){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=i,this.size=s,this.cts=e,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function un(t,i){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(i===B){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s)return fi(s,!1);const t="mp4a.40.5";return I.info(`Parsed audio codec "${s}" or audio object type not handled. Using "${t}"`),t}return I.warn(`Unhandled video codec "${s}"`),"hvc1"===s||"hev1"===s?"hvc1.1.6.L120.90":"av01"===s?"av01.0.04M.08":"avc1.42e01e"}try{en=self.performance.now.bind(self.performance)}catch(t){I.debug("Unable to use Performance API on this environment"),en=null==X?void 0:X.Date.now}const dn=[{demux:class{constructor(t,i){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=i}resetTimeStamp(){}resetInitSegment(t,i,s,e){const n=this.videoTrack=pe("video",1),r=this.audioTrack=pe("audio",1),h=this.txtTrack=pe("text",1);if(this.id3Track=pe("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Ut(t);if(o.video){const{id:t,timescale:i,codec:s}=o.video;n.id=t,n.timescale=h.timescale=i,n.codec=s}if(o.audio){const{id:t,timescale:i,codec:s}=o.audio;r.id=t,r.timescale=i,r.codec=s}h.id=Lt.text,n.sampleDuration=0,n.duration=r.duration=e}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const i=t.byteLength;for(let s=0;s<i;){const e=Ct(t,s);if(e>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=e>1?s+e:i}return!1}(t)}demux(t,i){this.timeOffset=i;let s=t;const e=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Kt(this.remainderData,t));const i=function(t){const i={valid:null,remainder:null},s=Ot(t,["moof"]);if(s.length<2)return i.remainder=t,i;const e=s[s.length-1];return i.valid=ot(t,0,e.byteOffset-8),i.remainder=ot(t,e.byteOffset-8),i}(s);this.remainderData=i.remainder,e.samples=i.valid||new Uint8Array}else e.samples=s;const r=this.extractID3Track(e,i);return n.samples=Vt(i,e),{videoTrack:e,audioTrack:this.audioTrack,id3Track:r,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,i=this.videoTrack,s=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const e=this.extractID3Track(i,this.timeOffset);return s.samples=Vt(t,i),{videoTrack:i,audioTrack:pe(),id3Track:e,textTrack:pe()}}extractID3Track(t,i){const s=this.id3Track;if(t.samples.length){const e=Ot(t.samples,["emsg"]);e&&e.forEach((t=>{const e=function(t){const i=t[0];let s="",e="",n=0,r=0,h=0,o=0,a=0,l=0;if(0===i){for(;"\0"!==xt(t.subarray(l,l+1));)s+=xt(t.subarray(l,l+1)),l+=1;for(s+=xt(t.subarray(l,l+1)),l+=1;"\0"!==xt(t.subarray(l,l+1));)e+=xt(t.subarray(l,l+1)),l+=1;e+=xt(t.subarray(l,l+1)),l+=1,n=Ct(t,12),r=Ct(t,16),o=Ct(t,20),a=Ct(t,24),l=28}else if(1===i){l+=4,n=Ct(t,l),l+=4;const i=Ct(t,l);l+=4;const r=Ct(t,l);for(l+=4,h=2**32*i+r,$(h)||(h=Number.MAX_SAFE_INTEGER,I.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ct(t,l),l+=4,a=Ct(t,l),l+=4;"\0"!==xt(t.subarray(l,l+1));)s+=xt(t.subarray(l,l+1)),l+=1;for(s+=xt(t.subarray(l,l+1)),l+=1;"\0"!==xt(t.subarray(l,l+1));)e+=xt(t.subarray(l,l+1)),l+=1;e+=xt(t.subarray(l,l+1)),l+=1}return{schemeIdUri:s,value:e,timeScale:n,presentationTime:h,presentationTimeDelta:r,eventDuration:o,id:a,payload:t.subarray(l,t.byteLength)}}(t);if(Ne.test(e.schemeIdUri)){const t=T(e.presentationTime)?e.presentationTime/e.timeScale:i+e.presentationTimeDelta/e.timeScale;let n=4294967295===e.eventDuration?Number.POSITIVE_INFINITY:e.eventDuration/e.timeScale;n<=.001&&(n=Number.POSITIVE_INFINITY);const r=e.payload;s.samples.push({data:r,len:r.byteLength,dts:t,pts:t,type:Ki,duration:n})}}))}return s}demuxSampleAes(t,i,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,i,s,e){this.audioCodec=i,this.videoCodec=s,this.generateInitSegment(function(t,i){if(!t||!i)return t;const s=i.keyId;return s&&i.isCommonEncryption&&Ot(t,["moov","trak"]).forEach((t=>{const i=Ot(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let e=Ot(i,["enca"]);const n=e.length>0;n||(e=Ot(i,["encv"])),e.forEach((t=>{Ot(t.subarray(n?28:78),["sinf"]).forEach((t=>{const i=Gt(t);if(i){const t=i.subarray(8,24);t.some((t=>0!==t))||(I.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Et(t)} -> ${Et(s)}`),i.set(s,8))}}))}))})),t}(t,e)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:i,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const e=this.initData=Ut(t);e.audio&&(i=un(e.audio,B)),e.video&&(s=un(e.video,j));const n={};e.audio&&e.video?n.audiovideo={container:"video/mp4",codec:i+","+s,initSegment:t,id:"main"}:e.audio?n.audio={container:"audio/mp4",codec:i,initSegment:t,id:"audio"}:e.video?n.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:I.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(t,i,s,e,n,r){var h,o;let{initPTS:a,lastEndTime:l}=this;const c={audio:void 0,video:void 0,text:e,id3:s,initSegment:void 0};T(l)||(l=this.lastEndTime=n||0);const u=i.samples;if(null==u||!u.length)return c;const d={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(h=f)&&h.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return I.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const v=function(t,i){let s=0,e=0,n=0;const r=Ot(t,["moof","traf"]);for(let t=0;t<r.length;t++){const h=r[t],o=Ot(h,["tfhd"])[0],a=i[Ct(o,4)];if(!a)continue;const l=a.default,c=Ct(o,0)|(null==l?void 0:l.flags);let u=null==l?void 0:l.duration;8&c&&(u=Ct(o,2&c?12:8));const d=a.timescale||9e4,f=Ot(h,["trun"]);for(let t=0;t<f.length;t++)s=Ht(f[t]),!s&&u&&(s=u*Ct(f[t],4)),a.type===j?e+=s/d:a.type===B&&(n+=s/d)}if(0===e&&0===n){let i=1/0,s=0,e=0;const n=Ot(t,["sidx"]);for(let t=0;t<n.length;t++){const r=Nt(n[t]);if(null!=r&&r.references){i=Math.min(i,r.earliestPresentationTime/r.timescale);const t=r.references.reduce(((t,i)=>t+i.info.duration||0),0);s=Math.max(s,t+r.earliestPresentationTime/r.timescale),e=s-i}}if(e&&T(e))return e}return e||n}(u,f),p=function(t,i){return Ot(i,["moof","traf"]).reduce(((i,s)=>{const e=Ot(s,["tfdt"])[0],n=e[0],r=Ot(s,["tfhd"]).reduce(((i,s)=>{const r=Ct(s,4),h=t[r];if(h){let t=Ct(e,4);if(1===n){if(t===At)return I.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),i;t*=At+1,t+=Ct(e,8)}const s=t/(h.timescale||9e4);if(T(s)&&(null===i||s<i))return s}return i}),null);return null!==r&&T(r)&&(null===i||r<i)?r:i}),null)}(f,u),g=null===p?n:p;(function(t,i,s,e){if(null===t)return!0;const n=Math.max(e,1);return Math.abs(i-t.baseTime/t.timescale-s)>n}(a,g,n,v)||d.timescale!==a.timescale&&r)&&(d.initPTS=g-n,a&&1===a.timescale&&I.warn("Adjusting initPTS by "+(d.initPTS-a.baseTime)),this.initPTS=a={baseTime:d.initPTS,timescale:1});const m=t?g-a.baseTime/a.timescale:l,y=m+v;!function(t,i,s){Ot(i,["moof","traf"]).forEach((i=>{Ot(i,["tfhd"]).forEach((e=>{const n=Ct(e,4),r=t[n];if(!r)return;const h=r.timescale||9e4;Ot(i,["tfdt"]).forEach((t=>{const i=t[0],e=s*h;if(e){let s=Ct(t,4);if(0===i)s-=e,s=Math.max(s,0),Pt(t,4,s);else{s*=Math.pow(2,32),s+=Ct(t,8),s-=e,s=Math.max(s,0);const i=Math.floor(s/(At+1)),n=Math.floor(s%(At+1));Pt(t,4,i),Pt(t,8,n)}}}))}))}))}(f,u,a.baseTime/a.timescale),v>0?this.lastEndTime=y:(I.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!f.audio,b=!!f.video;let k="";w&&(k+="audio"),b&&(k+="video");const S={data1:u,startPTS:m,startDTS:m,endPTS:y,endDTS:y,type:k,hasAudio:w,hasVideo:b,nb:1,dropped:0};return c.audio="audio"===S.type?S:void 0,c.video="audio"!==S.type?S:void 0,c.initSegment=d,c.id3=an(s,n,a,a),e.samples.length&&(c.text=ln(e,n,a)),c}}},{demux:Ke,remux:hn},{demux:class extends ge{constructor(t,i){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=i}resetInitSegment(t,i,s,e){super.resetInitSegment(t,i,s,e),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:e,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const i=ct(t,0);let s=(null==i?void 0:i.length)||0;if(Oe(t,s))return!1;for(let i=t.length;s<i;s++)if(Se(t,s))return I.log("ADTS sync word found !"),!0;return!1}canParse(t,i){return function(t,i){return function(t,i){return i+5<t.length}(t,i)&&ye(t,i)&&be(t,i)<=t.length-i}(t,i)}appendFrame(t,i,s){Te(t,this.observer,i,s,t.manifestCodec);const e=Ee(t,i,s,this.basePTS,this.frameIndex);if(e&&0===e.missing)return e}},remux:hn},{demux:class extends ge{resetInitSegment(t,i,s,e){super.resetInitSegment(t,i,s,e),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:e,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const i=ct(t,0);let s=(null==i?void 0:i.length)||0;if(i&&11===t[s]&&119===t[s+1]&&void 0!==ft(i)&&Ue(t,s)<=16)return!1;for(let i=t.length;s<i;s++)if(Oe(t,s))return I.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,i){return function(t,i){return Re(t,i)&&4<=t.length-i}(t,i)}appendFrame(t,i,s){if(null!==this.basePTS)return Ce(t,i,s,this.basePTS,this.frameIndex)}},remux:hn}];dn.splice(2,0,{demux:class extends ge{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,i,s,e){super.resetInitSegment(t,i,s,e),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:e,inputTimeScale:9e4,dropped:0}}canParse(t,i){return i+64<t.length}appendFrame(t,i,s){const e=Fe(t,i,s,this.basePTS,this.frameIndex);if(-1!==e)return{sample:t.samples[t.samples.length-1],length:e,missing:0}}static probe(t){if(!t)return!1;const i=ct(t,0);if(!i)return!1;const s=i.length;return 11===t[s]&&119===t[s+1]&&void 0!==ft(i)&&Ue(t,s)<16}},remux:hn});class fn{constructor(t,i,s,e,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=i,this.config=s,this.vendor=e,this.id=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,i,s,e){const n=s.transmuxing;n.executeStart=en();let r=new Uint8Array(t);const{currentTransmuxState:h,transmuxConfig:o}=this;e&&(this.currentTransmuxState=e);const{contiguous:a,discontinuity:l,trackSwitch:c,accurateTimeOffset:u,timeOffset:d,initSegmentChange:f}=e||h,{audioCodec:v,videoCodec:p,defaultInitPts:g,duration:m,initSegmentData:y}=o,w=function(t,i){let s=null;return t.byteLength>0&&null!=(null==i?void 0:i.key)&&null!==i.iv&&null!=i.method&&(s=i),s}(r,i);if(w&&"AES-128"===w.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(r,w.key.buffer,w.iv.buffer).then((t=>{const i=this.push(t,null,s);return this.decryptionPromise=null,i})),this.decryptionPromise;{let i=t.softwareDecrypt(r,w.key.buffer,w.iv.buffer);if(s.part>-1&&(i=t.flush()),!i)return n.executeEnd=en(),vn(s);r=new Uint8Array(i)}}const b=this.needsProbing(l,c);if(b){const t=this.configureTransmuxer(r);if(t)return I.warn(`[transmuxer] ${t.message}`),this.observer.emit(A.ERROR,A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),n.executeEnd=en(),vn(s)}(l||c||f||b)&&this.resetInitSegment(y,v,p,m,i),(l||f||b)&&this.resetInitialTimestamp(g),a||this.resetContiguity();const k=this.transmux(r,w,d,u,s),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=en(),k}flush(t){const i=t.transmuxing;i.executeStart=en();const{decrypter:s,currentTransmuxState:e,decryptionPromise:n}=this;if(n)return n.then((()=>this.flush(t)));const r=[],{timeOffset:h}=e;if(s){const i=s.flush();i&&r.push(this.push(i,null,t))}const{demuxer:o,remuxer:a}=this;if(!o||!a)return i.executeEnd=en(),[vn(t)];const l=o.flush(h);return pn(l)?l.then((i=>(this.flushRemux(r,i,t),r))):(this.flushRemux(r,l,t),r)}flushRemux(t,i,s){const{audioTrack:e,videoTrack:n,id3Track:r,textTrack:h}=i,{accurateTimeOffset:o,timeOffset:a}=this.currentTransmuxState;I.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const l=this.remuxer.remux(e,n,r,h,a,o,!0,this.id);t.push({remuxResult:l,chunkMeta:s}),s.transmuxing.executeEnd=en()}resetInitialTimestamp(t){const{demuxer:i,remuxer:s}=this;i&&s&&(i.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetContiguity(),i.resetNextTimestamp())}resetInitSegment(t,i,s,e,n){const{demuxer:r,remuxer:h}=this;r&&h&&(r.resetInitSegment(t,i,s,e),h.resetInitSegment(t,i,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,i,s,e,n){let r;return r=i&&"SAMPLE-AES"===i.method?this.transmuxSampleAes(t,i,s,e,n):this.transmuxUnencrypted(t,s,e,n),r}transmuxUnencrypted(t,i,s,e){const{audioTrack:n,videoTrack:r,id3Track:h,textTrack:o}=this.demuxer.demux(t,i,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,r,h,o,i,s,!1,this.id),chunkMeta:e}}transmuxSampleAes(t,i,s,e,n){return this.demuxer.demuxSampleAes(t,i,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,e,!1,this.id),chunkMeta:n})))}configureTransmuxer(t){const{config:i,observer:s,typeSupported:e,vendor:n}=this;let r;for(let i=0,s=dn.length;i<s;i++){var h;if(null!=(h=dn[i].demux)&&h.probe(t)){r=dn[i];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,a=this.remuxer,l=r.remux,c=r.demux;a&&a instanceof l||(this.remuxer=new l(s,i,e,n)),o&&o instanceof c||(this.demuxer=new c(s,i,e),this.probe=c.probe)}needsProbing(t,i){return!this.demuxer||!this.remuxer||t||i}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new te(this.config)),t}}const vn=t=>({remuxResult:{},chunkMeta:t});function pn(t){return"then"in t&&t.then instanceof Function}class gn{constructor(t,i,s,e,n){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=i,this.initSegmentData=s,this.duration=e,this.defaultInitPts=n||null}}class mn{constructor(t,i,s,e,n,r){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=i,this.accurateTimeOffset=s,this.trackSwitch=e,this.timeOffset=n,this.initSegmentChange=r}}var yn={exports:{}};!function(t){var i=Object.prototype.hasOwnProperty,s="~";function e(){}function n(t,i,s){this.fn=t,this.context=i,this.once=s||!1}function r(t,i,e,r,h){if("function"!=typeof e)throw new TypeError("The listener must be a function");var o=new n(e,r||t,h),a=s?s+i:i;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],o]:t._events[a].push(o):(t._events[a]=o,t._eventsCount++),t}function h(t,i){0==--t._eventsCount?t._events=new e:delete t._events[i]}function o(){this._events=new e,this._eventsCount=0}Object.create&&(e.prototype=Object.create(null),(new e).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,e,n=[];if(0===this._eventsCount)return n;for(e in t=this._events)i.call(t,e)&&n.push(s?e.slice(1):e);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(t)):n},o.prototype.listeners=function(t){var i=this._events[s?s+t:t];if(!i)return[];if(i.fn)return[i.fn];for(var e=0,n=i.length,r=new Array(n);e<n;e++)r[e]=i[e].fn;return r},o.prototype.listenerCount=function(t){var i=this._events[s?s+t:t];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,i,e,n,r,h){var o=s?s+t:t;if(!this._events[o])return!1;var a,l,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,i),!0;case 3:return c.fn.call(c.context,i,e),!0;case 4:return c.fn.call(c.context,i,e,n),!0;case 5:return c.fn.call(c.context,i,e,n,r),!0;case 6:return c.fn.call(c.context,i,e,n,r,h),!0}for(l=1,a=new Array(u-1);l<u;l++)a[l-1]=arguments[l];c.fn.apply(c.context,a)}else{var d,f=c.length;for(l=0;l<f;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,i);break;case 3:c[l].fn.call(c[l].context,i,e);break;case 4:c[l].fn.call(c[l].context,i,e,n);break;default:if(!a)for(d=1,a=new Array(u-1);d<u;d++)a[d-1]=arguments[d];c[l].fn.apply(c[l].context,a)}}return!0},o.prototype.on=function(t,i,s){return r(this,t,i,s,!1)},o.prototype.once=function(t,i,s){return r(this,t,i,s,!0)},o.prototype.removeListener=function(t,i,e,n){var r=s?s+t:t;if(!this._events[r])return this;if(!i)return h(this,r),this;var o=this._events[r];if(o.fn)o.fn!==i||n&&!o.once||e&&o.context!==e||h(this,r);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==i||n&&!o[a].once||e&&o[a].context!==e)&&l.push(o[a]);l.length?this._events[r]=1===l.length?l[0]:l:h(this,r)}return this},o.prototype.removeAllListeners=function(t){var i;return t?this._events[i=s?s+t:t]&&h(this,i):(this._events=new e,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(yn);var wn=f(yn.exports);class bn{constructor(t,i,s,e){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=t.config;this.hls=t,this.id=i,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=e;const r=(t,i)=>{(i=i||{}).frag=this.frag,i.id=this.id,t===A.ERROR&&(this.error=i.error),this.hls.trigger(t,i)};this.observer=new wn,this.observer.on(A.FRAG_DECRYPTED,r),this.observer.on(A.ERROR,r);const h=ni(n.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:h.isTypeSupported("audio/mpeg"),mp3:h.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:h.isTypeSupported('audio/mp4; codecs="ac-3"')};if(!this.useWorker||"undefined"==typeof Worker||!n.workerPath&&"function"!=typeof __HLS_WORKER_BUNDLE__)this.transmuxer=new fn(this.observer,o,n,"",i);else try{n.workerPath?(I.log(`loading Web Worker ${n.workerPath} for "${i}"`),this.workerContext=function(t){const i=new self.URL(t,self.location.href).href;return{worker:new self.Worker(i),scriptURL:i}}(n.workerPath)):(I.log(`injecting Web Worker for "${i}"`),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"}),i=self.URL.createObjectURL(t);return{worker:new self.Worker(i),objectURL:i}}()),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})`);n.enableWorker=!1,I.warn(`Error in "${i}" Web Worker, fallback to inline`),this.hls.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:o,vendor:"",id:i,config:JSON.stringify(n)})}catch(t){I.warn(`Error setting up "${i}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new fn(this.observer,o,n,"",i)}}resetWorker(){if(this.workerContext){const{worker:t,objectURL:i}=this.workerContext;i&&self.URL.revokeObjectURL(i),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,i,s,e,n,r,h,o,a,l){var c,u;a.transmuxing.start=self.performance.now();const{transmuxer:d}=this,f=r?r.start:n.start,v=n.decryptdata,p=this.frag,g=!(p&&n.cc===p.cc),m=!(p&&a.level===p.level),y=p?a.sn-p.sn:-1,w=this.part?a.part-this.part.index:-1,b=!m&&(1===y||0===y&&(1===w||0===y&&a.id>1&&a.id===(null==p?void 0:p.stats.chunkCount)&&w<=0)),k=self.performance.now();(m||y||0===n.stats.parsing.start)&&(n.stats.parsing.start=k),!r||!w&&b||(r.stats.parsing.start=k);const S=!(p&&(null==(c=n.initSegment)?void 0:c.url)===(null==(u=p.initSegment)?void 0:u.url)),T=new mn(g,b,o,m,f,S);if(!b||g||S){I.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${a.sn} p: ${a.part} level: ${a.level} id: ${a.id}\n discontinuity: ${g}\n trackSwitch: ${m}\n contiguous: ${b}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${S}`);const t=new gn(s,e,i,h,l);this.configureTransmuxer(t)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:v,chunkMeta:a,state:T},t instanceof ArrayBuffer?[t]:[]);else if(d){const i=d.push(t,v,a,T);pn(i)?(d.async=!0,i.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,a,"transmuxer-interface push error")}))):(d.async=!1,this.handleTransmuxComplete(i))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(i){let s=i.flush(t);pn(s)||i.async?(pn(s)||(s=Promise.resolve(s)),s.then((i=>{this.handleFlushResult(i,t)})).catch((i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}))):this.handleFlushResult(s,t)}}transmuxerError(t,i,s){this.hls&&(this.error=t,this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:i,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,i){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(i)}onWorkerMessage(t){const i=t.data;if(null==i||!i.event)return void I.warn("worker message received with no "+(i?"event name":"data"));const s=this.hls;if(this.hls)switch(i.event){case"init":{var e;const t=null==(e=this.workerContext)?void 0:e.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(i.data);break;case"flush":this.onFlush(i.data);break;case"workerLog":I[i.data.logType]&&I[i.data.logType](i.data.message);break;default:i.data=i.data||{},i.data.frag=this.frag,i.data.id=this.id,s.trigger(i.event,i.data)}}configureTransmuxer(t){const{transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function kn(t,i){if(t.length!==i.length)return!1;for(let s=0;s<t.length;s++)if(!Sn(t[s].attrs,i[s].attrs))return!1;return!0}function Sn(t,i,s){const e=t["STABLE-RENDITION-ID"];return e&&!s?e===i["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((s=>t[s]!==i[s]))}function Tn(t,i){return i.label.toLowerCase()===t.name.toLowerCase()&&(!i.language||i.language.toLowerCase()===(t.lang||"").toLowerCase())}class $n{constructor(t){this.buffered=void 0;const i=(i,s,e)=>{if((s>>>=0)>e-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${e})`);return t[s][i]};this.buffered={get length(){return t.length},end:s=>i("end",s,t.length),start:s=>i("start",s,t.length)}}}class En{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,i,s){const e=this.queues[i];e.push(t),1!==e.length||s||this.executeNext(i)}insertAbort(t,i){this.queues[i].unshift(t),this.executeNext(i)}appendBlocker(t){let i;const s=new Promise((t=>{i=t}));return this.append({execute:i,onStart:()=>{},onComplete:()=>{},onError:()=>{}},t),s}executeNext(t){const i=this.queues[t];if(i.length){const s=i[0];try{s.execute()}catch(i){I.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${i}`),s.onError(i);const e=this.buffers[t];null!=e&&e.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const An=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Mn(t){const i=t.querySelectorAll("source");[].slice.call(i).forEach((i=>{t.removeChild(i)}))}const Ln={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},xn=t=>String.fromCharCode(Ln[t]||t),Dn=15,Cn=100,In={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Rn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Pn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},On={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Nn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Un{constructor(){this.time=null,this.verboseLevel=0}log(t,i){if(this.verboseLevel>=t){const s="function"==typeof i?i():i;I.log(`${this.time} [${t}] ${s}`)}}}const Fn=function(t){const i=[];for(let s=0;s<t.length;s++)i.push(t[s].toString(16));return i};class Bn{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const i=["foreground","underline","italics","background","flash"];for(let s=0;s<i.length;s++){const e=i[s];t.hasOwnProperty(e)&&(this[e]=t[e])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class jn{constructor(){this.uchar=" ",this.penState=new Bn}reset(){this.uchar=" ",this.penState.reset()}setChar(t,i){this.uchar=t,this.penState.copy(i)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class _n{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Bn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Cn;t++)this.chars.push(new jn);this.logger=t}equals(t){for(let i=0;i<Cn;i++)if(!this.chars[i].equals(t.chars[i]))return!1;return!0}copy(t){for(let i=0;i<Cn;i++)this.chars[i].copy(t.chars[i])}isEmpty(){let t=!0;for(let i=0;i<Cn;i++)if(!this.chars[i].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Cn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Cn)}moveCursor(t){const i=this.pos+t;if(t>1)for(let t=this.pos+1;t<i+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(i)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const i=xn(t);this.pos>=Cn?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+i+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))}clearFromPos(t){let i;for(i=t;i<Cn;i++)this.chars[i].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let i=!0;for(let s=0;s<Cn;s++){const e=this.chars[s].uchar;" "!==e&&(i=!1),t.push(e)}return i?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}class Gn{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let i=0;i<Dn;i++)this.rows.push(new _n(t));this.logger=t}reset(){for(let t=0;t<Dn;t++)this.rows[t].clear();this.currRow=14}equals(t){let i=!0;for(let s=0;s<Dn;s++)if(!this.rows[s].equals(t.rows[s])){i=!1;break}return i}copy(t){for(let i=0;i<Dn;i++)this.rows[i].copy(t.rows[i])}isEmpty(){let t=!0;for(let i=0;i<Dn;i++)if(!this.rows[i].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,(()=>"pacData = "+JSON.stringify(t)));let i=t.row-1;if(this.nrRollUpRows&&i<this.nrRollUpRows-1&&(i=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==i){for(let t=0;t<Dn;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const e=s.rows[t].cueStartTime,n=this.logger.time;if(null!==e&&null!==n&&e<n)for(let e=0;e<this.nrRollUpRows;e++)this.rows[i-this.nrRollUpRows+e+1].copy(s.rows[t+e])}}this.currRow=i;const s=this.rows[this.currRow];if(null!==t.indent){const i=Math.max(t.indent-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}this.setPen({foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1})}setBkgData(t){this.logger.log(2,(()=>"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.rows.splice(this.currRow+1-this.nrRollUpRows,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const i=[];let s="",e=-1;for(let s=0;s<Dn;s++){const n=this.rows[s].getTextString();n&&(e=s+1,i.push(t?"Row "+e+": '"+n+"'":n.trim()))}return i.length>0&&(s=t?"["+i.join(" | ")+"]":i.join("\n")),s}getTextAndFormat(){return this.rows}}class Hn{constructor(t,i,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=i,this.mode=null,this.verbose=0,this.displayedMemory=new Gn(s),this.nonDisplayedMemory=new Gn(s),this.lastOutputScreen=new Gn(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 i=0;i<t.length;i++)this.writeScreen.insertChar(t[i]);const i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>i+": "+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 i={flash:!1};if(i.underline=t%2==1,i.italics=t>=46,i.italics)i.foreground="white";else{const s=Math.floor(t/2)-16;i.foreground=["white","green","blue","cyan","red","yellow","magenta"][s]}this.logger.log(2,"MIDROW: "+JSON.stringify(i)),this.writeScreen.setPen(i)}outputDataUpdate(t=!1){const i=this.logger.time;null!==i&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,i,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:i):this.cueStartTime=i,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 Kn{constructor(t,i,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const e=this.logger=new Un;this.channels=[null,new Hn(t,i,e),new Hn(t+1,s,e)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,i){this.channels[t].setHandler(i)}addData(t,i){this.logger.time=t;for(let t=0;t<i.length;t+=2){const s=127&i[t],e=127&i[t+1];let n=!1,r=null;if(0===s&&0===e)continue;this.logger.log(3,(()=>"["+Fn([i[t],i[t+1]])+"] -> ("+Fn([s,e])+")"));const h=this.cmdHistory;if(s>=16&&s<=31){if(zn(s,e,h)){Vn(null,null,h),this.logger.log(3,(()=>"Repeated command ("+Fn([s,e])+") is dropped"));continue}Vn(s,e,this.cmdHistory),n=this.parseCmd(s,e),n||(n=this.parseMidrow(s,e)),n||(n=this.parsePAC(s,e)),n||(n=this.parseBackgroundAttributes(s,e))}else Vn(null,null,h);if(!n&&(r=this.parseChars(s,e),r)){const t=this.currentChannel;t&&t>0?this.channels[t].insertChars(r):this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||r||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Fn([s,e])+" orig: "+Fn([i[t],i[t+1]])))}}parseCmd(t,i){if(!((20===t||28===t||21===t||29===t)&&i>=32&&i<=47||(23===t||31===t)&&i>=33&&i<=35))return!1;const s=20===t||21===t||23===t?1:2,e=this.channels[s];return 20===t||21===t||28===t||29===t?32===i?e.ccRCL():33===i?e.ccBS():34===i?e.ccAOF():35===i?e.ccAON():36===i?e.ccDER():37===i?e.ccRU(2):38===i?e.ccRU(3):39===i?e.ccRU(4):40===i?e.ccFON():41===i?e.ccRDC():42===i?e.ccTR():43===i?e.ccRTD():44===i?e.ccEDM():45===i?e.ccCR():46===i?e.ccENM():47===i&&e.ccEOC():e.ccTO(i-32),this.currentChannel=s,!0}parseMidrow(t,i){let s=0;if((17===t||25===t)&&i>=32&&i<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const e=this.channels[s];return!!e&&(e.ccMIDROW(i),this.logger.log(3,(()=>"MIDROW ("+Fn([t,i])+")")),!0)}return!1}parsePAC(t,i){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&i>=64&&i<=127||(16===t||24===t)&&i>=64&&i<=95))return!1;const e=t<=23?1:2;s=i>=64&&i<=95?1===e?In[t]:Pn[t]:1===e?Rn[t]:On[t];const n=this.channels[e];return!!n&&(n.setPAC(this.interpretPAC(s,i)),this.currentChannel=e,!0)}interpretPAC(t,i){let s;const e={color:null,italics:!1,indent:null,underline:!1,row:t};return s=i>95?i-96:i-64,e.underline=!(1&~s),s<=13?e.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(e.italics=!0,e.color="white"):e.indent=4*Math.floor((s-16)/2),e}parseChars(t,i){let s,e=null,n=null;if(t>=25?(s=2,n=t-8):(s=1,n=t),n>=17&&n<=19){let t;t=17===n?i+80:18===n?i+112:i+144,this.logger.log(2,(()=>"Special char '"+xn(t)+"' in channel "+s)),e=[t]}else t>=32&&t<=127&&(e=0===i?[t]:[t,i]);return e&&this.logger.log(3,(()=>"Char codes = "+Fn(e).join(","))),e}parseBackgroundAttributes(t,i){if(!((16===t||24===t)&&i>=32&&i<=47||(23===t||31===t)&&i>=45&&i<=47))return!1;let s;const e={};return 16===t||24===t?(s=Math.floor((i-32)/2),e.background=Nn[s],i%2==1&&(e.background=e.background+"_semi")):45===i?e.background="transparent":(e.foreground="black",47===i&&(e.underline=!0)),this.channels[t<=23?1:2].setBkgData(e),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const i=this.channels[t];i&&i.reset()}Vn(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let i=0;i<this.channels.length;i++){const s=this.channels[i];s&&s.cueSplitAtTime(t)}}}function Vn(t,i,s){s.a=t,s.b=i}function zn(t,i,s){return s.a===t&&s.b===i}class Wn{constructor(t,i){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=i}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,i,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=i,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Xn=function(){if(null!=X&&X.VTTCue)return self.VTTCue;const t=["","lr","rl"],i=["start","middle","end","left","right"];function s(t,i){if("string"!=typeof i)return!1;if(!Array.isArray(t))return!1;const s=i.toLowerCase();return!!~t.indexOf(s)&&s}function e(t){return s(i,t)}function n(t){let i=1;for(;i<arguments.length;i++){const s=arguments[i];for(const i in s)t[i]=s[i]}return t}function r(i,r,h){const o=this,a={enumerable:!0};o.hasBeenReset=!1;let l="",c=!1,u=i,d=r,f=h,v=null,p="",g=!0,m="auto",y="start",w=50,b="middle",k=50,S="middle";Object.defineProperty(o,"id",n({},a,{get:function(){return l},set:function(t){l=""+t}})),Object.defineProperty(o,"pauseOnExit",n({},a,{get:function(){return c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",n({},a,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},a,{get:function(){return d},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},a,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},a,{get:function(){return v},set:function(t){v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},a,{get:function(){return p},set:function(i){const e=function(i){return s(t,i)}(i);if(!1===e)throw new SyntaxError("An invalid or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},a,{get:function(){return g},set:function(t){g=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},a,{get:function(){return m},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},a,{get:function(){return y},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");y=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},a,{get:function(){return w},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},a,{get:function(){return b},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");b=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},a,{get:function(){return k},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");k=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},a,{get:function(){return S},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");S=i,this.hasBeenReset=!0}})),o.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class qn{decode(t,i){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Yn(t){function i(t,i,s,e){return 3600*(0|t)+60*(0|i)+(0|s)+parseFloat(e||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?i(s[2],s[3],0,s[4]):i(s[1],s[2],s[3],s[4]):null}class Jn{constructor(){this.values=Object.create(null)}set(t,i){this.get(t)||""===i||(this.values[t]=i)}get(t,i,s){return s?this.has(t)?this.values[t]:i[s]:this.has(t)?this.values[t]:i}has(t){return t in this.values}alt(t,i,s){for(let e=0;e<s.length;++e)if(i===s[e]){this.set(t,i);break}}integer(t,i){/^-?\d+$/.test(i)&&this.set(t,parseInt(i,10))}percent(t,i){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(i)){const s=parseFloat(i);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function Qn(t,i,s,e){const n=e?t.split(e):[t];for(const t in n){if("string"!=typeof n[t])continue;const e=n[t].split(s);2===e.length&&i(e[0],e[1])}}const Zn=new Xn(0,0,""),tr="middle"===Zn.align?"middle":"center";function ir(t,i,s){const e=t;function n(){const i=Yn(t);if(null===i)throw new Error("Malformed timestamp: "+e);return t=t.replace(/^[^\sa-zA-Z-]+/,""),i}function r(){t=t.replace(/^\s+/,"")}if(r(),i.startTime=n(),r(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+e);t=t.slice(3),r(),i.endTime=n(),r(),function(t,i){const e=new Jn;Qn(t,(function(t,i){let n;switch(t){case"region":for(let n=s.length-1;n>=0;n--)if(s[n].id===i){e.set(t,s[n].region);break}break;case"vertical":e.alt(t,i,["rl","lr"]);break;case"line":n=i.split(","),e.integer(t,n[0]),e.percent(t,n[0])&&e.set("snapToLines",!1),e.alt(t,n[0],["auto"]),2===n.length&&e.alt("lineAlign",n[1],["start",tr,"end"]);break;case"position":n=i.split(","),e.percent(t,n[0]),2===n.length&&e.alt("positionAlign",n[1],["start",tr,"end","line-left","line-right","auto"]);break;case"size":e.percent(t,i);break;case"align":e.alt(t,i,["start",tr,"end","left","right"])}}),/:/,/\s/),i.region=e.get("region",null),i.vertical=e.get("vertical","");let n=e.get("line","auto");"auto"===n&&-1===Zn.line&&(n=-1),i.line=n,i.lineAlign=e.get("lineAlign","start"),i.snapToLines=e.get("snapToLines",!0),i.size=e.get("size",100),i.align=e.get("align",tr);let r=e.get("position","auto");"auto"===r&&50===Zn.position&&(r="start"===i.align||"left"===i.align?0:"end"===i.align||"right"===i.align?100:50),i.position=r}(t,i)}function sr(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class er{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new qn,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const i=this;function s(){let t=i.buffer,s=0;for(t=sr(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const e=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,i.buffer=t.slice(s),e}t&&(i.buffer+=i.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===i.state){if(!/\r\n|\n/.test(i.buffer))return this;t=s();const e=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==e||!e[0])throw new Error("Malformed WebVTT signature.");i.state="HEADER"}let e=!1;for(;i.buffer;){if(!/\r\n|\n/.test(i.buffer))return this;switch(e?e=!1:t=s(),i.state){case"HEADER":/:/.test(t)?Qn(t,(function(){}),/:/):t||(i.state="ID");continue;case"NOTE":t||(i.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){i.state="NOTE";break}if(!t)continue;if(i.cue=new Xn(0,0,""),i.state="CUE",-1===t.indexOf("--\x3e")){i.cue.id=t;continue}case"CUE":if(!i.cue){i.state="BADCUE";continue}try{ir(t,i.cue,i.regionList)}catch(t){i.cue=null,i.state="BADCUE";continue}i.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(e=!0)){i.oncue&&i.cue&&i.oncue(i.cue),i.cue=null,i.state="ID";continue}if(null===i.cue)continue;i.cue.text&&(i.cue.text+="\n"),i.cue.text+=t}continue;case"BADCUE":t||(i.state="ID")}}}catch(t){"CUETEXT"===i.state&&i.cue&&i.oncue&&i.oncue(i.cue),i.cue=null,i.state="INITIAL"===i.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(i){t.onparsingerror&&t.onparsingerror(i)}return t.onflush&&t.onflush(),this}}const nr=/\r\n|\n\r|\n|\r/g,rr=function(t,i,s=0){return t.slice(s,s+i.length)===i},hr=function(t){let i=5381,s=t.length;for(;s;)i=33*i^t.charCodeAt(--s);return(i>>>0).toString()};function or(t,i,s){return hr(t.toString())+hr(i.toString())+hr(s)}const ar="stpp.ttml.im1t",lr=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,cr=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ur={left:"start",center:"center",right:"end",start:"start",end:"end"};function dr(t,i,s,e){const n=Ot(new Uint8Array(t),["mdat"]);if(0===n.length)return void e(new Error("Could not parse IMSC1 mdat"));const r=n.map((t=>St(t))),h=function(t,i,s=1,e=!1){return tn(t,1,1/s,e)}(i.baseTime,0,i.timescale);try{r.forEach((t=>s(function(t,i){const s=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const e={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(e).reduce(((t,i)=>(t[i]=s.getAttribute(`ttp:${i}`)||e[i],t)),{}),r="preserve"!==s.getAttribute("xml:space"),h=vr(fr(s,"styling","style")),o=vr(fr(s,"layout","region")),a=fr(s,"body","[begin]");return[].map.call(a,(t=>{const s=pr(t,r);if(!s||!t.hasAttribute("begin"))return null;const e=yr(t.getAttribute("begin"),n),a=yr(t.getAttribute("dur"),n);let l=yr(t.getAttribute("end"),n);if(null===e)throw mr(t);if(null===l){if(null===a)throw mr(t);l=e+a}const c=new Xn(e-i,l-i,s);c.id=or(c.startTime,c.endTime,c.text);const u=function(t,i,s){const e="http://www.w3.org/ns/ttml#styling";let n=null;const r=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return r&&s.hasOwnProperty(r)&&(n=s[r]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(((s,r)=>{const h=gr(i,e,r)||gr(t,e,r)||gr(n,e,r);return h&&(s[r]=h),s}),{})}(o[t.getAttribute("region")],h[t.getAttribute("style")],h),{textAlign:d}=u;if(d){const t=ur[d];t&&(c.lineAlign=t),c.align=d}return S(c,u),c})).filter((t=>null!==t))}(t,h))))}catch(t){e(t)}}function fr(t,i,s){const e=t.getElementsByTagName(i)[0];return e?[].slice.call(e.querySelectorAll(s)):[]}function vr(t){return t.reduce(((t,i)=>{const s=i.getAttribute("xml:id");return s&&(t[s]=i),t}),{})}function pr(t,i){return[].slice.call(t.childNodes).reduce(((t,s,e)=>{var n;return"br"===s.nodeName&&e?t+"\n":null!=(n=s.childNodes)&&n.length?pr(s,i):i?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function gr(t,i,s){return t&&t.hasAttributeNS(i,s)?t.getAttributeNS(i,s):null}function mr(t){return new Error(`Could not parse ttml timestamp ${t}`)}function yr(t,i){if(!t)return null;let s=Yn(t);return null===s&&(lr.test(t)?s=function(t,i){const s=lr.exec(t);return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+((0|s[4])+(0|s[5])/i.subFrameRate)/i.frameRate}(t,i):cr.test(t)&&(s=function(t,i){const s=cr.exec(t),e=Number(s[1]);switch(s[2]){case"h":return 3600*e;case"m":return 60*e;case"ms":return 1e3*e;case"f":return e/i.frameRate;case"t":return e/i.tickRate}return e}(t,i))),s}function wr(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function br(t,i){return!!t&&t.kind===wr(i)&&Tn(i,t)}class kr{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(A.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.BUFFER_CODECS,this.onBufferCodecs,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(A.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.BUFFER_CODECS,this.onBufferCodecs,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,i){const s=this.hls.levels[i.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,i){this.media=i.media instanceof HTMLVideoElement?i.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,i){const s=this.hls;this.restrictedLevels=[],this.firstLevel=i.firstLevel,s.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onLevelsUpdated(t,i){this.timer&&T(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,i){this.hls.config.capLevelToPlayerSize&&i.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 i=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&I.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),i.autoLevelCapping=s,i.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=i.autoLevelCapping}}}getMaxLevel(t){const i=this.hls.levels;if(!i.length)return-1;const s=i.filter(((i,s)=>this.isLevelAllowed(i)&&s<=t));return this.clientRect=null,kr.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,i={width:0,height:0};if(t){const s=t.getBoundingClientRect();i.width=s.width,i.height=s.height,i.width||i.height||(i.width=s.right-s.left||t.width||0,i.height=s.bottom-s.top||t.height||0)}return this.clientRect=i,i}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((i=>t.bitrate===i.bitrate&&t.width===i.width&&t.height===i.height))}static getMaxLevelByMediaSize(t,i,s){if(null==t||!t.length)return-1;let e=t.length-1;const n=Math.max(i,s);for(let i=0;i<t.length;i+=1){const s=t[i];if((s.width>=n||s.height>=n)&&(r=s,!(h=t[i+1])||r.width!==h.width||r.height!==h.height)){e=i;break}}var r,h;return e}}const Sr="[eme]";class Tr{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=Tr.CDMCleanupPromise?[Tr.CDMCleanupPromise]:[],this.debug=I.debug.bind(I,Sr),this.log=I.log.bind(I,Sr),this.warn=I.warn.bind(I,Sr),this.error=I.error.bind(I,Sr),this.onMediaEncrypted=t=>{const{initDataType:i,initData:s}=t,e=`"${t.type}" event: init data type: "${i}"`;if(this.debug(e),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=et(this.config));const i=t.map(st).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(i)}this.keyFormatPromise.then((n=>{const r=tt(n);let h,o;if("sinf"===i){if(r!==q.FAIRPLAY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${r}`);const n=xt(new Uint8Array(s));try{const t=Gt(z(JSON.parse(n).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=t.subarray(8,24),o=q.FAIRPLAY}catch(t){return void this.warn(`${e} Failed to parse sinf: ${t}`)}}else{if(r!==q.WIDEVINE&&r!==q.PLAYREADY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${r}`);const n=function(t){const i=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let e=0;for(;e+32<s;){const s=qt(new DataView(t,e));i.push(s),e+=s.size}}return i}(s),a=n.filter((t=>!!t.systemId&&it(t.systemId)===r));a.length>1&&this.warn(`${e} Using first of ${a.length} pssh found for selected key-system ${r}`);const l=a[0];if(!l)return void(0===n.length||n.some((t=>!t.systemId))?this.warn(`${e} contains incomplete or invalid pssh data`):this.log(`ignoring ${e} for ${n.map((t=>it(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=it(l.systemId),0===l.version&&l.data)if(o===q.WIDEVINE){const t=l.data.length-22;h=l.data.subarray(t,t+16)}else o===q.PLAYREADY&&(h=ht(l.data))}if(!o||!h)return void this.log(`Unable to handle ${e} with key-system ${r}`);const a=Et(h),{keyIdToKeySessionPromise:l,mediaKeySessions:c}=this;let u=l[a];for(let t=0;t<c.length;t++){const e=c[t],n=e.decryptdata;if(!n.keyId)continue;const r=Et(n.keyId);if(a===r||-1!==n.uri.replace(/-/g,"").indexOf(a)){if(u=l[r],n.pssh)break;delete l[r],n.pssh=new Uint8Array(s),n.keyId=h,u=l[a]=u.then((()=>this.generateRequestWithPreferredKeySession(e,i,s,"encrypted-event-key-match"))),u.catch((t=>this.handleError(t)));break}}if(!u){if(o!==r)return void this.log(`Ignoring "${e}" with ${o} init data for selected key-system ${r}`);u=l[a]=this.getKeySystemSelectionPromise([o]).then((({keySystem:t,mediaKeys:e})=>{var n;this.throwIfDestroyed();const r=new Jt("ISO-23001-7",a,null!=(n=st(t))?n:"");return r.pssh=new Uint8Array(s),r.keyId=h,this.attemptSetMediaKeys(t,e).then((()=>{this.throwIfDestroyed();const n=this.createMediaKeySessionContext({decryptdata:r,keySystem:t,mediaKeys:e});return this.generateRequestWithPreferredKeySession(n,i,s,"encrypted-event-no-match")}))})),u.catch((t=>this.handleError(t)))}}))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},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.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(A.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(A.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(A.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(A.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:i,widevineLicenseUrl:s}=this.config,e=i[t];return e?e.licenseUrl:t===q.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(t){const i=this.getLicenseServerUrl(t);if(void 0===i)throw new Error(`no license server URL configured for key-system "${t}"`);return i}getServerCertificateUrl(t){const{drmSystems:i}=this.config,s=i[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const i=this.hls.levels,s=(t,i,s)=>!!t&&s.indexOf(t)===i,e=i.map((t=>t.audioCodec)).filter(s),n=i.map((t=>t.videoCodec)).filter(s);return e.length+n.length===0&&n.push("avc1.42e01e"),new Promise(((i,s)=>{const r=t=>{const h=t.shift();this.getMediaKeysPromise(h,e,n).then((t=>i({keySystem:h,mediaKeys:t}))).catch((i=>{t.length?r(t):s(i instanceof $r?i:new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:i,fatal:!0},i.message))}))};r(t)}))}requestMediaKeySystemAccess(t,i){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===nt&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,i)}getMediaKeysPromise(t,i,s){const e=function(t,i,s,e){let n;switch(t){case q.FAIRPLAY:n=["cenc","sinf"];break;case q.WIDEVINE:case q.PLAYREADY:n=["cenc"];break;case q.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,i,s,e){return[{initDataTypes:t,persistentState:e.persistentState||"optional",distinctiveIdentifier:e.distinctiveIdentifier||"optional",sessionTypes:e.sessionTypes||[e.sessionType||"temporary"],audioCapabilities:i.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:e.audioRobustness||"",encryptionScheme:e.audioEncryptionScheme||null}))),videoCapabilities:s.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:e.videoRobustness||"",encryptionScheme:e.videoEncryptionScheme||null})))}]}(n,i,s,e)}(t,i,s,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t];let r=null==n?void 0:n.keySystemAccess;if(!r){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(e)}`),r=this.requestMediaKeySystemAccess(t,e);const i=this.keySystemAccessPromises[t]={keySystemAccess:r};return r.catch((i=>{this.log(`Failed to obtain access to key-system "${t}": ${i}`)})),r.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const e=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),i.mediaKeys=s.createMediaKeys().then((i=>(this.log(`Media-keys created for "${t}"`),e.then((s=>s?this.setMediaKeysServerCertificate(i,t,s):i))))),i.mediaKeys.catch((i=>{this.error(`Failed to create media-keys for "${t}"}: ${i}`)})),i.mediaKeys}))}return r.then((()=>n.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:i,mediaKeys:s}){this.log(`Creating key-system session "${i}" keyId: ${Et(t.keyId||[])}`);const e=s.createSession(),n={decryptdata:t,keySystem:i,mediaKeys:s,mediaKeysSession:e,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(t){const i=t.decryptdata;if(i.pssh){const s=this.createMediaKeySessionContext(t),e=this.getKeyIdString(i);this.keyIdToKeySessionPromise[e]=this.generateRequestWithPreferredKeySession(s,"cenc",i.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 Et(t.keyId)}updateKeySession(t,i){var s;const e=t.mediaKeysSession;return this.log(`Updating key-session "${e.sessionId}" for keyID ${Et((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${i?i.byteLength:i})`),e.update(i)}selectKeySystemFormat(t){const i=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((i,s)=>{const e=et(this.config),n=t.map(tt).filter((t=>!!t&&-1!==e.indexOf(t)));return this.getKeySystemSelectionPromise(n).then((({keySystem:t})=>{const e=st(t);e?i(e):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)}))}loadKey(t){const i=t.keyInfo.decryptdata,s=this.getKeyIdString(i),e=`(keyId: ${s} format: "${i.keyFormat}" method: ${i.method} uri: ${i.uri})`;this.log(`Starting session for key ${e}`);let n=this.keyIdToKeySessionPromise[s];return n||(n=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(i).then((({keySystem:s,mediaKeys:n})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${e}`),this.attemptSetMediaKeys(s,n).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:n,decryptdata:i});return this.generateRequestWithPreferredKeySession(t,"cenc",i.pssh,"playlist-key")}))))),n.catch((t=>this.handleError(t)))),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),this.hls.trigger(A.ERROR,t instanceof $r?t.data:{type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const i=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[i];if(!s){const i=tt(t.keyFormat),s=i?[i]:et(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=et(this.config)),0===t.length)throw new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,i){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const e=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(i)}));return this.setMediaKeysQueue.push(e),e.then((()=>{this.log(`Media-keys set for "${t}"`),s.push(e),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===s.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,i,s,e){var n,r;const h=null==(n=this.config.drmSystems)||null==(r=n[t.keySystem])?void 0:r.generateRequest;if(h)try{const e=h.call(this.hls,i,s,t);if(!e)throw new Error("Invalid response from configured generateRequest filter");i=e.initDataType,s=t.decryptdata.pssh=e.initData?new Uint8Array(e.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 "${e}" (no initData)`),Promise.resolve(t);const a=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${e}": ${a} (init data type: ${i} length: ${s?s.byteLength:null})`);const l=new wn,c=t._onmessage=i=>{const s=t.mediaKeysSession;if(!s)return void l.emit("error",new Error("invalid state"));const{messageType:e,message:n}=i;this.log(`"${e}" message event for session "${s.sessionId}" message size: ${n.byteLength}`),"license-request"===e||"license-renewal"===e?this.renewLicense(t,n).catch((t=>{this.handleError(t),l.emit("error",t)})):"license-release"===e?t.keySystem===q.FAIRPLAY&&(this.updateKeySession(t,W("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${e}"`)},u=t._onkeystatuseschange=()=>{if(!t.mediaKeysSession)return void l.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const i=t.keyStatus;l.emit("keyStatus",i),"expired"===i&&(this.warn(`${t.keySystem} expired for key ${a}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",c),t.mediaKeysSession.addEventListener("keystatuseschange",u);const d=new Promise(((t,i)=>{l.on("error",i),l.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?i(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?i(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?i(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return t.mediaKeysSession.generateRequest(i,s).then((()=>{var i;this.log(`Request generated for key-session "${null==(i=t.mediaKeysSession)?void 0:i.sessionId}" keyId: ${a}`)})).catch((t=>{throw new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>d)).catch((i=>{throw l.removeAllListeners(),this.removeSession(t),i})).then((()=>(l.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((i,s)=>{this.log(`key status change "${i}" for keyStatuses keyId: ${Et("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Et(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=i}))}fetchServerCertificate(t){const i=this.config,s=new(0,i.loader)(i),e=this.getServerCertificateUrl(t);return e?(this.log(`Fetching server certificate for "${t}"`),new Promise(((n,r)=>{const h={responseType:"arraybuffer",url:e},o=i.certLoadPolicy.default;s.load(h,{loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},{onSuccess:t=>{n(t.data)},onError:(i,s,n)=>{r(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:k({url:h.url,data:void 0},i)},`"${t}" certificate request failed (${e}). Status: ${i.code} (${i.text})`))},onTimeout:(i,s,n)=>{r(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:h.url,data:void 0}},`"${t}" certificate request timed out (${e})`))},onAbort:()=>{r(new Error("aborted"))}})}))):Promise.resolve()}setMediaKeysServerCertificate(t,i,s){return new Promise(((e,n)=>{t.setServerCertificate(s).then((n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${i}"`),e(t)})).catch((t=>{n(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,i){return this.requestLicense(t,new Uint8Array(i)).then((i=>this.updateKeySession(t,new Uint8Array(i)).catch((t=>{throw new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,i){const s=String.fromCharCode.apply(null,new Uint16Array(i.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),i;const e=(new DOMParser).parseFromString(s,"application/xml"),n=e.querySelectorAll("HttpHeader");if(n.length>0){let i;for(let s=0,e=n.length;s<e;s++){var r,h;i=n[s];const e=null==(r=i.querySelector("name"))?void 0:r.textContent,o=null==(h=i.querySelector("value"))?void 0:h.textContent;e&&o&&t.setRequestHeader(e,o)}}const o=e.querySelector("Challenge"),a=null==o?void 0:o.textContent;if(!a)throw new Error("Cannot find <Challenge> in key message");return W(atob(a))}setupLicenseXHR(t,i,s,e){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,i,s,e)})).catch((r=>{if(!s.decryptdata)throw r;return t.open("POST",i,!0),n.call(this.hls,t,i,s,e)})).then((s=>(t.readyState||t.open("POST",i,!0),{xhr:t,licenseChallenge:s||e}))):(t.open("POST",i,!0),Promise.resolve({xhr:t,licenseChallenge:e}))}requestLicense(t,i){const s=this.config.keyLoadPolicy.default;return new Promise(((e,n)=>{const r=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${r}`);const h=new XMLHttpRequest;h.responseType="arraybuffer",h.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(4===h.readyState)if(200===h.status){this._requestLicenseFailureCount=0;let i=h.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);const s=this.config.licenseResponseCallback;if(s)try{i=s.call(this.hls,h,r,t)}catch(t){this.error(t)}e(i)}else{const o=s.errorRetry,a=o?o.maxNumRetry:0;this._requestLicenseFailureCount++,this._requestLicenseFailureCount>a||h.status>=400&&h.status<500?n(new $r({type:M.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:h,response:{url:r,data:void 0,code:h.status,text:h.statusText}},`License Request XHR failed (${r}). Status: ${h.status} (${h.statusText})`)):(this.warn(`Retrying license request, ${a-this._requestLicenseFailureCount+1} attempts left`),this.requestLicense(t,i).then(e,n))}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=h,this.setupLicenseXHR(h,r,t,i).then((({xhr:i,licenseChallenge:s})=>{t.keySystem==q.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(i,s)),i.send(s)}))}))}onMediaAttached(t,i){if(!this.config.emeEnabled)return;const s=i.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,i=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=i.length;Tr.CDMCleanupPromise=Promise.all(i.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"),i.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:i}){if(i&&this.config.emeEnabled&&!this.keyFormatPromise){const t=i.reduce(((t,i)=>(-1===t.indexOf(i.keyFormat)&&t.push(i.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:i,licenseXhr:s}=t;if(i){this.log(`Remove licenses and keys and close session ${i.sessionId}`),t._onmessage&&(i.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const e=this.mediaKeySessions.indexOf(t);return e>-1&&this.mediaKeySessions.splice(e,1),i.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>i.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}Tr.CDMCleanupPromise=void 0;class $r extends Error{constructor(t,i){super(i),this.data=void 0,t.error||(t.error=new Error(i)),this.data=t,t.err=t.error}}var Er,Ar,Mr;!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"}(Er||(Er={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(Ar||(Ar={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(Mr||(Mr={}));const Lr={[Mr.OBJECT]:["br","d","ot","tb"],[Mr.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Mr.SESSION]:["cid","pr","sf","sid","st","v"],[Mr.STATUS]:["bs","rtp"]};class xr{constructor(t,i){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof xr?t:new xr(t)))),this.value=t,this.params=i}}class Dr{constructor(t){this.description=void 0,this.description=t}}const Cr="Dict";const Ir="Bare Item",Rr="Boolean",Pr="Byte Sequence",Or="Decimal",Nr="Integer",Ur=/[\x00-\x1f\x7f]+/,Fr="Token",Br="Key";function jr(t,i,s){return function(t,i,s,e){return new Error(`failed to ${t} "${n=i,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n)}" as ${s}`,{cause:e});var n}("serialize",t,i,s)}function _r(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw jr(t,Nr);return t.toString()}function Gr(t,i){if(t<0)return-Gr(-t,i);const s=Math.pow(10,i);if(Math.abs(t*s%1-.5)<Number.EPSILON){const i=Math.floor(t*s);return(i%2==0?i:i+1)/s}return Math.round(t*s)/s}function Hr(t){const i=Gr(t,3);if(Math.floor(Math.abs(i)).toString().length>12)throw jr(t,Or);const s=i.toString();return s.includes(".")?s:`${s}.0`}const Kr="String";function Vr(t){const i=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw jr(i,Fr);return i}function zr(t){switch(typeof t){case"number":if(!T(t))throw jr(t,Ir);return Number.isInteger(t)?_r(t):Hr(t);case"string":return function(t){if(Ur.test(t))throw jr(t,Kr);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Vr(t);case"boolean":return function(t){if("boolean"!=typeof t)throw jr(t,Rr);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${_r(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return function(t){if(!1===ArrayBuffer.isView(t))throw jr(t,Pr);return`:${i=t,btoa(String.fromCharCode(...i))}:`;var i}(t);if(t instanceof Dr)return Vr(t);default:throw jr(t,Ir)}}function Wr(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw jr(t,Br);return t}function Xr(t){return null==t?"":Object.entries(t).map((([t,i])=>!0===i?`;${Wr(t)}`:`;${Wr(t)}=${zr(i)}`)).join("")}function qr(t){return t instanceof xr?`${zr(t.value)}${Xr(t.params)}`:zr(t)}const Yr=t=>"ot"===t||"sf"===t||"st"===t,Jr=t=>"number"==typeof t?T(t):null!=t&&""!==t&&!1!==t,Qr=t=>Math.round(t),Zr=t=>100*Qr(t/100),th={br:Qr,d:Qr,bl:Zr,dl:Zr,mtp:Zr,nor:(t,i)=>(null!=i&&i.baseUrl&&(t=function(t,i){const s=new URL(t),e=new URL(i);if(s.origin!==e.origin)return t;const n=s.pathname.split("/").slice(1),r=e.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")}(t,i.baseUrl)),encodeURIComponent(t)),rtp:Zr,tb:Qr};function ih(t,i={}){return t?function(t,i){return function(t,i={whitespace:!0}){if("object"!=typeof t)throw jr(t,Cr);const s=t instanceof Map?t.entries():Object.entries(t),e=null!=i&&i.whitespace?" ":"";return Array.from(s).map((([t,i])=>{i instanceof xr==0&&(i=new xr(i));let s=Wr(t);var e;return!0===i.value?s+=Xr(i.params):(s+="=",Array.isArray(i.value)?s+=`(${(e=i).value.map(qr).join(" ")})${Xr(e.params)}`:s+=qr(i)),s})).join(`,${e}`)}(t,i)}(function(t,i){const s={};if(null==t||"object"!=typeof t)return s;const e=Object.keys(t).sort(),n=S({},th,null==i?void 0:i.formatters),r=null==i?void 0:i.filter;return e.forEach((e=>{if(null!=r&&r(e))return;let h=t[e];const o=n[e];o&&(h=o(h,i)),"v"===e&&1===h||"pr"==e&&1===h||Jr(h)&&(Yr(e)&&"string"==typeof h&&(h=new Dr(h)),s[e]=h)})),s}(t,i),S({whitespace:!1},i)):""}const sh=/CMCD=[^&#]+/;function eh(t,i,s,e){t&&Object.keys(i).forEach((n=>{const r=t.filter((t=>t.groupId===n)).map((t=>{const r=S({},t);return r.details=void 0,r.attrs=new O(r.attrs),r.url=r.attrs.URI=nh(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),r.groupId=r.attrs["GROUP-ID"]=i[n],r.attrs["PATHWAY-ID"]=e,r}));t.push(...r)}))}function nh(t,i,s,e){const{HOST:n,PARAMS:r,[s]:h}=e;let o;i&&(o=null==h?void 0:h[i],o&&(t=o));const a=new self.URL(t);return n&&!o&&(a.host=n),r&&Object.keys(r).sort().forEach((t=>{t&&a.searchParams.set(t,r[t])})),a.href}const rh=/^age:\s*[\d.]+\s*$/im;class hh{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 F,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,i,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=i,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:i}=this;if(!t||!i)return;const s=this.loader=new self.XMLHttpRequest,e=this.stats;e.loading.first=0,e.loaded=0,e.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return n(s,i.url)})).catch((()=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",i.url,!0),n(s,i.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,i,t)})).catch((t=>{this.callbacks.onError({code:s.status,text:t.message},i,s,e)})):this.openAndSendXhr(s,i,t)}openAndSendXhr(t,i,s){t.readyState||t.open("GET",i.url,!0);const e=i.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:r}=s.loadPolicy;if(e)for(const i in e)t.setRequestHeader(i,e[i]);i.rangeEnd&&t.setRequestHeader("Range","bytes="+i.rangeStart+"-"+(i.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=i.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&T(n)?n:r,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:i,stats:s}=this;if(!t||!i)return;const e=i.readyState,n=this.config;if(!s.aborted&&e>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===e)){self.clearTimeout(this.requestTimeout),i.onreadystatechange=null,i.onprogress=null;const e=i.status,r="text"===i.responseType?i.responseText:null;if(e>=200&&e<300){const n=null!=r?r:i.response;if(null!=n){if(s.loading.end=Math.max(self.performance.now(),s.loading.first),s.loaded=s.total="arraybuffer"===i.responseType?n.byteLength:n.length,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const r=this.callbacks.onProgress;if(r&&r(s,t,n,i),!this.callbacks)return;return void this.callbacks.onSuccess({url:i.responseURL,data:n,code:e},s,t,i)}}const h=n.loadPolicy.errorRetry;vs(h,s.retry,!1,{url:t.url,data:void 0,code:e})?this.retry(h):(I.error(`${e} while loading ${t.url}`),this.callbacks.onError({code:e,text:i.statusText},t,i,s))}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(vs(t,this.stats.retry,!0))this.retry(t);else{var i;I.warn(`timeout while loading ${null==(i=this.context)?void 0:i.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:i,stats:s}=this;this.retryDelay=ds(t,s.retry),s.retry++,I.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==i?void 0:i.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 i=this.stats;i.loaded=t.loaded,t.lengthComputable&&(i.total=t.total)}getCacheAge(){let t=null;if(this.loader&&rh.test(this.loader.getAllResponseHeaders())){const i=this.loader.getResponseHeader("age");t=i?parseFloat(i):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 oh=/(\d+)-(\d+)\/(\d+)/;class ah{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||lh,this.controller=new self.AbortController,this.stats=new F}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,i,s){const e=this.stats;if(e.loading.start)throw new Error("Loader can only be used once.");e.loading.start=self.performance.now();const n=function(t,i){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:i,headers:new self.Headers(S({},t.headers))};return t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),s}(t,this.controller.signal),r=s.onProgress,h="arraybuffer"===t.responseType,o=h?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:l}=i.loadPolicy;this.context=t,this.config=i,this.callbacks=s,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),i.timeout=a&&T(a)?a:l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(e,t,this.response)}),i.timeout),self.fetch(this.request).then((n=>{this.response=this.loader=n;const o=Math.max(self.performance.now(),e.loading.start);if(self.clearTimeout(this.requestTimeout),i.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(e,t,this.response)}),l-(o-e.loading.start)),!n.ok){const{status:t,statusText:i}=n;throw new ch(i||"fetch, bad network response",t,n)}return e.loading.first=o,e.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const i=oh.exec(t);if(i)return parseInt(i[2])-parseInt(i[1])+1}(i);if(T(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(n.headers)||e.total,r&&T(i.highWaterMark)?this.loadProgressively(n,e,t,i.highWaterMark,r):h?n.arrayBuffer():"json"===t.responseType?n.json():n.text()})).then((n=>{const h=this.response;if(!h)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),e.loading.end=Math.max(self.performance.now(),e.loading.first);const a=n[o];a&&(e.loaded=e.total=a);const l={url:h.url,data:n,code:h.status};r&&!T(i.highWaterMark)&&r(e,t,n,h),s.onSuccess(l,e,t,h)})).catch((i=>{self.clearTimeout(this.requestTimeout),e.aborted||s.onError({code:i&&i.code||0,text:i?i.message:null},t,i?i.details:null,e)}))}getCacheAge(){let t=null;if(this.response){const i=this.response.headers.get("age");t=i?parseFloat(i):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,i,s,e=0,n){const r=new ve,h=t.body.getReader(),o=()=>h.read().then((h=>{if(h.done)return r.dataLength&&n(i,s,r.flush(),t),Promise.resolve(new ArrayBuffer(0));const a=h.value,l=a.length;return i.loaded+=l,l<e||r.dataLength?(r.push(a),r.dataLength>=e&&n(i,s,r.flush(),t)):n(i,s,a,t),o()})).catch((()=>Promise.reject()));return o()}}function lh(t,i){return new self.Request(t.url,i)}class ch extends Error{constructor(t,i,s){super(t),this.code=void 0,this.details=void 0,this.code=i,this.details=s}}const uh=/\s/,dh={newCue(t,i,s,e){const n=[];let r,h,o,a,l;const c=self.VTTCue||self.TextTrackCue;for(let d=0;d<e.rows.length;d++)if(r=e.rows[d],o=!0,a=0,l="",!r.isEmpty()){var u;for(let t=0;t<r.chars.length;t++)uh.test(r.chars[t].uchar)&&o?a++:(l+=r.chars[t].uchar,o=!1);r.cueStartTime=i,i===s&&(s+=1e-4),a>=16?a--:a++;const e=sr(l.trim()),f=or(i,s,e);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(h=new c(i,s,e),h.id=f,h.line=d+1,h.align="left",h.position=10+Math.min(80,10*Math.floor(8*a/32)),n.push(h))}return t&&n.length&&(n.sort(((t,i)=>"auto"===t.line||"auto"===i.line?0:t.line>8&&i.line>8?i.line-t.line:t.line-i.line)),n.forEach((i=>Bi(t,i)))),n}},fh=k(k({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:hh,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:i,hls:s}=this,{autoLevelEnabled:e,media:n}=s;if(!t||!n)return;const r=performance.now(),h=i?i.stats:t.stats,o=i?i.duration:t.duration,a=r-h.loading.start,l=s.minAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||t.level<=l)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!e||n.paused||!n.playbackRate||!n.readyState)return;const c=s.mainForwardBufferInfo;if(null===c)return;const u=this.bwEstimator.getEstimateTTFB(),d=Math.abs(n.playbackRate);if(a<=Math.max(u,o/(2*d)*1e3))return;const f=c.len/d,v=h.loading.first?h.loading.first-h.loading.start:-1,p=h.loaded&&v>-1,g=this.getBwEstimate(),m=s.levels,y=h.total||Math.max(h.loaded,Math.round(o*m[t.level].averageBitrate/8));let w=p?a-v:a;w<1&&p&&(w=Math.min(a,8*h.loaded/g));const b=p?1e3*h.loaded/w:0,k=b?(y-h.loaded)/b:8*y/g+u/1e3;if(k<=f)return;const S=b?8*b:g;let $,E=Number.POSITIVE_INFINITY;for($=t.level-1;$>l&&(E=this.getTimeToLoadFrag(u/1e3,S,o*m[$].maxBitrate,!m[$].details),!(E<f));$--);if(E>=k)return;if(E>10*o)return;s.nextLoadLevel=s.nextAutoLevel=$,p?this.bwEstimator.sample(a-Math.min(u,v),h.loaded):this.bwEstimator.sampleTTFB(a);const M=m[$].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>M&&this.resetEstimator(M),this.clearTimer(),I.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${k.toFixed(3)} s\n Estimated load time for down switch fragment: ${E.toFixed(3)} s\n TTFB estimate: ${0|v} ms\n Current BW estimate: ${T(g)?0|g:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${$} @ ${0|M} bps`),s.trigger(A.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:h})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(I.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 ks(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.FRAG_LOADING,this.onFragLoading,this),t.on(A.FRAG_LOADED,this.onFragLoaded,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this),t.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.FRAG_LOADING,this.onFragLoading,this),t.off(A.FRAG_LOADED,this.onFragLoaded,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this),t.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(A.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,i){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,i){const s=i.frag;var e;this.ignoreFragment(s)||(s.bitrateTest||(this.fragCurrent=s,this.partCurrent=null!=(e=i.part)?e:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(t,i){this.clearTimer()}onError(t,i){if(!i.fatal)switch(i.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{const t=i.frag,{fragCurrent:s,partCurrent:e}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const i=performance.now(),s=e?e.stats:t.stats,n=i-s.loading.start,r=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&r>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(n-Math.min(t,r),s.loaded)}else this.bwEstimator.sampleTTFB(n)}break}}}getTimeToLoadFrag(t,i,s,e){return t+s/i+(e?this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:e}=i.stats,n=e.end-e.start;T(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(t,{frag:i,part:s}){const e=s?s.stats:i.stats;if(i.type===Ii&&this.bwEstimator.sampleTTFB(e.loading.first-e.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=this.hls.levels[i.level],n=(t.loaded?t.loaded.bytes:0)+e.loaded,r=(t.loaded?t.loaded.duration:0)+(s?s.duration:i.duration);t.loaded={bytes:n,duration:r},t.realBitrate=Math.round(8*n/r)}i.bitrateTest?(this.onFragBuffered(A.FRAG_BUFFERED,{stats:e,frag:i,part:s,id:i.type}),i.bitrateTest=!1):this.lastLoadedFragLevel=i.level}}onFragBuffered(t,i){const{frag:s,part:e}=i,n=null!=e&&e.stats.loaded?e.stats:s.stats;if(n.aborted)return;if(this.ignoreFragment(s))return;const r=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(r,n.loaded),n.bwEstimate=this.getBwEstimate(),this.bitrateTestDelay=s.bitrateTest?r/1e3:0}ignoreFragment(t){return t.type!==Ii||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,s=this.getBwEstimate(),e=this.findBestLevel(s,i,t,0,this.hls.config.maxStarvationDelay,1,1);if(e>-1)return e;const n=this.hls.firstLevel,r=Math.min(Math.max(n,i),t);return I.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${r}`),r}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||i&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const e=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const i=this.hls.levels;if(i.length>Math.max(t,e)&&i[t].loadError<=i[e].loadError)return t}return this._nextAutoLevel=e,this.nextAutoLevelKey=this.getAutoLevelKey(),e}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:i,hls:s}=this,{maxAutoLevel:e,config:n,minAutoLevel:r}=s,h=i?i.duration:t?t.duration:0,o=this.getBwEstimate(),a=this.getStarvationDelay();let l=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(a){const t=this.findBestLevel(o,r,e,a,0,l,c);if(t>=0)return t}let u=h?Math.min(h,n.maxStarvationDelay):n.maxStarvationDelay;if(!a){const t=this.bitrateTestDelay;t&&(u=(h?Math.min(h,n.maxLoadingDelay):n.maxLoadingDelay)-t,I.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),l=c=1)}const d=this.findBestLevel(o,r,e,a,u,l,c);if(I.info(`[abr] ${a?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`),d>-1)return d;const f=s.levels[r],v=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==v?void 0:v.bitrate)?r:s.loadLevel}getStarvationDelay(){const t=this.hls,i=t.media;if(!i)return 1/0;const s=i&&0!==i.playbackRate?Math.abs(i.playbackRate):1,e=t.mainForwardBufferInfo;return(e?e.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,i,s,e,n,r,h){var o;const a=e+n,l=this.lastLoadedFragLevel,c=-1===l?this.hls.firstLevel:l,{fragCurrent:u,partCurrent:d}=this,{levels:f,allAudioTracks:v,loadLevel:p,config:g}=this.hls;if(1===f.length)return 0;const m=f[c],y=!(null==m||null==(o=m.details)||!o.live),w=-1===p||-1===l;let b,k="SDR",S=(null==m?void 0:m.frameRate)||0;const{audioPreference:$,videoPreference:E}=g,A=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,i)=>{let s=t.groups[i.groupId];s||(s=t.groups[i.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(i);const e=i.channels||"2";return s.channels[e]=(s.channels[e]||0)+1,s.hasDefault=s.hasDefault||i.default,s.hasAutoSelect=s.hasAutoSelect||i.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(v));if(w){if(-1!==this.firstSelection)return this.firstSelection;const e=this.codecTiers||(this.codecTiers=function(t,i,s,e){return t.slice(s,e+1).reduce(((t,s)=>{if(!s.codecSet)return t;const e=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!e,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const r=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,r),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,e&&e.forEach((t=>{if(!t)return;const s=i.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||i.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!i.hasDefaultAudio&&!i.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]})))})),t}),{})}(f,A,i,s)),n=function(t,i,s,e,n){const r=Object.keys(t),h=null==e?void 0:e.channels,o=null==e?void 0:e.audioCodec,a=h&&2===parseInt(h);let l=!0,c=!1,u=1/0,d=1/0,f=1/0,v=0,p=[];const{preferHDR:g,allowedVideoRanges:m}=function(t,i){let s=!1,e=[];return t&&(s="SDR"!==t,e=[t]),i&&(e=i.allowedVideoRanges||Qi.slice(0),s=void 0!==i.preferHDR?i.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),i=matchMedia("bad query");if(t.media!==i.media)return!0===t.matches}return!1}(),e=s?e.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:s,allowedVideoRanges:e}}(i,n);for(let i=r.length;i--;){const s=t[r[i]];l=s.channels[2]>0,u=Math.min(u,s.minHeight),d=Math.min(d,s.minFramerate),f=Math.min(f,s.minBitrate);const e=m.filter((t=>s.videoRanges[t]>0));e.length>0&&(c=!0,p=e)}u=T(u)?u:0,d=T(d)?d:0;const y=Math.max(1080,u),w=Math.max(30,d);return f=T(f)?f:s,s=Math.max(f,s),c||(i=void 0,p=[]),{codecSet:r.reduce(((i,e)=>{const n=t[e];if(e===i)return i;if(n.minBitrate>s)return As(e,`min bitrate of ${n.minBitrate} > current estimate of ${s}`),i;if(!n.hasDefaultAudio)return As(e,"no renditions with default or auto-select sound found"),i;if(o&&e.indexOf(o.substring(0,4))%5!=0)return As(e,`audio codec preference "${o}" not found`),i;if(h&&!a){if(!n.channels[h])return As(e,`no renditions with ${h} channel sound found (channels options: ${Object.keys(n.channels)})`),i}else if((!o||a)&&l&&0===n.channels[2])return As(e,"no renditions with stereo sound found"),i;return n.minHeight>y?(As(e,`min resolution of ${n.minHeight} > maximum of ${y}`),i):n.minFramerate>w?(As(e,`min framerate of ${n.minFramerate} > maximum of ${w}`),i):p.some((t=>n.videoRanges[t]>0))?n.maxScore<v?(As(e,`max score of ${n.maxScore} < selected max of ${v}`),i):i&&(ci(e)>=ci(i)||n.fragmentError>t[i].fragmentError)?i:(v=n.maxScore,e):(As(e,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),i)}),void 0),videoRanges:p,preferHDR:g,minFramerate:d,minBitrate:f}}(e,k,t,$,E),{codecSet:r,videoRanges:h,minFramerate:o,minBitrate:a,preferHDR:l}=n;b=r,k=l?h[h.length-1]:h[0],S=o,t=Math.max(t,a),I.log(`[abr] picked start tier ${JSON.stringify(n)}`)}else b=null==m?void 0:m.codecSet,k=null==m?void 0:m.videoRange;const M=d?d.duration:u?u.duration:0,L=this.bwEstimator.getEstimateTTFB()/1e3,x=[];for(let o=s;o>=i;o--){var D;const i=f[o],u=o>c;if(!i)continue;if(g.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&$s(i,A,k,S,t,$)?(i.supportedPromise=Es(i,A,s),i.supportedPromise.then((t=>{if(!this.hls)return;i.supportedResult=t;const s=this.hls.levels,e=s.indexOf(i);t.error?I.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${e} ${JSON.stringify(t)}`):t.supported||(I.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${e} ${JSON.stringify(t)}`),e>-1&&s.length>1&&(I.log(`[abr] Removing unsupported level ${e}`),this.hls.removeLevel(e)))}))):i.supportedResult=Ss}if(b&&i.codecSet!==b||k&&i.videoRange!==k||u&&S>i.frameRate||!u&&S>0&&S<i.frameRate||i.supportedResult&&(null==(D=i.supportedResult.decodingInfoResults)||!D[0].smooth)){x.push(o);continue}const v=i.details,E=(d?null==v?void 0:v.partTarget:null==v?void 0:v.averagetargetduration)||M;let C;C=u?h*t:r*t;const R=M&&e>=2*M&&0===n?f[o].averageBitrate:f[o].maxBitrate,P=this.getTimeToLoadFrag(L,C,R*E,void 0===v);if(C>=R&&(o===l||0===i.loadError&&0===i.fragmentError)&&(P<=L||!T(P)||y&&!this.bitrateTestDelay||P<a)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(x.length&&I.trace(`[abr] Skipped level(s) ${x.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[x[0]].codecs}" ${f[x[0]].videoRange}; not compatible with "${m.codecs}" ${k}`),I.info(`[abr] switch candidate:${c}->${o} adjustedbw(${Math.round(C)})-bitrate=${Math.round(C-R)} ttfb:${L.toFixed(1)} avgDuration:${E.toFixed(1)} maxFetchDuration:${a.toFixed(1)} fetchDuration:${P.toFixed(1)} firstSelection:${w} codecSet:${b} videoRange:${k} hls.loadLevel:${p}`)),w&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:i,minAutoLevel:s}=this.hls,e=Math.min(Math.max(t,s),i);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}},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=()=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=()=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:i}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(A.MEDIA_ATTACHED,{media:t,mediaSource:i})),i&&i.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:i}=this;t!==i&&I.error(`Media element src was set while attaching MediaSource (${i} > ${t})`)},this.hls=t;const i="[buffer-controller]";var s;this.appendSource=(s=ni(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.log=I.log.bind(I,i),this.warn=I.warn.bind(I,i),this.error=I.error.bind(I,i),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(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.BUFFER_RESET,this.onBufferReset,this),t.on(A.BUFFER_APPENDING,this.onBufferAppending,this),t.on(A.BUFFER_CODECS,this.onBufferCodecs,this),t.on(A.BUFFER_EOS,this.onBufferEos,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(A.FRAG_PARSED,this.onFragParsed,this),t.on(A.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.BUFFER_RESET,this.onBufferReset,this),t.off(A.BUFFER_APPENDING,this.onBufferAppending,this),t.off(A.BUFFER_CODECS,this.onBufferCodecs,this),t.off(A.BUFFER_EOS,this.onBufferEos,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(A.FRAG_PARSED,this.onFragParsed,this),t.off(A.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new En(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,i){let s=2;(i.audio&&!i.video||!i.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,i){const s=this.media=i.media,e=ni(this.appendSource);if(s&&e){var n;const t=this.mediaSource=new e;this.log(`created media source: ${null==(n=t.constructor)?void 0:n.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 i=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&t instanceof e,Mn(s),function(t,i){const s=self.document.createElement("source");s.type="video/mp4",s.src=i,t.appendChild(s)}(s,i),s.load()}catch(t){s.src=i}else s.src=i;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:i,_objectUrl:s}=this;if(i){if(this.log("media source detaching"),"open"===i.readyState)try{i.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&Mn(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(A.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer(),this.hls.resumeBuffering()}resetBuffer(t){const i=this.sourceBuffer[t];try{var s;i&&(this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i))}catch(i){this.warn(`onBufferReset ${t}`,i)}}onBufferCodecs(t,i){const s=this.getSourceBufferTypes().length,e=Object.keys(i);if(e.forEach((t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var e;const{id:n,codec:r,levelCodec:h,container:o,metadata:a}=i[t],l=vi(s.codec,s.levelCodec),c=null==l?void 0:l.replace(An,"$1");let u=vi(r,h);const d=null==(e=u)?void 0:e.replace(An,"$1");u&&c!==d&&("audio"===t.slice(0,5)&&(u=fi(u,this.appendSource)),this.appendChangeType(t,`${o};codecs=${u}`),this.log(`switching codec ${l} to ${u}`),this.tracks[t]={buffer:s.buffer,codec:r,container:o,levelCodec:h,metadata:a,id:n})}}else this.pendingTracks[t]=i[t]})),s)return;const n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${e.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,i){const{operationQueue:s}=this,e={execute:()=>{const e=this.sourceBuffer[t];e&&(this.log(`changing ${t} sourceBuffer type to ${i}`),e.changeType(i)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:i=>{this.warn(`Failed to change ${t} SourceBuffer type`,i)}};s.append(e,t,!!this.pendingTracks[t])}onBufferAppending(t,i){const{hls:s,operationQueue:e,tracks:n}=this,{data:r,type:h,frag:o,part:a,chunkMeta:l}=i,c=l.buffering[h],u=self.performance.now();c.start=u;const d=o.stats.buffering,f=a?a.stats.buffering:null;0===d.start&&(d.start=u),f&&0===f.start&&(f.start=u);const v=n.audio;let p=!1;"audio"===h&&"audio/mpeg"===(null==v?void 0:v.container)&&(p=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const g=o.start,m={execute:()=>{if(c.executeStart=self.performance.now(),p){const t=this.sourceBuffer[h];if(t){const i=g-t.timestampOffset;Math.abs(i)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${g} (delta: ${i}) sn: ${o.sn})`),t.timestampOffset=g)}}this.appendExecutor(r,h)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();c.executeEnd=c.end=t,0===d.first&&(d.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:i}=this,s={};for(const t in i)s[t]=js.getBuffered(i[t]);this.appendErrors[h]=0,"audio"===h||"video"===h?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(A.BUFFER_APPENDED,{type:h,frag:o,part:a,chunkMeta:l,parent:o.type,timeRanges:s})},onError:t=>{const i={type:M.MEDIA_ERROR,parent:o.type,details:L.BUFFER_APPEND_ERROR,sourceBufferName:h,frag:o,part:a,chunkMeta:l,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)i.details=L.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[h];i.details=L.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${s.config.appendErrorMaxRetry} times to append segment in "${h}" sourceBuffer`),t>=s.config.appendErrorMaxRetry&&(i.fatal=!0)}s.trigger(A.ERROR,i)}};e.append(m,h,!!this.pendingTracks[h])}onBufferFlushing(t,i){const{operationQueue:s}=this,e=t=>({execute:this.removeExecutor.bind(this,t,i.startOffset,i.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(A.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove from ${t} SourceBuffer`,i)}});i.type?s.append(e(i.type),i.type):this.getSourceBufferTypes().forEach((t=>{s.append(e(t),t)}))}onFragParsed(t,i){const{frag:s,part:e}=i,n=[],r=e?e.elementaryStreams:s.elementaryStreams;r[_]?n.push("audiovideo"):(r[B]&&n.push("audio"),r[j]&&n.push("video")),0===n.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,e&&(e.stats.buffering.end=t),this.hls.trigger(A.FRAG_BUFFERED,{frag:s,part:e,stats:e?e.stats:s.stats,id:s.type})}),n)}onFragChanged(t,i){this.trimBuffers()}onBufferEos(t,i){this.getSourceBufferTypes().reduce(((t,s)=>{const e=this.sourceBuffer[s];return!e||i.type&&i.type!==s||(e.ending=!0,e.ended||(e.ended=!0,this.log(`${s} sourceBuffer now EOS`))),t&&!(e&&!e.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const i=this.sourceBuffer[t];i&&(i.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:i}){i.fragments.length&&(this.details=i,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:i,media:s}=this;if(!s||null===i)return;if(!this.getSourceBufferTypes().length)return;const e=t.config,n=s.currentTime,r=i.levelTargetDuration,h=i.live&&null!==e.liveBackBufferLength?e.liveBackBufferLength:e.backBufferLength;if(T(h)&&h>0){const t=Math.max(h,r),i=Math.floor(n/r)*r-t;this.flushBackBuffer(n,r,i)}if(T(e.frontBufferFlushThreshold)&&e.frontBufferFlushThreshold>0){const t=Math.max(e.maxBufferLength,e.frontBufferFlushThreshold),i=Math.max(t,r),s=Math.floor(n/r)*r+i;this.flushFrontBuffer(n,r,s)}}flushBackBuffer(t,i,s){const{details:e,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach((r=>{const h=n[r];if(h){const n=js.getBuffered(h);if(n.length>0&&s>n.start(0)){if(this.hls.trigger(A.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=e&&e.live)this.hls.trigger(A.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(h.ended&&n.end(n.length-1)-t<2*i)return void this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);this.hls.trigger(A.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}}))}flushFrontBuffer(t,i,s){const{sourceBuffer:e}=this;this.getSourceBufferTypes().forEach((n=>{const r=e[n];if(r){const e=js.getBuffered(r),h=e.length;if(h<2)return;const o=e.start(h-1),a=e.end(h-1);if(s>o||t>=o&&t<=a)return;if(r.ended&&t-a<2*i)return void this.log(`Cannot flush ${n} front buffer while SourceBuffer is in ended state`);this.hls.trigger(A.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:n})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:i,media:s,mediaSource:e}=this,n=t.fragments[0].start+t.totalduration,r=s.duration,h=T(e.duration)?e.duration:0;t.live&&i.config.liveDurationInfinity?(e.duration=1/0,this.updateSeekableRange(t)):(n>h&&n>r||!T(r))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),e.duration=n)}updateSeekableRange(t){const i=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=i&&i.setLiveSeekableRange){const e=Math.max(0,s[0].start),n=Math.max(e,e+t.totalduration);this.log(`Media Source duration is set to ${i.duration}. Setting seekable range to ${e}-${n}.`),i.setLiveSeekableRange(e,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:i,pendingTracks:s}=this,e=Object.keys(s).length;if(e&&(!t||2===e||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(A.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{i.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:i,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const n in t)if(!i[n]){var e;const r=t[n];if(!r)throw Error(`source buffer exists for track ${n}, however track does not`);let h=-1===(null==(e=r.levelCodec)?void 0:e.indexOf(","))?r.levelCodec:r.codec;h&&"audio"===n.slice(0,5)&&(h=fi(h,this.appendSource));const o=`${r.container};codecs=${h}`;this.log(`creating sourceBuffer(${o})`);try{const t=i[n]=s.addSourceBuffer(o),e=n;this.addBufferListener(e,"updatestart",this._onSBUpdateStart),this.addBufferListener(e,"updateend",this._onSBUpdateEnd),this.addBufferListener(e,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((t,i)=>{const s=i.removedRanges;null!=s&&s.length&&this.hls.trigger(A.BUFFER_FLUSHED,{type:n})})),this.tracks[n]={buffer:t,codec:h,container:r.container,levelCodec:r.levelCodec,metadata:r.metadata,id:r.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:o})}}}get mediaSrc(){var t,i;const s=(null==(t=this.media)||null==(i=t.querySelector)?void 0:i.call(t,"source"))||this.media;return null==s?void 0:s.src}_onSBUpdateStart(t){const{operationQueue:i}=this;i.current(t).onStart()}_onSBUpdateEnd(t){var i;if("closed"===(null==(i=this.mediaSource)?void 0:i.readyState))return void this.resetBuffer(t);const{operationQueue:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t)}_onSBUpdateError(t,i){var s;const e=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${e}`,i),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:e,fatal:!1});const n=this.operationQueue.current(t);n&&n.onError(e)}removeExecutor(t,i,s){const{media:e,mediaSource:n,operationQueue:r,sourceBuffer:h}=this,o=h[t];if(!e||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void r.shiftAndExecuteNext(t);const a=T(e.duration)?e.duration:1/0,l=T(n.duration)?n.duration:1/0,c=Math.max(0,i),u=Math.min(s,a,l);u>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${u}] from the ${t} SourceBuffer`),o.remove(c,u)):r.shiftAndExecuteNext(t)}appendExecutor(t,i){const s=this.sourceBuffer[i];if(s)s.ended=!1,s.appendBuffer(t);else if(!this.pendingTracks[i])throw new Error(`Attempting to append to the ${i} SourceBuffer, but it does not exist`)}blockBuffers(t,i=this.getSourceBufferTypes()){if(!i.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:s}=this,e=i.map((t=>s.appendBlocker(t)));Promise.all(e).then((()=>{t(),i.forEach((t=>{const i=this.sourceBuffer[t];null!=i&&i.updating||s.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,i,s){const e=this.sourceBuffer[t];if(!e)return;const n=s.bind(this,t);this.listeners[t].push({event:i,listener:n}),e.addEventListener(i,n)}removeBufferListeners(t){const i=this.sourceBuffer[t];i&&this.listeners[t].forEach((t=>{i.removeEventListener(t.event,t.listener)}))}},capLevelController:kr,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=I.log.bind(I,"[info]:"),this.warn=I.warn.bind(I,"[warning]:"),this.error=I.error.bind(I,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(A.ERROR,this.onError,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(A.ERROR,this.onError,this),t.off(A.ERROR,this.onErrorOut,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.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)===Ii?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,i){var s,e;if(i.fatal)return;const n=this.hls,r=i.context;switch(i.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:return void(i.errorAction=this.getFragRetryOrSwitchAction(i));case L.FRAG_PARSING_ERROR:if(null!=(s=i.frag)&&s.gap)return void(i.errorAction={action:0,flags:0});case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:return i.errorAction=this.getFragRetryOrSwitchAction(i),void(i.errorAction.action=2);case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var h,o;const t=i.parent===Ii?i.level:n.loadLevel;i.details===L.LEVEL_EMPTY_ERROR&&null!=(h=i.context)&&null!=(o=h.levelDetails)&&o.live?i.errorAction=this.getPlaylistRetryOrSwitchAction(i,t):(i.levelRetry=!1,i.errorAction=this.getLevelSwitchAction(i,t))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(i.errorAction=this.getPlaylistRetryOrSwitchAction(i,r.level)));case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=n.levels[n.loadLevel];if(t&&(r.type===Di&&t.hasAudioGroup(r.groupId)||r.type===Ci&&t.hasSubtitleGroup(r.groupId)))return i.errorAction=this.getPlaylistRetryOrSwitchAction(i,n.loadLevel),i.errorAction.action=2,void(i.errorAction.flags=1)}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=n.levels[n.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?i.errorAction={action:2,flags:2,hdcpLevel:s}:this.keySystemError(i)}return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:return void(i.errorAction=this.getLevelSwitchAction(i,null!=(e=i.level)?e:n.loadLevel));case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:return void(i.errorAction={action:0,flags:0})}i.type===M.KEY_SYSTEM_ERROR&&this.keySystemError(i)}keySystemError(t){const i=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,i)}getPlaylistRetryOrSwitchAction(t,i){const s=us(this.hls.config.playlistLoadPolicy,t),e=this.playlistError++;if(vs(s,e,cs(t),t.response))return{action:5,flags:0,retryConfig:s,retryCount:e};const n=this.getLevelSwitchAction(t,i);return s&&(n.retryConfig=s,n.retryCount=e),n}getFragRetryOrSwitchAction(t){const i=this.hls,s=this.getVariantLevelIndex(t.frag),e=i.levels[s],{fragLoadPolicy:n,keyLoadPolicy:r}=i.config,h=us(t.details.startsWith("key")?r:n,t),o=i.levels.reduce(((t,i)=>t+i.fragmentError),0);if(e&&(t.details!==L.FRAG_GAP&&e.fragmentError++,vs(h,o,cs(t),t.response)))return{action:5,flags:0,retryConfig:h,retryCount:o};const a=this.getLevelSwitchAction(t,s);return h&&(a.retryConfig=h,a.retryCount=o),a}getLevelSwitchAction(t,i){const s=this.hls;null==i&&(i=s.loadLevel);const e=this.hls.levels[i];if(e){var n,r;const i=t.details;e.loadError++,i===L.BUFFER_APPEND_ERROR&&e.fragmentError++;let a=-1;const{levels:l,loadLevel:c,minAutoLevel:u,maxAutoLevel:d}=s;s.autoLevelEnabled||(s.loadLevel=-1);const f=null==(n=t.frag)?void 0:n.type,v=(f===Ri&&i===L.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(i===L.BUFFER_ADD_CODEC_ERROR||i===L.BUFFER_APPEND_ERROR))&&l.some((({audioCodec:t})=>e.audioCodec!==t)),p="video"===t.sourceBufferName&&(i===L.BUFFER_ADD_CODEC_ERROR||i===L.BUFFER_APPEND_ERROR)&&l.some((({codecSet:t,audioCodec:i})=>e.codecSet!==t&&e.audioCodec===i)),{type:g,groupId:m}=null!=(r=t.context)?r:{};for(let s=l.length;s--;){const n=(s+c)%l.length;if(n!==c&&n>=u&&n<=d&&0===l[n].loadError){var h,o;const s=l[n];if(i===L.FRAG_GAP&&f===Ii&&t.frag){const i=l[n].details;if(i){const s=gs(t.frag,i.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(g===Di&&s.hasAudioGroup(m)||g===Ci&&s.hasSubtitleGroup(m))continue;if(f===Ri&&null!=(h=e.audioGroups)&&h.some((t=>s.hasAudioGroup(t)))||f===Pi&&null!=(o=e.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||v&&e.audioCodec===s.audioCodec||!v&&e.audioCodec!==s.audioCodec||p&&e.codecSet===s.codecSet)continue}a=n;break}}if(a>-1&&s.loadLevel!==a)return t.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:a}}return{action:2,flags:1}}onErrorOut(t,i){var s;switch(null==(s=i.errorAction)?void 0:s.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(i),i.errorAction.resolved||i.details===L.FRAG_GAP?/MediaSource readyState: ended/.test(i.error.message)&&(this.warn(`MediaSource ended after "${i.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):i.fatal=!0}i.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const i=this.hls,s=t.errorAction;if(!s)return;const{flags:e,hdcpLevel:n,nextAutoLevel:r}=s;switch(e){case 0:this.switchLevel(t,r);break;case 2:n&&(i.maxHdcpLevel=Ji[Ji.indexOf(n)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${i.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,r)}switchLevel(t,i){void 0!==i&&t.errorAction&&(this.warn(`switching to level ${i} after ${t.details}`),this.hls.nextAutoLevel=i,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(A.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,i){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=i.media instanceof self.HTMLVideoElement?i.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,i,s){const e=performance.now();if(i){if(this.lastTime){const t=s-this.lastDroppedFrames,n=i-this.lastDecodedFrames,r=1e3*t/(e-this.lastTime),h=this.hls;if(h.trigger(A.FPS_DROP,{currentDropped:t,currentDecoded:n,totalDroppedFrames:s}),r>0&&t>h.config.fpsDroppedMonitoringThreshold*n){let t=h.currentLevel;I.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=t)&&(t-=1,h.trigger(A.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:h.currentLevel}),h.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=e,this.lastDroppedFrames=s,this.lastDecodedFrames=i}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const i=t.getVideoPlaybackQuality();this.checkFPS(t,i.totalVideoFrames,i.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:nt,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:dh,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 fe{constructor(t,i,s){super(t,i,s,"[subtitle-stream-controller]",Pi),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(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.ERROR,this.onError,this),t.on(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(A.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(A.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.ERROR,this.onError,this),t.off(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(A.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(A.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=se,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,i){this.mainDetails=i.details}onSubtitleFragProcessed(t,i){const{frag:s,success:e}=i;if(this.fragPrevious=s,this.state=se,!e)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let r;const h=s.start;for(let t=0;t<n.length;t++)if(h>=n[t].start&&h<=n[t].end){r=n[t];break}const o=s.start+s.duration;r?r.end=o:(r={start:h,end:o},n.push(r)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(t,i){const{startOffset:s,endOffset:e}=i;if(0===s&&e!==Number.POSITIVE_INFINITY){const t=e-1;if(t<=0)return;i.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((i=>{for(let s=0;s<i.length;)if(i[s].end<=t)i.shift();else{if(!(i[s].start<t))break;i[s].start=t,s++}})),this.fragmentTracker.removeFragmentsInRange(s,t,Pi)}}onFragBuffered(t,i){var s;this.loadedmetadata||i.frag.type!==Ii||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,i){const s=i.frag;(null==s?void 0:s.type)===Pi&&(i.details===L.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ie&&(this.state=se))}onSubtitleTracksUpdated(t,{subtitleTracks:i}){this.levels&&kn(this.levels,i)?this.levels=i.map((t=>new is(t))):(this.tracksBuffered=[],this.levels=i.map((t=>{const i=new is(t);return this.tracksBuffered[i.id]=[],i})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Pi),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,i){var s;if(this.currentTrackId=i.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const e=this.levels[this.currentTrackId];this.mediaBuffer=null!=e&&e.details?this.mediaBufferTimeRanges:null,e&&this.setInterval(500)}onSubtitleTrackLoaded(t,i){var s;const{currentTrackId:e,levels:n}=this,{details:r,id:h}=i;if(!n)return void this.warn(`Subtitle tracks were reset while loading level ${h}`);const o=n[h];if(h>=n.length||!o)return;this.log(`Subtitle track ${h} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let a=0;if(r.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;const i=t.fragments[0];var l;o.details?(a=this.alignPlaylists(r,o.details,null==(l=this.levelLastLoaded)?void 0:l.details),0===a&&i&&(a=i.start,hs(r,a))):r.hasProgramDateTime&&t.hasProgramDateTime?(Vs(r,t),a=r.fragments[0].start):i&&(a=i.start,hs(r,a))}o.details=r,this.levelLastLoaded=o,h===e&&(this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(this.mainDetails||r,a),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===se)&&(gs(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0))}_handleFragmentLoadComplete(t){const{frag:i,payload:s}=t,e=i.decryptdata,n=this.hls;if(!this.fragContextChanged(i)&&s&&s.byteLength>0&&null!=e&&e.key&&e.iv&&"AES-128"===e.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),e.key.buffer,e.iv.buffer).catch((t=>{throw n.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((s=>{const e=performance.now();n.trigger(A.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:t,tdecrypt:e}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=se}))}}doTick(){if(this.media){if(this.state===se){const{currentTrackId:t,levels:i}=this,s=null==i?void 0:i[t];if(!s||!i.length||!s.details)return;const{config:e}=this,n=this.getLoadPosition(),r=js.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,e.maxBufferHole),{end:h,len:o}=r,a=this.getFwdBufferInfo(this.media,Ii),l=s.details;if(o>this.getMaxBufferLength(null==a?void 0:a.len)+l.levelTargetDuration)return;const c=l.fragments,u=c.length,d=l.edge;let f=null;const v=this.fragPrevious;if(h<d){const t=e.maxFragLookUpTolerance,i=h>d-t?0:t;f=gs(v,c,Math.max(c[0].start,h),i),!f&&v&&v.start<c[0].start&&(f=c[0])}else f=c[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const t=c[f.sn-l.startSN-1];t&&t.cc===f.cc&&this.fragmentTracker.getState(t)===Is&&(f=t)}this.fragmentTracker.getState(f)===Is&&this.loadFragment(f,s,h)}}else this.state=se}getMaxBufferLength(t){const i=super.getMaxBufferLength();return t?Math.max(i,t):i}loadFragment(t,i,s){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,i):(this.startFragRequested=!0,super.loadFragment(t,i,s))}get mediaBufferTimeRanges(){return new $n(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends ws{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.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 i=Gi(this.media.textTracks);for(let s=0;s<i.length;s++)if("hidden"===i[s].mode)t=i[s];else if("showing"===i[s].mode){t=i[s];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVEL_LOADING,this.onLevelLoading,this),t.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(A.ERROR,this.onError,this)}onMediaAttached(t,i){this.media=i.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(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Gi(this.media.textTracks).forEach((t=>{ji(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,i){this.tracks=i.subtitleTracks}onSubtitleTrackLoaded(t,i){const{id:s,groupId:e,details:n}=i,r=this.tracksInGroup[s];if(!r||r.groupId!==e)return void this.warn(`Subtitle track with id:${s} and group:${e} not found in active group ${null==r?void 0:r.groupId}`);const h=r.details;r.details=i.details,this.log(`Subtitle track ${s} "${r.name}" lang:${r.lang} group:${e} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,i,h)}onLevelLoading(t,i){this.switchLevel(i.level)}onLevelSwitching(t,i){this.switchLevel(i.level)}switchLevel(t){const i=this.hls.levels[t];if(!i)return;const s=i.subtitleGroups||null,e=this.groupIds;let n=this.currentTrack;if(!s||(null==e?void 0:e.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==e?void 0:e.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,i)=>{t.id=i}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const i=this.hls.config.subtitlePreference;if(!n&&i){this.selectDefaultTrack=!1;const s=Ms(i,t);if(s>-1)n=t[s];else{const t=Ms(i,this.tracks);n=this.tracks[t]}}let e=this.findTrackId(n);-1===e&&n&&(e=this.findTrackId(null));const r={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(A.SUBTITLE_TRACKS_UPDATED,r),-1!==e&&-1===this.trackId&&this.setSubtitleTrack(e)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const i=this.tracksInGroup,s=this.selectDefaultTrack;for(let e=0;e<i.length;e++){const n=i[e];if((!s||n.default)&&(s||t)&&(!t||Ls(n,t)))return e}if(t){for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE"]))return s}return-1}findTrackForTextTrack(t){if(t){const i=this.tracksInGroup;for(let s=0;s<i.length;s++)if(Tn(i[s],t))return s}return-1}onError(t,i){!i.fatal&&i.context&&(i.context.type!==Ci||i.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(i.context.groupId)||this.checkRetry(i))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const i=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&Ls(t,s))return s;const e=Ms(t,this.tracksInGroup);if(e>-1){const t=this.tracksInGroup[e];return this.setSubtitleTrack(e),t}if(s)return null;{const s=Ms(t,i);if(s>-1)return i[s]}}}return null}loadPlaylist(t){super.loadPlaylist();const i=this.currentTrack;if(this.shouldLoadPlaylist(i)&&i){const s=i.id,e=i.groupId;let n=i.url;if(t)try{n=t.addDirectives(n)}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(A.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const i=Gi(t.textTracks),s=this.currentTrack;let e;if(s&&(e=i.filter((t=>Tn(s,t)))[0],e||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(i).forEach((t=>{"disabled"!==t.mode&&t!==e&&(t.mode="disabled")})),e){const t=this.subtitleDisplay?"showing":"hidden";e.mode!==t&&(e.mode=t)}}setSubtitleTrack(t){const i=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=i.length||!T(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,e=i[t]||null;if(this.trackId=t,this.currentTrack=e,this.toggleTrackModes(),!e)return void this.hls.trigger(A.SUBTITLE_TRACK_SWITCH,{id:t});if(t===this.trackId&&e===s&&e.details&&!e.details.live)return;this.log(`Switching to subtitle-track ${t}`+(e?` "${e.name}" lang:${e.lang} group:${e.groupId}`:""));const{id:n,groupId:r="",name:h,type:o,url:a}=e;this.hls.trigger(A.SUBTITLE_TRACK_SWITCH,{id:n,groupId:r,name:h,type:o,url:a});const l=this.switchParams(e.url,null==s?void 0:s.details,e.details);this.loadPlaylist(l)}},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(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(A.FRAG_LOADING,this.onFragLoading,this),t.on(A.FRAG_LOADED,this.onFragLoaded,this),t.on(A.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(A.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(A.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(A.FRAG_LOADING,this.onFragLoading,this),t.off(A.FRAG_LOADED,this.onFragLoaded,this),t.off(A.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(A.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(A.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(A.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 Wn(this,"textTrack1"),i=new Wn(this,"textTrack2"),s=new Wn(this,"textTrack3"),e=new Wn(this,"textTrack4");this.cea608Parser1=new Kn(1,t,i),this.cea608Parser2=new Kn(3,s,e)}}addCues(t,i,s,e,n){let r=!1;for(let t=n.length;t--;){const e=n[t],a=(h=e[0],o=i,Math.min(e[1],s)-Math.max(h,o));if(a>=0&&(e[0]=Math.min(e[0],i),e[1]=Math.max(e[1],s),r=!0,a/(s-i)>.5))return}var h,o;if(r||n.push([i,s]),this.config.renderTextTracksNatively)this.Cues.newCue(this.captionsTracks[t],i,s,e);else{const n=this.Cues.newCue(null,i,s,e);this.hls.trigger(A.CUES_PARSED,{type:"captions",cues:n,track:t})}}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){const{unparsedVttFrags:r}=this;"main"===s&&(this.initPTS[i.cc]={baseTime:e,timescale:n}),r.length&&(this.unparsedVttFrags=[],r.forEach((t=>{this.onFragLoaded(A.FRAG_LOADED,t)})))}getExistingTrack(t,i){const{media:s}=this;if(s)for(let e=0;e<s.textTracks.length;e++){const n=s.textTracks[e];if(br(n,{name:t,lang:i,attrs:{}}))return n}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:i,captionsTracks:s,media:e}=this,{label:n,languageCode:r}=i[t],h=this.getExistingTrack(n,r);if(h)s[t]=h,ji(s[t]),Fi(s[t],e);else{const i=this.createTextTrack("captions",n,r);i&&(i[t]=!0,s[t]=i)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const i=this.captionsProperties[t];if(!i)return;const s={_id:t,label:i.label,kind:"captions",default:!!i.media&&!!i.media.default,closedCaptions:i.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(A.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,i,s){const e=this.media;if(e)return e.addTextTrack(t,i,s)}onMediaAttaching(t,i){this.media=i.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach((i=>{ji(t[i]),delete t[i]})),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 i=t.textTracks;if(i)for(let t=0;t<i.length;t++)ji(i[t])}onSubtitleTracksUpdated(t,i){const s=i.subtitleTracks||[],e=s.some((t=>t.textCodec===ar));if(this.config.enableWebVTT||e&&this.config.enableIMSC1){if(kn(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,i=t?Gi(t.textTracks):null;if(this.tracks.forEach((t=>{let s;if(i){let e=null;for(let s=0;s<i.length;s++)if(i[s]&&br(i[s],t)){e=i[s],i[s]=null;break}e&&(s=e)}if(s)ji(s);else{const i=wr(t);s=this.createTextTrack(i,t.name,t.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)})),null!=i&&i.length){const t=i.filter((t=>null!==t)).map((t=>t.label));t.length&&I.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(A.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,i){this.config.enableCEA708Captions&&i.captions&&i.captions.forEach((t=>{const i=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!i)return;const s=this.captionsProperties[`textTrack${i[1]}`];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)}))}closedCaptionsForLevel(t){const i=this.hls.levels[t.level];return null==i?void 0:i.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,i){if(this.enabled&&i.frag.type===Ii){var s,e;const{cea608Parser1:t,cea608Parser2:n,lastSn:r}=this,{cc:h,sn:o}=i.frag,a=null!=(s=null==(e=i.part)?void 0:e.index)?s:-1;t&&n&&(o!==r+1||o===r&&a!==this.lastPartIndex+1||h!==this.lastCc)&&(t.reset(),n.reset()),this.lastCc=h,this.lastSn=o,this.lastPartIndex=a}}onFragLoaded(t,i){const{frag:s,payload:e}=i;if(s.type===Pi)if(e.byteLength){const t=s.decryptdata;if(null==t||!t.encrypted||"stats"in i){const t=this.tracks[s.level],n=this.vttCCs;n[s.cc]||(n[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===ar?this._parseIMSC1(s,e):this._parseVTTs(i)}}else this.hls.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,i){const s=this.hls;dr(i,this.initPTS[t.cc],(i=>{this._appendCues(i,t.level),s.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(i=>{I.log(`Failed to parse IMSC1: ${i}`),s.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:i})}))}_parseVTTs(t){var i;const{frag:s,payload:e}=t,{initPTS:n,unparsedVttFrags:r}=this,h=n.length-1;if(!n[s.cc]&&-1===h)return void r.push(t);const o=this.hls;!function(t,i,s,e,n,r,h){const o=new er,a=St(new Uint8Array(t)).trim().replace(nr,"\n").split("\n"),l=[],c=i?function(t,i=1){return tn(t,9e4,1/i)}(i.baseTime,i.timescale):0;let u,d="00:00.000",f=0,v=0,p=!0;o.oncue=function(t){const r=s[e];let h=s.ccOffset;const o=(f-c)/9e4;if(null!=r&&r.new&&(void 0!==v?h=s.ccOffset=r.start:function(t,i,s){let e=t[i],n=t[e.prevCC];if(!n||!n.new&&e.new)return t.ccOffset=t.presentationOffset=e.start,void(e.new=!1);for(;null!=(r=n)&&r.new;){var r;t.ccOffset+=e.start-n.start,e.new=!1,e=n,n=t[e.prevCC]}t.presentationOffset=s}(s,e,o)),o){if(!i)return void(u=new Error("Missing initPTS for VTT MPEGTS"));h=o-s.presentationOffset}const a=t.endTime-t.startTime,d=on(9e4*(t.startTime+h-v),9e4*n)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+a,0);const p=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(p)),t.id||(t.id=or(t.startTime,t.endTime,p)),t.endTime>0&&l.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?h(u):r(l)},a.forEach((t=>{if(p){if(rr(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{rr(t,"LOCAL:")?d=t.slice(6):rr(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{v=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),e=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(T(i)&&T(s)&&T(e)&&T(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*e,i+=36e5*n,i}(d)/1e3}catch(t){u=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}(null!=(i=s.initSegment)&&i.data?Kt(s.initSegment.data,new Uint8Array(e)):e,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(i=>{const n="Missing initPTS for VTT MPEGTS"===i.message;n?r.push(t):this._fallbackToIMSC1(s,e),I.log(`Failed to parse VTT cue: ${i}`),n&&h>s.cc||o.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:i})}))}_fallbackToIMSC1(t,i){const s=this.tracks[t.level];s.textCodec||dr(i,this.initPTS[t.cc],(()=>{s.textCodec=ar,this._parseIMSC1(t,i)}),(()=>{s.textCodec="wvtt"}))}_appendCues(t,i){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[i];if(!s||"disabled"===s.mode)return;t.forEach((t=>Bi(s,t)))}else{const e=this.tracks[i];if(!e)return;s.trigger(A.CUES_PARSED,{type:"subtitles",cues:t,track:e.default?"default":"subtitles"+i})}}onFragDecrypted(t,i){const{frag:s}=i;s.type===Pi&&this.onFragLoaded(A.FRAG_LOADED,i)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,i){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:e}=this;if(!this.enabled||!s||!e)return;const{frag:n,samples:r}=i;if(n.type!==Ii||"NONE"!==this.closedCaptionsForLevel(n))for(let t=0;t<r.length;t++){const i=r[t].bytes;if(i){const n=this.extractCea608Data(i);s.addData(r[t].pts,n[0]),e.addData(r[t].pts,n[1])}}}onBufferFlushing(t,{startOffset:i,endOffset:s,endOffsetSubtitles:e,type:n}){const{media:r}=this;if(r&&!(r.currentTime<s)){if(!n||"video"===n){const{captionsTracks:t}=this;Object.keys(t).forEach((e=>_i(t[e],i,s)))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==e){const{textTracks:t}=this;Object.keys(t).forEach((s=>_i(t[s],i,e)))}}}extractCea608Data(t){const i=[[],[]],s=31&t[0];let e=2;for(let n=0;n<s;n++){const s=t[e++],n=127&t[e++],r=127&t[e++];if((0!==n||0!==r)&&4&s){const t=3&s;0!==t&&1!==t||(i[t].push(n),i[t].push(r))}}return i}},audioStreamController:class extends fe{constructor(t,i,s){super(t,i,s,"[audio-stream-controller]",Ri),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(A.ERROR,this.onError,this),t.on(A.BUFFER_RESET,this.onBufferReset,this),t.on(A.BUFFER_CREATED,this.onBufferCreated,this),t.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(A.ERROR,this.onError,this),t.off(A.BUFFER_RESET,this.onBufferReset,this),t.off(A.BUFFER_CREATED,this.onBufferCreated,this),t.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(A.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){if("main"===s){const t=i.cc;this.initPTS[i.cc]={baseTime:e,timescale:n},this.log(`InitPTS for cc: ${t} found from main: ${e}`),this.videoTrackCC=t,this.state===ue&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=ie);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=se):(this.loadedmetadata=!1,this.state=he),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case se:this.doTickIdle();break;case he:{var t;const{levels:i,trackId:s}=this,e=null==i||null==(t=i[s])?void 0:t.details;if(e){if(this.waitForCdnTuneIn(e))break;this.state=ue}break}case re:{var i;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(i=this.media)&&i.seeking){const{levels:t,trackId:i}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[i])||null),this.state=se}break}case ue:{const t=this.waitingData;if(t){const{frag:i,part:s,cache:e,complete:n}=t;if(void 0!==this.initPTS[i.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=ne;const t={frag:i,part:s,payload:e.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),n&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=js.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);ms(s.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=se}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=se)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:i,media:s,trackId:e}=this;if(!this.buffering||!s&&(this.startFragRequested||!t.config.startFragPrefetch)||null==i||!i[e])return;const n=i[e],r=n.details;if(!r||r.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(r))return void(this.state=he);const h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,B,Ri));const o=this.getFwdBufferInfo(h,Ri);if(null===o)return;if(!this.switchingTrack&&this._streamEnded(o,r))return t.trigger(A.BUFFER_EOS,{type:"audio"}),void(this.state=le);const a=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Ii),l=o.len,c=this.getMaxBufferLength(null==a?void 0:a.len),u=r.fragments,d=u[0].start,f=this.getLoadPosition(),v=this.flushing?f:o.end;if(this.switchingTrack&&s&&r.PTSKnown&&f<d&&(o.end>d||o.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=d+.05),l>=c&&!this.switchingTrack&&v<u[u.length-1].start)return;let p=this.getNextFragment(v,r),g=!1;if(p&&this.isLoopLoading(p,v)&&(g=!!p.gap,p=this.getNextFragmentLoopLoading(p,r,o,Ii,c)),!p)return void(this.bufferFlushed=!0);const m=a&&p.start>a.end+r.targetduration;if(m||(null==a||!a.len)&&o.len){const t=this.getAppendedFrag(p.start,Ii);if(null===t)return;if(g||(g=!!t.gap||!!m&&0===a.len),m&&!g||g&&o.nextStart&&o.nextStart<t.end)return}this.loadFragment(p,n,v)}getMaxBufferLength(t){const i=super.getMaxBufferLength();return t?Math.min(Math.max(i,t),this.config.maxMaxBufferLength):i}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:i}){this.resetTransmuxer(),this.levels=i.map((t=>new is(t)))}onAudioTrackSwitching(t,i){const s=!!i.url;this.trackId=i.id;const{fragCurrent:e}=this;e&&(e.abortRequests(),this.removeUnbufferedFrags(e.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=i,this.state=se,this.flushAudioIfNeeded(i)):(this.switchingTrack=null,this.bufferedTrack=i,this.state=ie),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,i){this.mainDetails=i.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(A.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,i){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=i);const{levels:e}=this,{details:n,id:r}=i;if(!e)return void this.warn(`Audio tracks were reset while loading level ${r}`);this.log(`Audio track ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const h=e[r];let o=0;if(n.live||null!=(s=h.details)&&s.live){this.checkLiveUpdate(n);const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;var a;!h.details&&n.hasProgramDateTime&&t.hasProgramDateTime?(Vs(n,t),o=n.fragments[0].start):o=this.alignPlaylists(n,h.details,null==(a=this.levelLastLoaded)?void 0:a.details)}h.details=n,this.levelLastLoaded=h,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,o),this.state!==he||this.waitForCdnTuneIn(n)||(this.state=se),this.tick()}_handleFragmentLoadProgress(t){var i;const{frag:s,part:e,payload:n}=t,{config:r,trackId:h,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 a=o[h];if(!a)return void this.warn("Audio track is undefined on fragment load progress");const l=a.details;if(!l)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const c=r.defaultAudioCodec||a.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new bn(this.hls,Ri,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[s.cc],f=null==(i=s.initSegment)?void 0:i.data;if(void 0!==d){const t=!1,i=e?e.index:-1,r=new _s(s.level,s.sn,s.stats.chunkCount,n.byteLength,i,-1!==i);u.push(n,f,c,"",s,e,l.totalduration,t,r,d)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${l.startSN} ,${l.endSN}],track ${h}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:e,cache:new ve,complete:!1};t.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=ue}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,i){const s=i.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),i.tracks.video&&(this.videoBuffer=i.tracks.video.buffer||null)}onFragBuffered(t,i){const{frag:s,part:e}=i;if(s.type===Ri)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${e?" p: "+e.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(A.AUDIO_TRACK_SWITCHED,k({},t)))}this.fragBufferedComplete(s,e)}else if(!this.loadedmetadata&&s.type===Ii){const t=this.videoBuffer||this.media;t&&js.getBuffered(t).length&&(this.loadedmetadata=!0)}}onError(t,i){var s;if(i.fatal)this.state=ce;else switch(i.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ri,i);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==he||(null==(s=i.context)?void 0:s.type)!==Di||(this.state=se);break;case L.BUFFER_APPEND_ERROR:case L.BUFFER_FULL_ERROR:if(!i.parent||"audio"!==i.parent)return;if(i.details===L.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}onBufferFlushing(t,{type:i}){i!==j&&(this.flushing=!0)}onBufferFlushed(t,{type:i}){if(i!==j){this.flushing=!1,this.bufferFlushed=!0,this.state===le&&(this.state=se);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,i,Ri),this.tick())}}_handleTransmuxComplete(t){var i;const s="audio",{hls:e}=this,{remuxResult:n,chunkMeta:r}=t,h=this.getCurrentContext(r);if(!h)return void this.resetWhenMissingContext(r);const{frag:o,part:a,level:l}=h,{details:c}=l,{audio:u,text:d,id3:f,initSegment:v}=n;if(!this.fragContextChanged(o)&&c){if(this.state=oe,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,v.tracks,t,r),e.trigger(A.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:v.tracks})}if(u){const{startPTS:t,endPTS:i,startDTS:s,endDTS:e}=u;a&&(a.elementaryStreams[B]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(B,t,i,s,e),this.bufferFragmentData(u,o,a,r)}if(null!=f&&null!=(i=f.samples)&&i.length){const t=S({id:s,frag:o,details:c},f);e.trigger(A.FRAG_PARSING_METADATA,t)}if(d){const t=S({id:s,frag:o,details:c},d);e.trigger(A.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,i,s,e){if(this.state!==oe)return;i.video&&delete i.video;const n=i.audio;if(!n)return;n.id="audio";const r=t.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${r}/${n.codec}]`),r&&1===r.split(",").length&&(n.levelCodec=r),this.hls.trigger(A.BUFFER_CODECS,i);const h=n.initSegment;null!=h&&h.byteLength&&this.hls.trigger(A.BUFFER_APPENDING,{type:"audio",frag:s,part:null,chunkMeta:e,parent:s.type,data:h}),this.tickImmediate()}loadFragment(t,i,s){const e=this.fragmentTracker.getState(t);var n;if(this.fragCurrent=t,this.switchingTrack||e===Is||e===Ps)if("initSegment"===t.sn)this._loadInitSegment(t,i);else if(null!=(n=i.details)&&n.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=ue;const s=this.mainDetails;s&&s.fragments[0].start!==i.details.fragments[0].start&&Vs(i.details,s)}else this.startFragRequested=!0,super.loadFragment(t,i,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:i,lang:s,assocLang:e,characteristics:n,audioCodec:r,channels:h}=this.bufferedTrack;Ls({name:i,lang:s,assocLang:e,characteristics:n,audioCodec:r,channels:h},t,xs)||(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}}completeAudioSwitch(t){const{hls:i}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,i.trigger(A.AUDIO_TRACK_SWITCHED,k({},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(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVEL_LOADING,this.onLevelLoading,this),t.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(A.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,i){this.tracks=i.audioTracks||[]}onAudioTrackLoaded(t,i){const{id:s,groupId:e,details:n}=i,r=this.tracksInGroup[s];if(!r||r.groupId!==e)return void this.warn(`Audio track with id:${s} and group:${e} not found in active group ${null==r?void 0:r.groupId}`);const h=r.details;r.details=i.details,this.log(`Audio track ${s} "${r.name}" lang:${r.lang} group:${e} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,i,h)}onLevelLoading(t,i){this.switchLevel(i.level)}onLevelSwitching(t,i){this.switchLevel(i.level)}switchLevel(t){const i=this.hls.levels[t];if(!i)return;const s=i.audioGroups||null,e=this.groupIds;let n=this.currentTrack;if(!s||(null==e?void 0:e.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==e?void 0:e.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,i)=>{t.id=i}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const i=this.hls.config.audioPreference;if(!n&&i){const s=Ms(i,t,xs);if(s>-1)n=t[s];else{const t=Ms(i,this.tracks);n=this.tracks[t]}}let e=this.findTrackId(n);-1===e&&n&&(e=this.findTrackId(null));const h={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(A.AUDIO_TRACKS_UPDATED,h);const o=this.trackId;if(-1!==e&&-1===o)this.setAudioTrack(e);else if(t.length&&-1===o){var r;const i=new Error(`No audio track selected for current audio group-ID(s): ${null==(r=this.groupIds)?void 0:r.join(",")} track count: ${t.length}`);this.warn(i.message),this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}onError(t,i){!i.fatal&&i.context&&(i.context.type!==Di||i.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(i.context.groupId)||(this.requestScheduled=-1,this.checkRetry(i)))}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 i=this.hls;if(i.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const e=this.currentTrack;if(e&&Ls(t,e,xs))return e;const n=Ms(t,this.tracksInGroup,xs);if(n>-1){const t=this.tracksInGroup[n];return this.setAudioTrack(n),t}if(e){let e=i.loadLevel;-1===e&&(e=i.firstAutoLevel);const n=function(t,i,s,e,n){const r=i[e],h=i.reduce(((t,i,s)=>{const e=i.uri;return(t[e]||(t[e]=[])).push(s),t}),{})[r.uri];h.length>1&&(e=Math.max.apply(Math,h));const o=r.videoRange,a=r.frameRate,l=r.codecSet.substring(0,4),c=Ds(i,e,(i=>{if(i.videoRange!==o||i.frameRate!==a||i.codecSet.substring(0,4)!==l)return!1;const e=i.audioGroups,r=s.filter((t=>!e||-1!==e.indexOf(t.groupId)));return Ms(t,r,n)>-1}));return c>-1?c:Ds(i,e,(i=>{const e=i.audioGroups,r=s.filter((t=>!e||-1!==e.indexOf(t.groupId)));return Ms(t,r,n)>-1}))}(t,i.levels,s,e,xs);if(-1===n)return null;i.nextLoadLevel=n}if(t.channels||t.audioCodec){const i=Ms(t,s);if(i>-1)return s[i]}}}return null}setAudioTrack(t){const i=this.tracksInGroup;if(t<0||t>=i.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,e=i[t],n=e.details&&!e.details.live;if(t===this.trackId&&e===s&&n)return;if(this.log(`Switching to audio-track ${t} "${e.name}" lang:${e.lang} group:${e.groupId} channels:${e.channels}`),this.trackId=t,this.currentTrack=e,this.hls.trigger(A.AUDIO_TRACK_SWITCHING,k({},e)),n)return;const r=this.switchParams(e.url,null==s?void 0:s.details,e.details);this.loadPlaylist(r)}findTrackId(t){const i=this.tracksInGroup;for(let s=0;s<i.length;s++){const e=i[s];if((!this.selectDefaultTrack||e.default)&&(!t||Ls(t,e,xs)))return s}if(t){const{name:s,lang:e,assocLang:n,characteristics:r,audioCodec:h,channels:o}=t;for(let t=0;t<i.length;t++)if(Ls({name:s,lang:e,assocLang:n,characteristics:r,audioCodec:h,channels:o},i[t],xs))return t;for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(Sn(t.attrs,i[s].attrs,["LANGUAGE"]))return s}return-1}loadPlaylist(t){const i=this.currentTrack;if(this.shouldLoadPlaylist(i)&&i){super.loadPlaylist();const s=i.id,e=i.groupId;let n=i.url;if(t)try{n=t.addDirectives(n)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`loading audio-track playlist ${s} "${i.name}" lang:${i.lang} group:${e}`),this.clearTimer(),this.hls.trigger(A.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:t||null})}}},emeController:Tr,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{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:Er.MANIFEST,su:!this.initialized})}catch(t){I.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const i=t.frag,s=this.hls.levels[i.level],e=this.getObjectType(i),n={d:1e3*i.duration,ot:e};e!==Er.VIDEO&&e!==Er.AUDIO&&e!=Er.MUXED||(n.br=s.bitrate/1e3,n.tb=this.getTopBandwidth(e)/1e3,n.bl=this.getBufferLength(e)),this.apply(t,n)}catch(t){I.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const i=this.config=t.config,{cmcd:s}=i;null!=s&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),i=t.toString();return URL.revokeObjectURL(t),i.slice(i.lastIndexOf("/")+1)}catch(t){let i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const s=(i+16*Math.random())%16|0;return i=Math.floor(i/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(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHED,this.onMediaDetached,this),t.on(A.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHED,this.onMediaDetached,this),t.off(A.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,i){this.media=i.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,i){var s,e;this.audioBuffer=null==(s=i.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(e=i.tracks.video)?void 0:e.buffer}createData(){var t;return{v:1,sf:Ar.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,i={}){S(i,this.createData()),this.starved&&(i.ot===Er.INIT||i.ot===Er.VIDEO||i.ot===Er.MUXED)&&(i.bs=!0,i.su=!0,this.starved=!1),null==i.su&&(i.su=this.buffering);const{includeKeys:s}=this;var e;s&&(i=Object.keys(i).reduce(((t,e)=>(s.includes(e)&&(t[e]=i[e]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),S(t.headers,function(t,i={}){if(!t)return{};const s=Object.entries(t),e=Object.entries(Lr).concat(Object.entries((null==i?void 0:i.customHeaderMap)||{})),n=s.reduce(((t,i)=>{var s;const[n,r]=i,h=(null==(s=e.find((t=>t[1].includes(n))))?void 0:s[0])||Mr.REQUEST;return null!=t[h]||(t[h]={}),t[h][n]=r,t}),{});return Object.entries(n).reduce(((t,[s,e])=>(t[s]=ih(e,i),t)),{})}(i,e))):t.url=function(t,i,s){const e=function(t,i={}){if(!t)return"";const s=ih(t,i);return`CMCD=${encodeURIComponent(s)}`}(i,s);if(!e)return t;if(sh.test(t))return t.replace(sh,e);const n=t.includes("?")?"&":"?";return`${t}${n}${e}`}(t.url,i)}getObjectType(t){const{type:i}=t;return"subtitle"===i?Er.TIMED_TEXT:"initSegment"===t.sn?Er.INIT:"audio"===i?Er.AUDIO:"main"===i?this.hls.audioTracks.length?Er.VIDEO:Er.MUXED:void 0}getTopBandwidth(t){let i,s=0;const e=this.hls;if(t===Er.AUDIO)i=e.audioTracks;else{const t=e.maxAutoLevel;i=e.levels.slice(0,t>-1?t+1:e.levels.length)}for(const t of i)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const i=this.hls.media,s=t===Er.AUDIO?this.audioBuffer:this.videoBuffer;return s&&i?1e3*js.bufferInfo(s,i.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){const{pLoader:t}=this.config,i=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,e){i(t),this.loader.load(t,s,e)}}}createFragmentLoader(){const{fLoader:t}=this.config,i=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,e){i(t),this.loader.load(t,s,e)}}}},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=I.log.bind(I,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.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 i=this.levels;i&&(this.levels=i.filter((i=>i!==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,i){const{contentSteering:s}=i;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,i){this.audioTracks=i.audioTracks,this.subtitleTracks=i.subtitleTracks}onError(t,i){const{errorAction:s}=i;if(2===(null==s?void 0:s.action)&&1===s.flags){const t=this.levels;let e=this.pathwayPriority,n=this.pathwayId;if(i.context){const{groupId:s,pathwayId:e,type:r}=i.context;s&&t?n=this.getPathwayForGroupId(s,r,n):e&&(n=e)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!e&&t&&(e=t.reduce(((t,i)=>(-1===t.indexOf(i.pathwayId)&&t.push(i.pathwayId),t)),[])),e&&e.length>1&&(this.updatePathwayPriority(e),s.resolved=this.pathwayId!==n),s.resolved||I.warn(`Could not resolve ${i.details} ("${i.error.message}") with content-steering for Pathway: ${n} levels: ${t?t.length:t} priorities: ${JSON.stringify(e)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let i=this.getLevelsForPathway(this.pathwayId);if(0===i.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),i=this.getLevelsForPathway(s),this.pathwayId=s}return i.length!==t.length&&this.log(`Found ${i.length}/${t.length} levels in Pathway "${this.pathwayId}"`),i}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((i=>t===i.pathwayId))}updatePathwayPriority(t){let i;this.pathwayPriority=t;const s=this.penalizedPathways,e=performance.now();Object.keys(s).forEach((t=>{e-s[t]>3e5&&delete s[t]}));for(let e=0;e<t.length;e++){const n=t[e];if(n in s)continue;if(n===this.pathwayId)return;const r=this.hls.nextLoadLevel,h=this.hls.levels[r];if(i=this.getLevelsForPathway(n),i.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,ls(i),this.hls.trigger(A.LEVELS_UPDATED,{levels:i});const t=this.hls.levels[r];h&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==h.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==h.bitrate&&this.log(`Unstable Pathways change from bitrate ${h.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=r);break}}}getPathwayForGroupId(t,i,s){const e=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<e.length;s++)if(i===Di&&e[s].hasAudioGroup(t)||i===Ci&&e[s].hasSubtitleGroup(t))return e[s].pathwayId;return s}clonePathways(t){const i=this.levels;if(!i)return;const s={},e={};t.forEach((t=>{const{ID:n,"BASE-ID":r,"URI-REPLACEMENT":h}=t;if(i.some((t=>t.pathwayId===n)))return;const o=this.getLevelsForPathway(r).map((t=>{const i=new O(t.attrs);i["PATHWAY-ID"]=n;const r=i.AUDIO&&`${i.AUDIO}_clone_${n}`,o=i.SUBTITLES&&`${i.SUBTITLES}_clone_${n}`;r&&(s[i.AUDIO]=r,i.AUDIO=r),o&&(e[i.SUBTITLES]=o,i.SUBTITLES=o);const a=nh(t.uri,i["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",h),l=new is({attrs:i,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:a,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let i=1;i<t.audioGroups.length;i++)l.addGroupId("audio",`${t.audioGroups[i]}_clone_${n}`);if(t.subtitleGroups)for(let i=1;i<t.subtitleGroups.length;i++)l.addGroupId("text",`${t.subtitleGroups[i]}_clone_${n}`);return l}));i.push(...o),eh(this.audioTracks,s,h,n),eh(this.subtitleTracks,e,h,n)}))}loadSteeringManifest(t){const i=this.hls.config,s=i.loader;let e;this.loader&&this.loader.destroy(),this.loader=new s(i);try{e=new self.URL(t)}catch(i){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==e.protocol){const t=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);e.searchParams.set("_HLS_pathway",this.pathwayId),e.searchParams.set("_HLS_throughput",""+t)}const n={responseType:"json",url:e.href},r=i.steeringManifestLoadPolicy.default,h=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},a={onSuccess:(t,i,s)=>{this.log(`Loaded steering manifest: "${e}"`);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":r,"PATHWAY-CLONES":h,"PATHWAY-PRIORITY":o}=n;if(r)try{this.uri=new self.URL(r,e).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${r}`)}this.scheduleRefresh(this.uri||s.url),h&&this.clonePathways(h);const a={steeringManifest:n,url:e.toString()};this.hls.trigger(A.STEERING_MANIFEST_LOADED,a),o&&this.updatePathwayPriority(o)},onError:(t,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${i.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${i.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||i.url,s);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const i=t.getResponseHeader("Retry-After");i&&(s=1e3*parseFloat(i))}this.log(`Steering manifest ${i.url} rate limited`)}},onTimeout:(t,i)=>{this.log(`Timeout loading steering manifest (${i.url})`),this.scheduleRefresh(this.uri||i.url)}};this.log(`Requesting steering manifest: ${e}`),this.loader.load(n,o,a)}scheduleRefresh(t,i=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var i;const s=null==(i=this.hls)?void 0:i.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),i)}}});function vh(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(vh):Object.keys(t).reduce(((i,s)=>(i[s]=vh(t[s]),i)),{}):t}let ph;class gh extends ws{constructor(t,i){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=i,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this),t.on(A.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this),t.off(A.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,i){this.resetLevels()}onManifestLoaded(t,i){const s=this.hls.config.preferManagedMediaSource,e=[],n={},r={};let h=!1,o=!1,a=!1;i.levels.forEach((t=>{var i,l;const c=t.attrs;let{audioCodec:u,videoCodec:d}=t;-1!==(null==(i=u)?void 0:i.indexOf("mp4a.40.34"))&&(ph||(ph=/chrome|firefox/i.test(navigator.userAgent)),ph&&(t.audioCodec=u=void 0)),u&&(t.audioCodec=u=fi(u,s)),0===(null==(l=d)?void 0:l.indexOf("avc1"))&&(d=t.videoCodec=function(t){const i=t.split(",");for(let t=0;t<i.length;t++){const s=i[t].split(".");if(s.length>2){let e=s.shift()+".";e+=parseInt(s.shift()).toString(16),e+=("000"+parseInt(s.shift()).toString(16)).slice(-4),i[t]=e}}return i.join(",")}(d));const{width:f,height:v,unknownCodecs:p}=t;if(h||(h=!(!f||!v)),o||(o=!!d),a||(a=!!u),null!=p&&p.length||u&&!hi(u,"audio",s)||d&&!hi(d,"video",s))return;const{CODECS:g,"FRAME-RATE":m,"HDCP-LEVEL":y,"PATHWAY-ID":w,RESOLUTION:b,"VIDEO-RANGE":k}=c,S=`${w||"."}-${t.bitrate}-${b}-${m}-${g}-${k}-${y}`;if(n[S])if(n[S].uri===t.url||t.attrs["PATHWAY-ID"])n[S].addGroupId("audio",c.AUDIO),n[S].addGroupId("text",c.SUBTITLES);else{const i=r[S]+=1;t.attrs["PATHWAY-ID"]=new Array(i+1).join(".");const s=new is(t);n[S]=s,e.push(s)}else{const i=new is(t);n[S]=i,r[S]=1,e.push(i)}})),this.filterAndSortMediaOptions(e,i,h,o,a)}filterAndSortMediaOptions(t,i,s,e,n){let r=[],h=[],o=t;if((s||e)&&n&&(o=o.filter((({videoCodec:t,videoRange:i,width:s,height:e})=>{return(!!t||!(!s||!e))&&!!(n=i)&&Qi.indexOf(n)>-1;var n}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){i.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(i.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:i.url,error:t,reason:t.message})}}));if(i.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;r=i.audioTracks.filter((i=>!i.audioCodec||hi(i.audioCodec,"audio",t))),mh(r)}i.subtitles&&(h=i.subtitles,mh(h));const a=o.slice(0);o.sort(((t,i)=>{if(t.attrs["HDCP-LEVEL"]!==i.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(i.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==i.height)return t.height-i.height;if(t.frameRate!==i.frameRate)return t.frameRate-i.frameRate;if(t.videoRange!==i.videoRange)return Qi.indexOf(t.videoRange)-Qi.indexOf(i.videoRange);if(t.videoCodec!==i.videoCodec){const s=li(t.videoCodec),e=li(i.videoCodec);if(s!==e)return e-s}if(t.uri===i.uri&&t.codecSet!==i.codecSet){const s=ci(t.codecSet),e=ci(i.codecSet);if(s!==e)return e-s}return t.averageBitrate!==i.averageBitrate?t.averageBitrate-i.averageBitrate:0}));let l=a[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==a.length))for(let t=0;t<a.length;t++)if(a[t].pathwayId===o[0].pathwayId){l=a[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===l){var c;this._firstLevel=t;const i=l.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${i}`),void 0===(null==(c=this.hls.userConfig)?void 0:c.abrEwmaDefaultEstimate)){const t=Math.min(i,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===fh.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const u={levels:o,audioTracks:r,subtitleTracks:h,sessionData:i.sessionData,sessionKeys:i.sessionKeys,firstLevel:this._firstLevel,stats:i.stats,audio:n,video:e,altAudio:!(n&&!e)&&r.some((t=>!!t.url))};this.hls.trigger(A.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 i=this._levels;if(0===i.length)return;if(t<0||t>=i.length){const s=new Error("invalid level idx"),e=t<0;if(this.hls.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:t,fatal:e,error:s,reason:s.message}),e)return;t=Math.min(t,i.length-1)}const s=this.currentLevelIndex,e=this.currentLevel,n=e?e.attrs["PATHWAY-ID"]:void 0,r=i[t],h=r.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=r,s===t&&r.details&&e&&n===h)return;this.log(`Switching to level ${t} (${r.height?r.height+"p ":""}${r.videoRange?r.videoRange+" ":""}${r.codecSet?r.codecSet+" ":""}@${r.bitrate})${h?" with Pathway "+h:""} from level ${s}${n?" with Pathway "+n:""}`),this.hls.trigger(A.LEVEL_SWITCHING,{level:t,attrs:r.attrs,details:r.details,bitrate:r.bitrate,averageBitrate:r.averageBitrate,maxBitrate:r.maxBitrate,realBitrate:r.realBitrate,width:r.width,height:r.height,codecSet:r.codecSet,audioCodec:r.audioCodec,videoCodec:r.videoCodec,audioGroups:r.audioGroups,subtitleGroups:r.subtitleGroups,loaded:r.loaded,loadError:r.loadError,fragmentError:r.fragmentError,name:r.name,id:r.id,uri:r.uri,url:r.url,urlId:0,audioGroupIds:r.audioGroupIds,textGroupIds:r.textGroupIds});const o=r.details;if(!o||o.live){const t=this.switchParams(r.uri,null==e?void 0:e.details,o);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,i){!i.fatal&&i.context&&i.context.type===xi&&i.context.level===this.level&&this.checkRetry(i)}onFragBuffered(t,{frag:i}){if(void 0!==i&&i.type===Ii){const t=i.elementaryStreams;if(!Object.keys(t).some((i=>!!t[i])))return;const s=this._levels[i.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,i){var s;const{level:e,details:n}=i,r=this._levels[e];var h;if(!r)return this.warn(`Invalid level index ${e}`),void(null!=(h=i.deliveryDirectives)&&h.skip&&(n.deltaUpdateFailed=!0));e===this.currentLevelIndex?(0===r.fragmentError&&(r.loadError=0),this.playlistLoaded(e,i,r.details)):null!=(s=i.deliveryDirectives)&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const i=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let e=s.uri;if(t)try{e=t.addDirectives(e)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const n=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${n?" Pathway "+n:""} ${e}`),this.clearTimer(),this.hls.trigger(A.LEVEL_LOADING,{url:e,level:i,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 i;const s=this._levels.filter(((i,s)=>s!==t||(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach((t=>t.level=-1))),!1)));ls(s),this._levels=s,this.currentLevelIndex>-1&&null!=(i=this.currentLevel)&&i.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(A.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:i}){this._levels=i}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:i,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(A.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function mh(t){const i={};t.forEach((t=>{const s=t.groupId||"";t.id=i[s]=i[s]||0,i[s]++}))}class yh{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[s].loader;if(e){var i;if(t&&t!==(null==(i=e.context)?void 0:i.frag.type))return;e.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[t];(i.mediaKeySessionContext||i.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[t].loader;i&&i.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,i=L.KEY_LOAD_ERROR,s,e,n){return new Ys({type:M.NETWORK_ERROR,details:i,fatal:!1,frag:t,response:n,error:s,networkDetails:e})}loadClear(t,i){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:e}=t;for(let t=0;t<i.length;t++){const n=i[t];if(e<=n.cc&&("initSegment"===s||"initSegment"===n.sn||s<n.sn)){this.emeController.selectKeySystemFormat(n).then((t=>{n.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then((i=>this.loadInternal(t,i))):this.loadInternal(t)}loadInternal(t,i){var s,e;i&&t.setKeyFormat(i);const n=t.decryptdata;if(!n){const s=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,s))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));let h=this.keyUriToKeyInfo[r];if(null!=(s=h)&&s.decryptdata.key)return n.key=h.decryptdata.key,Promise.resolve({frag:t,keyInfo:h});var o;if(null!=(e=h)&&e.keyLoadPromise)switch(null==(o=h.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return h.keyLoadPromise.then((i=>(n.key=i.keyInfo.decryptdata.key,{frag:t,keyInfo:h})))}switch(h=this.keyUriToKeyInfo[r]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(h,t):this.loadKeyEME(h,t);case"AES-128":return this.loadKeyHTTP(h,t);default:return Promise.reject(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(t,i){const s={frag:i,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(t.keyLoadPromise=i.then((i=>(t.mediaKeySessionContext=i,s)))).catch((i=>{throw t.keyLoadPromise=null,i}))}return Promise.resolve(s)}loadKeyHTTP(t,i){const s=this.config,e=new(0,s.loader)(s);return i.keyLoader=t.loader=e,t.keyLoadPromise=new Promise(((n,r)=>{const h={keyInfo:t,frag:i,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,a={onSuccess:(t,i,s,e)=>{const{frag:h,keyInfo:o,url:a}=s;if(!h.decryptdata||o!==this.keyUriToKeyInfo[a])return r(this.createKeyLoadError(h,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),e));o.decryptdata.key=h.decryptdata.key=new Uint8Array(t.data),h.keyLoader=null,o.loader=null,n({frag:h,keyInfo:o})},onError:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),e,k({url:h.url,data:void 0},t)))},onTimeout:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),e))},onAbort:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,L.INTERNAL_ABORTED,new Error("key loading aborted"),e))}};e.load(h,{loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},a)}))}resetLoader(t){const{frag:i,keyInfo:s,url:e}=t,n=s.loader;i.keyLoader===n&&(i.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[e],n&&n.destroy()}}function wh(){return self.SourceBuffer||self.WebKitSourceBuffer}function bh(){if(!ni())return!1;const t=wh();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class kh{constructor(t,i,s,e){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=i,this.fragmentTracker=s,this.hls=e}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,i){const{config:s,media:e,stalled:n}=this;if(null===e)return;const{currentTime:r,seeking:h}=e,o=this.seeking&&!h,a=!this.seeking&&h;if(this.seeking=h,r!==t){if(this.moved=!0,h||(this.nudgeRetry=0),null!==n){if(this.stallReported){const t=self.performance.now()-n;I.warn(`playback not stuck anymore @${r}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(a||o)return void(this.stalled=null);if(e.paused&&!h||e.ended||0===e.playbackRate||!js.getBuffered(e).length)return void(this.nudgeRetry=0);const l=js.bufferInfo(e,r,0),c=l.nextStart||0;if(h){const t=l.len>2,s=!c||i&&i.start<=r||c-r>2&&!this.fragmentTracker.getPartialFragment(r);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;if(!(l.len>0||c))return;const t=Math.max(c,l.start||0)-r,i=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==i||null==(u=i.details)?void 0:u.live)?2*i.details.targetduration:2,n=this.fragmentTracker.getPartialFragment(r);if(t>0&&(t<=s||n))return void(e.paused||this._trySkipBufferHole(n))}const d=self.performance.now();if(null===n)return void(this.stalled=d);const f=d-n;if(!h&&f>=250&&(this._reportStall(l),!this.media))return;const v=js.bufferInfo(e,r,s.maxBufferHole);this._tryFixBufferStall(v,f)}_tryFixBufferStall(t,i){const{config:s,fragmentTracker:e,media:n}=this;if(null===n)return;const r=n.currentTime,h=e.getPartialFragment(r);(!h||!this._trySkipBufferHole(h)&&this.media)&&(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-r<s.maxBufferHole)&&i>1e3*s.highBufferWatchdogPeriod&&(I.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:i,media:s,stallReported:e}=this;if(!e&&s){this.stallReported=!0;const e=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);I.warn(e.message),i.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:e,buffer:t.len})}}_trySkipBufferHole(t){const{config:i,hls:s,media:e}=this;if(null===e)return 0;const n=e.currentTime,r=js.bufferInfo(e,n,0),h=n<r.start?r.start:r.nextStart;if(h){const o=h-n;if(o>0&&(r.len<=i.maxBufferHole||r.len>0&&r.len<1&&e.readyState<3)){if(o>i.maxBufferHole){const{fragmentTracker:i}=this;let s=!1;if(0===n){const t=i.getAppendedFrag(0,Ii);t&&h<t.end&&(s=!0)}if(!s){const s=t||i.getAppendedFrag(n,Ii);if(s){let t=!1,e=s.end;for(;e<h;){const s=i.getPartialFragment(e);if(!s){t=!0;break}e+=s.duration}if(t)return 0}}}const r=Math.max(h+.05,n+.1);if(I.warn(`skipping hole, adjusting currentTime from ${n} to ${r}`),this.moved=!0,this.stalled=null,e.currentTime=r,t&&!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${r}`);s.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:t})}return r}}return 0}_tryNudgeBuffer(){const{config:t,hls:i,media:s,nudgeRetry:e}=this;if(null===s)return;const n=s.currentTime;if(this.nudgeRetry++,e<t.nudgeMaxRetry){const r=n+(e+1)*t.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${n} to ${r}`);I.warn(h.message),s.currentTime=r,i.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${t.nudgeMaxRetry} nudges`);I.error(s.message),i.trigger(A.ERROR,{type:M.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class Sh extends fe{constructor(t,i,s){super(t,i,s,"[stream-controller]",Ii),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(A.MANIFEST_LOADING,this.onManifestLoading,this),t.on(A.MANIFEST_PARSED,this.onManifestParsed,this),t.on(A.LEVEL_LOADING,this.onLevelLoading,this),t.on(A.LEVEL_LOADED,this.onLevelLoaded,this),t.on(A.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(A.ERROR,this.onError,this),t.on(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(A.BUFFER_CREATED,this.onBufferCreated,this),t.on(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(A.MANIFEST_LOADING,this.onManifestLoading,this),t.off(A.MANIFEST_PARSED,this.onManifestParsed,this),t.off(A.LEVEL_LOADED,this.onLevelLoaded,this),t.off(A.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(A.ERROR,this.onError,this),t.off(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(A.BUFFER_CREATED,this.onBufferCreated,this),t.off(A.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(A.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this.loadedmetadata=!1}i>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=se,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=ie}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case de:{const{levels:t,level:i}=this,s=null==t?void 0:t[i],e=null==s?void 0:s.details;if(e&&(!e.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(e))break;this.state=se;break}if(this.hls.nextLoadLevel!==this.level){this.state=se;break}break}case re:{var t;const i=self.performance.now(),s=this.retryDate;if(!s||i>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:i}=this;this.resetStartWhenNotLoaded((null==t?void 0:t[i])||null),this.state=se}}}this.state===se&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:i,levels:s,media:e}=this;if(null===i||!e&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const n=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[n])return;const r=s[n],h=this.getMainFwdBufferInfo();if(null===h)return;const o=this.getLevelDetails();if(o&&this._streamEnded(h,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(A.BUFFER_EOS,t),void(this.state=le)}if(!this.buffering)return;t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const a=r.details;if(!a||this.state===de||a.live&&this.levelLastLoaded!==r)return this.level=n,void(this.state=de);const l=h.len,c=this.getMaxBufferLength(r.maxBitrate);if(l>=c)return;this.backtrackFragment&&this.backtrackFragment.start>h.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:h.end;let d=this.getNextFragment(u,a);if(this.couldBacktrack&&!this.fragPrevious&&d&&"initSegment"!==d.sn&&this.fragmentTracker.getState(d)!==Os){var f;const t=(null!=(f=this.backtrackFragment)?f:d).sn,i=a.fragments[t-a.startSN-1];i&&d.cc===i.cc&&(d=i,this.fragmentTracker.removeFragment(i))}else this.backtrackFragment&&h.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,u)){if(!d.gap){const t=this.audioOnly&&!this.altAudio?B:j,i=(t===j?this.videoBuffer:this.mediaBuffer)||this.media;i&&this.afterBufferFlushed(i,t,Ii)}d=this.getNextFragmentLoopLoading(d,a,h,Ii,c)}d&&(!d.initSegment||d.initSegment.data||this.bitrateTest||(d=d.initSegment),this.loadFragment(d,r,u))}loadFragment(t,i,s){const e=this.fragmentTracker.getState(t);this.fragCurrent=t,e===Is||e===Ps?"initSegment"===t.sn?this._loadInitSegment(t,i):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,i)):(this.startFragRequested=!0,super.loadFragment(t,i,s)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Ii)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:i}=this;if(null!=i&&i.readyState){let s;const e=this.getAppendedFrag(i.currentTime);e&&e.start>1&&this.flushMainBuffer(0,e.start-1);const n=this.getLevelDetails();if(null!=n&&n.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*n.targetduration)return}if(!i.paused&&t){const i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*t[this.hls.nextLoadLevel].maxBitrate/(1e3*i)+1:0}else s=0;const r=this.getBufferedFrag(i.currentTime+s);if(r){const t=this.followingBufferedFrag(r);if(t){this.abortCurrentFrag();const i=t.duration,s=Math.max(r.end,(t.maxStartPTS?t.maxStartPTS:t.start)+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,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 ee:case ne:case re:case oe:case ae:this.state=se}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,i){super.flushMainBuffer(t,i,this.altAudio?"video":null)}onMediaAttached(t,i){super.onMediaAttached(t,i);const s=i.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 kh(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,i=t?t.currentTime:null;T(i)&&this.log(`Media seeked to ${i.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(A.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,i){let s=!1,e=!1;i.levels.forEach((t=>{const i=t.audioCodec;i&&(s=s||-1!==i.indexOf("mp4a.40.2"),e=e||-1!==i.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&e&&!function(){var t;const i=wh();return"function"==typeof(null==i||null==(t=i.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=i.levels,this.startFragRequested=!1}onLevelLoading(t,i){const{levels:s}=this;if(!s||this.state!==se)return;const e=s[i.level];(!e.details||e.details.live&&this.levelLastLoaded!==e||this.waitForCdnTuneIn(e.details))&&(this.state=de)}onLevelLoaded(t,i){var s;const{levels:e}=this,n=i.level,r=i.details,h=r.totalduration;if(!e)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""}, cc [${r.startCC}, ${r.endCC}] duration:${h}`);const o=e[n],a=this.fragCurrent;!a||this.state!==ne&&this.state!==re||a.level!==i.level&&a.loader&&this.abortCurrentFrag();let l=0;if(r.live||null!=(s=o.details)&&s.live){var c;if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;l=this.alignPlaylists(r,o.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(o.details=r,this.levelLastLoaded=o,this.hls.trigger(A.LEVEL_UPDATED,{details:r,level:n}),this.state===de){if(this.waitForCdnTuneIn(r))return;this.state=se}this.startFragRequested?r.live&&this.synchronizeToLiveEdge(r):this.setStartPosition(r,l),this.tick()}_handleFragmentLoadProgress(t){var i;const{frag:s,part:e,payload:n}=t,{levels:r}=this;if(!r)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 h=r[s.level],o=h.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 a=h.videoCodec,l=o.PTSKnown||!o.live,c=null==(i=s.initSegment)?void 0:i.data,u=this._getAudioCodec(h),d=this.transmuxer=this.transmuxer||new bn(this.hls,Ii,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=e?e.index:-1,v=new _s(s.level,s.sn,s.stats.chunkCount,n.byteLength,f,-1!==f);d.push(n,c,u,a,s,e,o.totalduration,l,v,this.initPTS[s.cc])}onAudioTrackSwitching(t,i){const s=this.altAudio;if(!i.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(A.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(A.AUDIO_TRACK_SWITCHED,i)}}onAudioTrackSwitched(t,i){const s=!!this.hls.audioTracks[i.id].url;if(s){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=s,this.tick()}onBufferCreated(t,i){const s=i.tracks;let e,n,r=!1;for(const t in s){const i=s[t];if("main"===i.id){if(n=t,e=i,"video"===t){const i=s[t];i&&(this.videoBuffer=i.buffer)}}else r=!0}r&&e?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=e.buffer):this.mediaBuffer=this.media}onFragBuffered(t,i){const{frag:s,part:e}=i;if(s&&s.type!==Ii)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${e?" p: "+e.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===ae&&(this.state=se));const n=e?e.stats:s.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,e)}onError(t,i){var s;if(i.fatal)this.state=ce;else switch(i.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ii,i);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==de||(null==(s=i.context)?void 0:s.type)!==xi||(this.state=se);break;case L.BUFFER_APPEND_ERROR:case L.BUFFER_FULL_ERROR:if(!i.parent||"main"!==i.parent)return;if(i.details===L.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(i)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}checkBuffer(){const{media:t,gapController:i}=this;t&&i&&t.readyState&&(!this.loadedmetadata&&js.getBuffered(t).length||i.poll(this.lastCurrentTime,this.state!==se?this.fragCurrent:null),this.lastCurrentTime=t.currentTime)}onFragLoadEmergencyAborted(){this.state=se,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:i}){(i!==B||this.audioOnly&&!this.altAudio)&&(this.afterBufferFlushed((i===j?this.videoBuffer:this.mediaBuffer)||this.media,i,Ii),this.tick())}onLevelsUpdated(t,i){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=i.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const i=t.currentTime;let s=this.startPosition;if(s>=0&&i<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${i}`);const e=js.getBuffered(t),n=(e.length?e.start(0):0)-s;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),s+=n,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${i}`),t.currentTime=s}}_getAudioCodec(t){let i=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&i&&(this.log("Swapping audio codec"),i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),i}_loadBitrateTestFrag(t,i){t.bitrateTest=!0,this._doFragLoad(t,i).then((s=>{const{hls:e}=this;if(!s||this.fragContextChanged(t))return;i.fragmentError=0,this.state=se,this.startFragRequested=!1,this.bitrateTest=!1;const n=t.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),e.trigger(A.FRAG_LOADED,s),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var i;const s="main",{hls:e}=this,{remuxResult:n,chunkMeta:r}=t,h=this.getCurrentContext(r);if(!h)return void this.resetWhenMissingContext(r);const{frag:o,part:a,level:l}=h,{video:c,text:u,id3:d,initSegment:f}=n,{details:v}=l,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=oe,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,f.tracks,t,r),e.trigger(A.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:f.tracks})}const t=f.initPTS,i=f.timescale;T(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:i},e.trigger(A.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:i}))}if(c&&v&&"initSegment"!==o.sn){const t=v.fragments[o.sn-1-v.startSN],i=o.sn===v.startSN,s=!t||o.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:e,startDTS:n,endDTS:h}=c;if(a)a.elementaryStreams[c.type]={startPTS:t,endPTS:e,startDTS:n,endDTS:h};else if(c.firstKeyFrame&&c.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),c.dropped&&c.independent){const n=this.getMainFwdBufferInfo(),r=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole;if(!i&&r<(c.firstKeyFramePTS?c.firstKeyFramePTS:t)-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(c.type,o.start,e,o.start,h,!0)}else i&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(c.type,t,e,n,h),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,a,r,i||s)}else{if(!i&&!s)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:t,endPTS:i,startDTS:s,endDTS:e}=p;a&&(a.elementaryStreams[B]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(B,t,i,s,e),this.bufferFragmentData(p,o,a,r)}v&&null!=d&&null!=(i=d.samples)&&i.length&&e.trigger(A.FRAG_PARSING_METADATA,{id:s,frag:o,details:v,samples:d.samples}),v&&u&&e.trigger(A.FRAG_PARSING_USERDATA,{id:s,frag:o,details:v,samples:u.samples})}}_bufferInitSegment(t,i,s,e){if(this.state!==oe)return;this.audioOnly=!!i.audio&&!i.video,this.altAudio&&!this.audioOnly&&delete i.audio;const{audio:n,video:r,audiovideo:h}=i;if(n){let i=t.audioCodec;const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=n.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===s.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==n.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),t.audioCodec&&t.audioCodec!==i&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${i}"`),n.levelCodec=i,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${i||""}/${t.audioCodec||""}/${n.codec}]`)}r&&(r.levelCodec=t.videoCodec,r.id="main",this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${t.videoCodec||""}/${r.codec}]`)),h&&this.log(`Init audiovideo buffer, container:${h.container}, codecs[level/parsed]=[${t.codecs}/${h.codec}]`),this.hls.trigger(A.BUFFER_CODECS,i),Object.keys(i).forEach((t=>{const n=i[t].initSegment;null!=n&&n.byteLength&&this.hls.trigger(A.BUFFER_APPENDING,{type:t,data:n,frag:s,part:null,chunkMeta:e,parent:s.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Ii)}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=se}checkFragmentChanged(){const t=this.media;let i=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(js.isBuffered(t,s)?i=this.getAppendedFrag(s):js.isBuffered(t,s+.1)&&(i=this.getAppendedFrag(s+.1)),i){this.backtrackFragment=null;const t=this.fragPlaying,s=i.level;t&&i.sn===t.sn&&t.level===s||(this.fragPlaying=i,this.hls.trigger(A.FRAG_CHANGED,{frag:i}),t&&t.level===s||this.hls.trigger(A.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 i=t.currentTime,s=this.currentFrag;if(s&&T(i)&&T(s.programDateTime))return new Date(s.programDateTime+1e3*(i-s.start))}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 Th{static get version(){return"1.5.20"}static isMSESupported(){return bh()}static isSupported(){return function(){if(!bh())return!1;const t=ni();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((i=>t.isTypeSupported(ai(i,"video"))))||["mp4a.40.2","fLaC"].some((i=>t.isTypeSupported(ai(i,"audio")))))}()}static getMediaSource(){return ni()}static get Events(){return A}static get ErrorTypes(){return M}static get ErrorDetails(){return L}static get DefaultConfig(){return Th.defaultConfig?Th.defaultConfig:fh}static set DefaultConfig(t){Th.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 wn,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){if("object"==typeof console&&!0===t||"object"==typeof t){!function(t,...i){i.forEach((function(i){C[i]=t[i]?t[i].bind(t):function(t){const i=self.console[t];return i?i.bind(self.console,`[${t}] >`):x}(i)}))}(t,"debug","log","info","warn","error");try{C.log('Debug logs enabled for "Hls instance" in hls.js version 1.5.20')}catch(t){C=D}}else C=D}(t.debug||!1);const i=this.config=function(t,i){if((i.liveSyncDurationCount||i.liveMaxLatencyDurationCount)&&(i.liveSyncDuration||i.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==i.liveMaxLatencyDurationCount&&(void 0===i.liveSyncDurationCount||i.liveMaxLatencyDurationCount<=i.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==i.liveMaxLatencyDuration&&(void 0===i.liveSyncDuration||i.liveMaxLatencyDuration<=i.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=vh(t),e=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,r=void 0===i[n],h=[];e.forEach((e=>{const o=`${t}Loading${e}`,a=i[o];if(void 0!==a&&r){h.push(o);const t=s[n].default;switch(i[n]={default:t},e){case"TimeOut":t.maxLoadTimeMs=a,t.maxTimeToFirstByteMs=a;break;case"MaxRetry":t.errorRetry.maxNumRetry=a,t.timeoutRetry.maxNumRetry=a;break;case"RetryDelay":t.errorRetry.retryDelayMs=a,t.timeoutRetry.retryDelayMs=a;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=a,t.timeoutRetry.maxRetryDelayMs=a}}})),h.length&&I.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(i[n])}`)})),k(k({},s),i)}(Th.DefaultConfig,t);this.userConfig=t,i.progressive&&function(t){const i=t.loader;i!==ah&&i!==hh?(I.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=ah,t.progressive=!0,t.enableSoftwareAES=!0,I.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i);const{abrController:s,bufferController:e,capLevelController:n,errorController:r,fpsController:h}=i,o=new r(this),a=this.abrController=new s(this),l=this.bufferController=new e(this),c=this.capLevelController=new n(this),u=new h(this),d=new Ui(this),f=new qi(this),v=i.contentSteeringController,p=v?new v(this):null,g=this.levelController=new gh(this,p),m=new Ns(this),y=new yh(this.config),w=this.streamController=new Sh(this,m,y);c.setStreamController(w),u.setStreamController(w);const b=[d,g,w];p&&b.splice(1,0,p),this.networkControllers=b;const S=[a,l,c,u,f,m];this.audioTrackController=this.createController(i.audioTrackController,b);const T=i.audioStreamController;T&&b.push(new T(this,m,y)),this.subtitleTrackController=this.createController(i.subtitleTrackController,b);const $=i.subtitleStreamController;$&&b.push(new $(this,m,y)),this.createController(i.timelineController,S),y.emeController=this.emeController=this.createController(i.emeController,S),this.cmcdController=this.createController(i.cmcdController,S),this.latencyController=this.createController(Yi,S),this.coreComponents=S,b.push(o);const E=o.onErrorOut;"function"==typeof E&&this.on(A.ERROR,E,o)}createController(t,i){if(t){const s=new t(this);return i&&i.push(s),s}return null}on(t,i,s=this){this._emitter.on(t,i,s)}once(t,i,s=this){this._emitter.once(t,i,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,i,s=this,e){this._emitter.off(t,i,s,e)}listeners(t){return this._emitter.listeners(t)}emit(t,i,s){return this._emitter.emit(t,i,s)}trigger(t,i){if(this.config.debug)return this.emit(t,t,i);try{return this.emit(t,t,i)}catch(i){I.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.triggeringException||(this.triggeringException=!0,this.trigger(A.ERROR,{type:M.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:t===A.ERROR,event:t,error:i}),this.triggeringException=!1)}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){I.log("destroy"),this.trigger(A.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){I.log("attachMedia"),this._media=t,this.trigger(A.MEDIA_ATTACHING,{media:t})}detachMedia(){I.log("detachMedia"),this.trigger(A.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const i=this.media,s=this.url,e=this.url=w.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,I.log(`loadSource:${e}`),i&&s&&(s!==e||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(A.MANIFEST_LOADING,{url:t})}startLoad(t=-1){I.log(`startLoad(${t})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t),this.started&&this.networkControllers);i++);}stopLoad(){I.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}resumeBuffering(){I.log("resume buffering"),this.networkControllers.forEach((t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){I.log("pause buffering"),this.networkControllers.forEach((t=>{t.pauseBuffering&&t.pauseBuffering()}))}swapAudioCodec(){I.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){I.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){I.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){I.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){I.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){I.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){I.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 i=!!t;i!==this.config.capLevelToPlayerSize&&(i?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}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&&(I.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Ji.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:i}}=this;if(!t)return 0;const s=t.length;for(let e=0;e<s;e++)if(t[e].maxBitrate>=i)return e;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:i,maxHdcpLevel:s}=this;let e;if(e=-1===i&&null!=t&&t.length?t.length-1:i,s)for(let i=e;i--;){const e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=s)return i}return e}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 i;return null==(i=this.audioTrackController)?void 0:i.setAudioOption(t)}setSubtitleOption(t){var i;return null==(i=this.subtitleTrackController)||i.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 i=this.audioTrackController;i&&(i.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 i=this.subtitleTrackController;i&&(i.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const i=this.subtitleTrackController;i&&(i.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 $h(t){const i=Math.floor(t/3600),s=Math.floor(t%3600/60),e=Math.floor(t%60);return i>0?`${i}:${s.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`:`${s}:${e.toString().padStart(2,"0")}`}Th.defaultConfig=void 0;var Eh=function(t,i,s,e){var n,r=arguments.length,h=r<3?i:null===e?e=Object.getOwnPropertyDescriptor(i,s):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)h=Reflect.decorate(t,i,s,e);else for(var o=t.length-1;o>=0;o--)(n=t[o])&&(h=(r<3?n(h):r>3?n(i,s,h):n(i,s))||h);return r>3&&h&&Object.defineProperty(i,s,h),h};const Ah=class{constructor(i){t(this,i),this.apiError=e(this,"rtkApiError",7),this.statsIntervalTimer=null,this.t=r(),this.iconPack=h,this.isSupported=!0,this.playerState=a.IDLE,this.livestreamState="IDLE",this.livestreamId=null,this.audioPlaybackError=!1,this.qualityLevels=[],this.selectedQuality=-1,this.currentTime=0,this.duration=0,this.hideControls=!0,this.hideControlsTimeout=null,this.livestreamUpdateListener=t=>{this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=t},this.updateProgress=()=>{this.currentTime=this.videoRef.currentTime},this.updateHlsStatsPeriodically=()=>{var t,i;this.duration=((null===(t=this.videoRef)||void 0===t?void 0:t.currentTime)||0)+((null===(i=this.hls)||void 0===i?void 0:i.latency)||0)},this.fastForwardToLatest=()=>{this.videoRef.currentTime=this.duration-1},this.togglePlay=()=>{this.videoRef.paused?(this.videoRef.play(),this.playerState=a.PLAYING):(this.videoRef.pause(),this.playerState=a.IDLE)},this.changeQuality=t=>{this.selectedQuality=t,this.hls&&(this.hls.currentLevel=t)},this.cleanupPlayer=()=>{var t;this.playerState=a.IDLE,this.videoRef&&(null===(t=this.hls)||void 0===t||t.destroy(),this.hls=null)},this.onMouseMovePlayer=()=>{this.hideControls=!1,clearTimeout(this.hideControlsTimeout),this.hideControlsTimeout=setTimeout((()=>{this.hideControls=!0}),5e3)},this.getLoadingState=()=>{let t="",i=!1,s=!1;switch(this.livestreamState){case"IDLE":t=this.t("livestream.idle"),i=!0,s=!1;break;case"STARTING":t=this.t("livestream.starting"),i=!0,s=!0;break;case"STOPPING":t=this.t("livestream.stopping"),i=!0,s=!0;break;case"LIVESTREAMING":this.playerState!==a.PLAYING&&this.playerState!==a.PAUSED&&(t=this.t("livestream.starting"),s=!0,i=!0);break;default:i=!1,t=this.t(""),s=!0}return{isLoading:i,loadingMessage:t,showIcon:s}},this.getErrorState=()=>{var t,i;let s=!1,e="";return"LIVESTREAMING"!==this.livestreamState?(s=!1,e=this.t(""),{isError:s,errorMessage:e}):(this.isSupported||(s=!0,e=this.t("livestream.error.not_supported")),this.playbackUrl||(s=!0,e=this.t("livestream.error.not_found")),this.playerError&&(s=!0,e=this.t(null!==(i=null===(t=this.playerError)||void 0===t?void 0:t.message)&&void 0!==i?i:"livestream.error.unknown")),{isError:s,errorMessage:e})},this.initialiseAndPlayStream=async()=>{try{this.meeting.__internals__.logger.info(`rtk-livestream-player:: About to initialise HLS. VideoRef? ${!!this.videoRef} playbackUrl: ${this.playbackUrl}`),Th.isSupported()?(this.meeting.__internals__.logger.info("rtk-livestream-player:: Initialising HLS. HLS is Supported"),this.hls=new Th({lowLatencyMode:!1}),window.rtk_hls=this.hls,this.meeting.__internals__.logger.info("rtk-livestream-player:: Loading source"),this.hls.loadSource(this.playbackUrl),this.meeting.__internals__.logger.info("rtk-livestream-player:: Attaching video element to HLS"),this.hls.attachMedia(this.videoRef),this.meeting.__internals__.logger.info("rtk-livestream-player:: Waiting async for HLS manifest parsing"),this.hls.on(Th.Events.ERROR,((t,i)=>{if(i.fatal){if(this.meeting.__internals__.logger.error(`rtk-livestream-player:: fatal error: ${i.details}`,{error:i.error}),this.playbackUrl&&"LIVESTREAMING"===this.livestreamState)return void setTimeout((()=>{this.playbackUrl&&"LIVESTREAMING"===this.livestreamState&&(this.meeting.__internals__.logger.info("rtk-livestream-player:: Retrying playbackUrl"),this.hls.loadSource(this.playbackUrl))}),5e3)}else this.meeting.__internals__.logger.warn(`rtk-livestream-player:: non-fatal error: ${i.details}`,{error:i.error})})),this.hls.on(Th.Events.MEDIA_ATTACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media attached")})),this.hls.on(Th.Events.MEDIA_DETACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media detached")})),this.hls.on(Th.Events.DESTROYING,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: hls is getting destroyed")})),this.hls.on(Th.Events.MANIFEST_PARSED,(async(t,i)=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: HLS manifest parsed");const{levels:s,autoLevelChangeAllowed:e}=l({meeting:this.meeting,hlsLevels:i.levels});this.qualityLevels=s.map(((t,i)=>({level:i,resolution:t.height?`${t.height}p`:"auto"}))),e&&(this.qualityLevels=[{level:-1,resolution:"Auto"},...this.qualityLevels]),this.hls.currentLevel=this.qualityLevels[0].level;try{this.meeting.__internals__.logger.info("rtk-livestream-player:: About to start video."),await this.videoRef.play(),this.meeting.__internals__.logger.info("rtk-livestream-player:: Video has started playing."),this.playerState=a.PLAYING}catch(t){this.audioPlaybackError=!0,this.meeting.__internals__.logger.error("rtk-livestream-player:: Video couldn't start. Trying with user gesture again.",{error:t})}})),this.videoRef.addEventListener("timeupdate",this.updateProgress),this.statsIntervalTimer=setInterval(this.updateHlsStatsPeriodically,1e3)):this.isSupported=!1}catch(t){this.meeting.__internals__.logger.error("rtk-livestream-player:: HLS couldn't initialise.",{error:t})}}}async updateLivestreamId(){const t=this.meeting.livestream.playbackUrl;if(!t||"LIVESTREAMING"!==this.livestreamState)return this.playbackUrl=null,this.livestreamId=null,void this.cleanupPlayer();const i=t.split("/"),s=i.findIndex((t=>"manifest"===t));this.livestreamId=i[s-1],await this.conditionallyStartLivestreamViewer()}async conditionallyStartLivestreamViewer(){this.videoRef&&this.playbackUrl&&!this.hls&&await this.initialiseAndPlayStream()}async connectedCallback(){this.meetingChanged(this.meeting)}disconnectedCallback(){this.meeting.livestream.removeListener("livestreamUpdate",this.livestreamUpdateListener),this.videoRef.removeEventListener("timeupdate",this.updateProgress),clearInterval(this.statsIntervalTimer),this.videoRef=null,this.hls&&this.hls.destroy(),window.rtk_hls=null}meetingChanged(t){null!=t&&(this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=this.meeting.livestream.state,this.meeting.livestream.on("livestreamUpdate",this.livestreamUpdateListener))}render(){var t,e;if(!o(this.meeting))return;const{isError:n,errorMessage:r}=this.getErrorState(),{isLoading:h,loadingMessage:l,showIcon:c}=this.getLoadingState();return i(s,null,i("div",{class:"player-container h-full max-h-full min-h-full w-full min-w-full max-w-full"},i("div",{ref:async t=>{this.videoContainerRef=t},class:"video-container relative flex h-full w-full flex-col items-center justify-center pb-20"},i("video",{onMouseMove:this.onMouseMovePlayer,ref:async t=>{this.videoRef=t,await this.conditionallyStartLivestreamViewer()},id:"livestream-video",style:{height:`${null===(t=this.el)||void 0===t?void 0:t.clientHeight}px`},controls:!1,onPlay:()=>{this.playerState===a.PAUSED&&(this.playerState=a.PLAYING)},onPause:()=>this.playerState=a.PAUSED}),this.playerState!==a.IDLE&&!this.hideControls&&i("div",{class:"control-bar",style:{width:`${null===(e=this.videoRef)||void 0===e?void 0:e.clientWidth}px`}},i("div",{class:"control-groups"},i("rtk-icon",{id:"playPause",onClick:this.togglePlay,size:"lg",class:"control-btn",icon:this.playerState===a.PLAYING?this.iconPack.pause:this.iconPack.play}),i("rtk-icon",{size:"lg",class:"control-btn",icon:this.iconPack.fastForward,onClick:this.fastForwardToLatest}),i("span",{class:"timings"},$h(this.currentTime)," /"," ",$h(this.duration))),i("div",{class:"control-groups"},i("select",{class:"level-select",onChange:t=>this.changeQuality(parseInt(t.target.value))},this.qualityLevels.map((t=>i("option",{value:t.level,selected:this.selectedQuality===t.level},t.resolution)))),i("rtk-fullscreen-toggle",{id:"fullscreen",class:"control-btn fullscreen-btn",targetElement:this.videoContainerRef,size:"sm",iconPack:this.iconPack,t:this.t,ref:t=>{var i;const s=document.createElement("style");s.textContent="\n rtk-controlbar-button {\n display: contents;\n background-color: var(--bg-brand-500);\n color: var(--text-text-on-brand);\n }\n ",null===(i=null==t?void 0:t.shadowRoot)||void 0===i||i.appendChild(s)}})))),this.audioPlaybackError&&i("div",{class:"unmute-popup"},i("h3",null,this.t("audio_playback.title")),i("p",null,this.t("audio_playback.description")),i("rtk-button",{kind:"wide",onClick:()=>{this.audioPlaybackError=!1,this.videoRef&&(this.videoRef.muted=!1,this.videoRef.play(),this.playerState=a.PLAYING)},title:this.t("audio_playback")},this.t("audio_playback"))),n&&i("div",{class:"loader"},i("rtk-icon",{icon:this.iconPack.warning}),i("p",null,r)),!n&&h&&i("div",{class:"loader"},c&&i("rtk-spinner",{id:"icon",part:"spinner",iconPack:this.iconPack,size:"md"}),i("p",null,l))))}get el(){return n(this)}static get watchers(){return{livestreamState:["updateLivestreamId"],meeting:["meetingChanged"]}}};Eh([c()],Ah.prototype,"meeting",void 0),Eh([c()],Ah.prototype,"size",void 0),Eh([c()],Ah.prototype,"t",void 0),Eh([c()],Ah.prototype,"iconPack",void 0),Ah.style=":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{display:flex;height:100%;max-height:100%;min-height:100%;width:100%;min-width:100%;max-width:100%;border-radius:var(--rtk-border-radius-md, 8px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity))}.player-container{position:relative;margin:var(--rtk-space-4, 16px);display:flex;flex-grow:1;align-items:center;justify-content:center;border-radius:var(--rtk-border-radius-md, 8px)}.loader{position:absolute;z-index:10;height:100%;width:100%;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity));display:flex;flex-direction:column;align-items:center;justify-content:center}p{margin-top:var(--rtk-space-1, 4px);margin-bottom:var(--rtk-space-1, 4px);font-size:16px;color:rgb(var(--rtk-colors-text-700, 255 255 255 / 0.64))}.unmute-popup{position:absolute;z-index:30 !important;display:flex;width:var(--rtk-space-72, 288px);flex-direction:column;border-radius:var(--rtk-border-radius-md, 8px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-800, 30 30 30) / var(--tw-bg-opacity));padding:var(--rtk-space-4, 16px);text-align:center;max-width:70%}.unmute-popup h3{margin:var(--rtk-space-0, 0px);font-size:16px;font-weight:500}.unmute-popup p{margin-top:var(--rtk-space-3, 12px);margin-bottom:var(--rtk-space-3, 12px);font-size:14px}.control-bar{position:absolute;bottom:0;display:flex;height:auto;justify-content:space-between;align-items:center;padding:10px 10px 0px 10px;z-index:10;}.timings{color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)))}.control-btn{border:none;margin-right:var(--rtk-space-2, 8px);border-radius:var(--rtk-border-radius-sm, 4px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)));cursor:pointer;font-size:24px;height:30px;width:30px}.fullscreen-btn{margin-right:20px;height:30px}.control-btn:hover{opacity:0.8}.control-btn:focus{outline:none}.control-groups{display:flex;align-items:center;justify-content:space-around}#livestream-video{aspect-ratio:16/9;max-width:100%;min-width:100%;left:var(--rtk-space-0, 0px);z-index:20;aspect-ratio:16 / 9;width:auto;border-radius:var(--rtk-border-radius-md, 8px);border-width:0px}.level-select{border-radius:var(--rtk-border-radius-sm, 4px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)));border:none;padding:5px 10px;font-size:14px;height:30px;cursor:pointer;border-radius:5px;margin-right:10px}.level-select:focus{outline:none}.level-select option{border-radius:var(--rtk-border-radius-sm, 4px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));color:rgb(var(--rtk-colors-text-on-brand-1000, var(--rtk-colors-text-1000, 255 255 255)))}.volume-control-holder{display:flex;justify-content:center;align-items:center}";var Mh=function(t,i,s,e){var n,r=arguments.length,h=r<3?i:null===e?e=Object.getOwnPropertyDescriptor(i,s):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)h=Reflect.decorate(t,i,s,e);else for(var o=t.length-1;o>=0;o--)(n=t[o])&&(h=(r<3?n(h):r>3?n(i,s,h):n(i,s))||h);return r>3&&h&&Object.defineProperty(i,s,h),h};const Lh=class{constructor(i){t(this,i),this.variant="primary",this.iconPack=h,this.t=r(),this.viewerCount=0,this.disconnectMeeting=t=>{var i;null!=t&&null!=this.countListener&&(null===(i=t.livestream)||void 0===i||i.removeListener("viewerCountUpdate",this.countListener))}}connectedCallback(){this.meetingChanged(this.meeting)}disconnectedCallback(){this.disconnectMeeting(this.meeting)}meetingChanged(t,i){var s;this.disconnectMeeting(i),null!=t&&(this.countListener=()=>{var i;this.viewerCount=null===(i=t.livestream)||void 0===i?void 0:i.viewerCount},this.countListener(),null===(s=t.livestream)||void 0===s||s.addListener("viewerCountUpdate",this.countListener))}render(){return o(this.meeting)?i(s,{tabIndex:0,role:"log","aria-label":`${this.viewerCount} ${this.t("viewers")}`},i("rtk-icon",{icon:this.iconPack.viewers,tabIndex:-1,"aria-hidden":!0,part:"icon"}),this.viewerCount," ",this.t("viewers")):i(s,{"data-hidden":!0})}static get watchers(){return{meeting:["meetingChanged"]}}};Mh([c()],Lh.prototype,"meeting",void 0),Mh([c()],Lh.prototype,"iconPack",void 0),Mh([c()],Lh.prototype,"t",void 0),Lh.style=":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{display:inline-flex;height:var(--rtk-space-10, 40px);-webkit-user-select:none;-moz-user-select:none;user-select:none;align-items:center;font-size:14px}:host([data-hidden]){display:none}:host([size='sm']){font-size:12px}rtk-icon{margin-right:var(--rtk-space-1, 4px);height:var(--rtk-space-5, 20px);width:var(--rtk-space-5, 20px)}:host([size='sm']) rtk-icon{height:var(--rtk-space-4, 16px);width:var(--rtk-space-4, 16px)}:host([variant='embedded']){--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-1000, 8 8 8) / var(--tw-bg-opacity));opacity:0.5;margin-top:var(--rtk-space-1, 4px);margin-left:var(--rtk-space-1, 4px);height:var(--rtk-space-5, 20px);border-radius:var(--rtk-border-radius-sm, 4px);padding-left:var(--rtk-space-2, 8px);padding-right:var(--rtk-space-2, 8px);font-size:12px}:host([variant='embedded']) rtk-icon{height:var(--rtk-space-4, 16px);width:var(--rtk-space-4, 16px)}";export{d as rtk_livestream_indicator,Ah as rtk_livestream_player,Lh as rtk_viewer_count}
|