@cloudflare/realtimekit-ui 1.1.0-staging.1 → 1.1.0-staging.10
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-7bb3e1fd.js → TextMessage-1dc6f8b9.js} +1 -1
- package/dist/cjs/{chat-717e517d.js → chat-2ae6f058.js} +1 -1
- package/dist/cjs/{config-8c9ac89a.js → config-0a88d50b.js} +2 -2
- package/dist/cjs/{debounce-a3e0d9e7.js → debounce-b06b27ca.js} +1 -1
- package/dist/cjs/{index-8d07e125.js → index-e4244d7d.js} +1 -1
- package/dist/cjs/index.cjs.js +6 -5
- package/dist/cjs/loader.cjs.js +1 -1
- package/dist/cjs/{merge-73e2770b.js → merge-c46cfa17.js} +1 -1
- package/dist/cjs/{notification-567fe887.js → notification-f3750b61.js} +1 -1
- 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 +3 -3
- package/dist/cjs/rtk-ai.cjs.entry.js +2 -2
- package/dist/cjs/rtk-audio-grid.cjs.entry.js +3 -3
- 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_24.cjs.entry.js +430 -301
- package/dist/cjs/rtk-breakout-room-manager_3.cjs.entry.js +6 -6
- package/dist/cjs/rtk-breakout-rooms-manager_9.cjs.entry.js +11 -11
- package/dist/cjs/rtk-breakout-rooms-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-camera-selector_2.cjs.entry.js +2 -2
- 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-creator.cjs.entry.js +4 -4
- package/dist/cjs/rtk-channel-details.cjs.entry.js +3 -3
- package/dist/cjs/rtk-channel-header.cjs.entry.js +2 -2
- package/dist/cjs/rtk-channel-selector-ui.cjs.entry.js +6 -6
- package/dist/cjs/rtk-chat-composer-ui.cjs.entry.js +3 -3
- package/dist/cjs/rtk-chat-message.cjs.entry.js +4 -4
- package/dist/cjs/rtk-chat-messages-ui.cjs.entry.js +5 -5
- package/dist/cjs/rtk-chat-search-results.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 +30 -25
- package/dist/cjs/rtk-clock.cjs.entry.js +5 -5
- package/dist/cjs/rtk-controlbar-button.cjs.entry.js +3 -3
- package/dist/cjs/rtk-controlbar.cjs.entry.js +3 -3
- package/dist/cjs/rtk-debugger-audio_4.cjs.entry.js +2 -2
- package/dist/cjs/rtk-debugger-toggle.cjs.entry.js +3 -3
- package/dist/cjs/rtk-dialog-manager.cjs.entry.js +2 -2
- package/dist/cjs/rtk-dialog.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 +3 -3
- package/dist/cjs/rtk-file-message_3.cjs.entry.js +12 -12
- 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 +3 -3
- package/dist/cjs/rtk-idle-screen.cjs.entry.js +3 -3
- package/dist/cjs/rtk-image-viewer.cjs.entry.js +3 -3
- package/dist/cjs/rtk-information-tooltip.cjs.entry.js +3 -3
- package/dist/cjs/rtk-leave-button.cjs.entry.js +3 -3
- 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-logo.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 +6 -6
- 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 +4 -4
- package/dist/cjs/rtk-mute-all-button.cjs.entry.js +2 -2
- package/dist/cjs/rtk-name-tag.cjs.entry.js +3 -3
- package/dist/cjs/rtk-network-indicator.cjs.entry.js +2 -2
- package/dist/cjs/rtk-notification.cjs.entry.js +6 -6
- package/dist/cjs/rtk-notifications.cjs.entry.js +8 -5
- 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 +17 -17
- package/dist/cjs/rtk-participants-audio.cjs.entry.js +3 -3
- package/dist/cjs/rtk-participants-stage-list_4.cjs.entry.js +3 -3
- package/dist/cjs/rtk-participants-toggle.cjs.entry.js +3 -3
- package/dist/cjs/rtk-participants.cjs.entry.js +3 -3
- package/dist/cjs/rtk-pip-toggle.cjs.entry.js +2 -2
- package/dist/cjs/rtk-plugin-main_2.cjs.entry.js +3 -3
- 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 +2 -2
- 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 +2 -2
- package/dist/cjs/rtk-sidebar-ui.cjs.entry.js +4 -4
- package/dist/cjs/rtk-sidebar.cjs.entry.js +3 -3
- package/dist/cjs/rtk-simple-grid.cjs.entry.js +2 -2
- 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 +13 -3
- package/dist/cjs/rtk-waiting-screen.cjs.entry.js +3 -3
- package/dist/cjs/{sidebar-2ad915b1.js → sidebar-0eb1e4ef.js} +1 -1
- package/dist/cjs/{ui-store-1cb28da8.js → ui-store-6c2d680f.js} +11 -2
- 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-avatar/rtk-avatar.js +1 -1
- package/dist/collection/components/rtk-breakout-room-participants/rtk-breakout-room-participants.js +2 -2
- package/dist/collection/components/rtk-broadcast-message-modal/rtk-broadcast-message-modal.js +2 -2
- package/dist/collection/components/rtk-channel-creator/rtk-channel-creator.js +2 -2
- package/dist/collection/components/rtk-channel-details/rtk-channel-details.js +1 -1
- package/dist/collection/components/rtk-channel-selector-ui/rtk-channel-selector-ui.js +2 -2
- package/dist/collection/components/rtk-channel-selector-view/rtk-channel-selector-view.css +29 -29
- package/dist/collection/components/rtk-channel-selector-view/rtk-channel-selector-view.js +4 -4
- package/dist/collection/components/rtk-chat/rtk-chat.css +47 -8
- package/dist/collection/components/rtk-chat/rtk-chat.js +98 -13
- package/dist/collection/components/rtk-chat-composer-view/rtk-chat-composer-view.js +28 -15
- package/dist/collection/components/rtk-chat-message/rtk-chat-message.js +2 -2
- package/dist/collection/components/rtk-chat-messages-ui/rtk-chat-messages-ui.js +3 -3
- package/dist/collection/components/rtk-chat-messages-ui-paginated/rtk-chat-messages-ui-paginated.js +37 -17
- package/dist/collection/components/rtk-chat-search-results/rtk-chat-search-results.js +1 -1
- package/dist/collection/components/rtk-chat-toggle/rtk-chat-toggle.css +1 -1
- package/dist/collection/components/rtk-chat-toggle/rtk-chat-toggle.js +27 -26
- package/dist/collection/components/rtk-clock/rtk-clock.js +3 -3
- package/dist/collection/components/rtk-confirmation-modal/rtk-confirmation-modal.js +1 -1
- package/dist/collection/components/rtk-controlbar/rtk-controlbar.js +1 -1
- package/dist/collection/components/rtk-controlbar-button/rtk-controlbar-button.js +1 -1
- package/dist/collection/components/rtk-counter/rtk-counter.js +2 -2
- package/dist/collection/components/rtk-debugger-toggle/rtk-debugger-toggle.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-file-dropzone/rtk-file-dropzone.js +1 -1
- package/dist/collection/components/rtk-file-message/rtk-file-message.js +2 -2
- package/dist/collection/components/rtk-file-message-view/rtk-file-message-view.js +1 -1
- package/dist/collection/components/rtk-file-picker-button/rtk-file-picker-button.js +1 -1
- package/dist/collection/components/rtk-header/rtk-header.js +1 -1
- package/dist/collection/components/rtk-icon/rtk-icon.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 +4 -4
- package/dist/collection/components/rtk-image-message-view/rtk-image-message-view.js +3 -3
- package/dist/collection/components/rtk-image-viewer/rtk-image-viewer.js +1 -1
- package/dist/collection/components/rtk-information-tooltip/rtk-information-tooltip.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 +2 -2
- package/dist/collection/components/rtk-markdown-view/rtk-markdown-view.js +1 -1
- package/dist/collection/components/rtk-meeting/rtk-meeting.js +37 -0
- package/dist/collection/components/rtk-menu/rtk-menu.js +2 -2
- package/dist/collection/components/rtk-menu-item/rtk-menu-item.css +6 -1
- package/dist/collection/components/rtk-menu-item/rtk-menu-item.js +23 -1
- package/dist/collection/components/rtk-menu-list/rtk-menu-list.css +15 -4
- package/dist/collection/components/rtk-menu-list/rtk-menu-list.js +23 -1
- package/dist/collection/components/rtk-message-list-view/rtk-message-list-view.js +3 -3
- package/dist/collection/components/rtk-message-view/rtk-message-view.css +30 -22
- package/dist/collection/components/rtk-message-view/rtk-message-view.js +72 -2
- package/dist/collection/components/rtk-more-toggle/rtk-more-toggle.js +2 -2
- 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-notification/rtk-notification.js +2 -2
- package/dist/collection/components/rtk-notifications/rtk-notifications.js +4 -1
- package/dist/collection/components/rtk-overlay-modal/rtk-overlay-modal.js +1 -1
- package/dist/collection/components/rtk-paginated-list/rtk-paginated-list.css +5 -5
- package/dist/collection/components/rtk-paginated-list/rtk-paginated-list.js +327 -264
- package/dist/collection/components/rtk-participant/rtk-participant.js +12 -12
- package/dist/collection/components/rtk-participant-setup/rtk-participant-setup.js +2 -2
- package/dist/collection/components/rtk-participants-audio/rtk-participants-audio.js +1 -1
- package/dist/collection/components/rtk-participants-stage-list/rtk-participants-stage-list.js +1 -1
- package/dist/collection/components/rtk-permissions-message/rtk-permissions-message.js +1 -1
- package/dist/collection/components/rtk-plugins/rtk-plugins.js +1 -1
- package/dist/collection/components/rtk-poll/rtk-poll.js +1 -1
- package/dist/collection/components/rtk-poll-form/rtk-poll-form.js +2 -2
- package/dist/collection/components/rtk-polls/rtk-polls.js +3 -3
- package/dist/collection/components/rtk-recording-indicator/rtk-recording-indicator.js +1 -1
- package/dist/collection/components/rtk-screenshare-view/rtk-screenshare-view.js +5 -5
- package/dist/collection/components/rtk-settings-toggle/rtk-settings-toggle.js +1 -1
- package/dist/collection/components/rtk-sidebar-ui/rtk-sidebar-ui.js +2 -2
- package/dist/collection/components/rtk-spinner/rtk-spinner.js +1 -1
- package/dist/collection/components/rtk-spotlight-grid/rtk-spotlight-grid.js +2 -2
- package/dist/collection/components/rtk-stage/rtk-stage.js +1 -1
- package/dist/collection/components/rtk-switch/rtk-switch.js +1 -1
- 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 +1 -1
- package/dist/collection/components/rtk-text-message/rtk-text-message.js +2 -2
- package/dist/collection/components/rtk-text-message-view/rtk-text-message-view.js +1 -1
- package/dist/collection/components/rtk-tooltip/rtk-tooltip.js +1 -1
- package/dist/collection/components/rtk-transcript/rtk-transcript.js +1 -1
- package/dist/collection/components/rtk-ui-provider/rtk-ui-provider.js +37 -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 +1 -1
- package/dist/collection/exports.js +2 -1
- package/dist/collection/lib/overrides.js +6 -0
- package/dist/collection/utils/flags.js +0 -1
- package/dist/collection/utils/sync-with-store/ui-store.js +4 -1
- package/dist/components/index.js +6 -6
- package/dist/components/{p-6f340109.js → p-05df465d.js} +1 -1
- package/dist/components/{p-9e87b2c9.js → p-0a31ef52.js} +2 -2
- package/dist/components/{p-618864a0.js → p-107e55c1.js} +3 -3
- package/dist/components/{p-5f26bba3.js → p-193d8051.js} +2 -2
- package/dist/components/{p-d3de8b85.js → p-19b037c5.js} +4 -4
- package/dist/components/{p-8d25843a.js → p-1a9e3806.js} +3 -3
- package/dist/components/{p-82f8c924.js → p-1afc54bb.js} +3 -3
- package/dist/components/{p-afe77b50.js → p-1da807a2.js} +3 -3
- package/dist/components/{p-2f08d7eb.js → p-210862ae.js} +98 -37
- package/dist/components/{p-abe1dbe6.js → p-2309fb19.js} +4 -4
- package/dist/components/{p-f8f5cb31.js → p-2447a26f.js} +4 -4
- package/dist/components/{p-63ef7ea4.js → p-282e8e83.js} +7 -7
- package/dist/components/{p-ee98bbaf.js → p-33be3c19.js} +13 -13
- package/dist/components/{p-adf73364.js → p-33e73313.js} +6 -6
- package/dist/components/{p-121e073d.js → p-35e93724.js} +2 -2
- package/dist/components/{p-bb8f2597.js → p-395ef9c8.js} +7 -7
- package/dist/components/{p-f47894a6.js → p-3972098e.js} +21 -27
- package/dist/components/{p-10ef077c.js → p-39e8b34a.js} +3 -3
- package/dist/components/{p-e81fc1e8.js → p-3e58e0f3.js} +3 -3
- package/dist/components/{p-0b4e526c.js → p-43bf8953.js} +4 -4
- package/dist/components/p-44a203bd.js +409 -0
- package/dist/components/{p-190db142.js → p-44c32349.js} +8 -8
- package/dist/components/{p-2d08ab28.js → p-45b4f6a1.js} +4 -4
- package/dist/components/{p-9889bee5.js → p-46d99dd9.js} +4 -4
- package/dist/components/{p-65cd2fe3.js → p-524d7900.js} +5 -5
- package/dist/components/{p-0d7bf41b.js → p-5476e3f3.js} +4 -4
- package/dist/components/{p-914563e7.js → p-586482a8.js} +6 -6
- package/dist/components/{p-fd68a52b.js → p-5f1b84f7.js} +9 -9
- package/dist/components/{p-d06d1eac.js → p-600579a6.js} +3 -3
- package/dist/components/{p-6f272732.js → p-6392204c.js} +9 -9
- package/dist/components/{p-a94b2e67.js → p-6739a399.js} +2 -2
- package/dist/components/{p-f7eb9c47.js → p-6c02b0d0.js} +6 -6
- package/dist/components/{p-c515acba.js → p-6f361314.js} +3 -3
- package/dist/components/{p-47c25f64.js → p-6f7c46d2.js} +1 -1
- package/dist/components/{p-84e5b453.js → p-6f8d2043.js} +2 -2
- package/dist/components/{p-080acf18.js → p-7148ec6a.js} +7 -4
- package/dist/components/{p-33a87325.js → p-72fffe3e.js} +3 -3
- package/dist/components/{p-3b29dda1.js → p-73baf5ba.js} +1 -1
- package/dist/components/{p-2f82e0b0.js → p-74356882.js} +8 -8
- package/dist/components/{p-fe911889.js → p-7a27fdb5.js} +20 -11
- package/dist/components/{p-b011763d.js → p-7b6356e2.js} +4 -4
- package/dist/components/{p-5c92df32.js → p-7bde2b2d.js} +6 -6
- package/dist/components/{p-6c2cfa0d.js → p-7c8096c2.js} +5 -5
- package/dist/components/{p-a6296b02.js → p-819cb785.js} +7 -4
- package/dist/components/{p-6756b222.js → p-851b90a6.js} +3 -3
- package/dist/components/{p-e4a080a5.js → p-89151c7a.js} +4 -4
- package/dist/components/{p-244cbe7b.js → p-89eb65a9.js} +2 -2
- package/dist/components/{p-c3621e10.js → p-92729e09.js} +7 -7
- package/dist/components/{p-cf503999.js → p-977f9875.js} +5 -5
- package/dist/components/{p-f4e75ea9.js → p-9bdc24b8.js} +5 -5
- package/dist/components/{p-188bfe87.js → p-abdff498.js} +9 -9
- package/dist/components/{p-78b61cce.js → p-ad873f2d.js} +1 -1
- package/dist/components/{p-d107e9f4.js → p-b6869c32.js} +4 -4
- package/dist/components/{p-395d7140.js → p-b76e3950.js} +5 -5
- package/dist/components/{p-102b6df8.js → p-c05530c8.js} +2 -2
- package/dist/components/p-c78c26b1.js +203 -0
- package/dist/components/{p-88bef213.js → p-cf8f725b.js} +1 -1
- package/dist/components/{p-c078ae06.js → p-d188f58b.js} +3 -3
- package/dist/components/{p-2e282643.js → p-d9f6db4f.js} +5 -5
- package/dist/components/{p-51de7af3.js → p-da87cc71.js} +1 -1
- package/dist/components/{p-0d582365.js → p-dc3143c0.js} +2 -2
- package/dist/components/{p-4d582a90.js → p-dd89aff2.js} +6 -6
- package/dist/components/{p-7481511c.js → p-dfb42075.js} +3 -3
- package/dist/components/{p-e675729a.js → p-e375b50d.js} +5 -5
- package/dist/components/{p-0a35a909.js → p-e443d803.js} +4 -4
- package/dist/components/{p-a6f2b402.js → p-e4888ccc.js} +31 -31
- package/dist/components/{p-a10b9faa.js → p-e552dc59.js} +3 -3
- package/dist/components/{p-55501201.js → p-e57e8041.js} +5 -5
- package/dist/components/{p-b34865c7.js → p-e64e3cec.js} +5 -5
- package/dist/components/{p-3da4880c.js → p-e72a0f16.js} +5 -5
- package/dist/components/{p-7fc0dc2f.js → p-e847fee9.js} +11 -3
- package/dist/components/{p-b882f4a1.js → p-ecb016da.js} +5 -5
- package/dist/components/{p-a4a5ff5a.js → p-edd12f2f.js} +6 -6
- package/dist/components/{p-563c785d.js → p-eeb37b16.js} +3 -3
- package/dist/components/{p-dbfc9151.js → p-f0e4633e.js} +4 -4
- package/dist/components/{p-a29c01fc.js → p-f6c2e822.js} +3 -3
- package/dist/components/{p-20290b0b.js → p-f7bd10f1.js} +5 -5
- package/dist/components/{p-e8df7ac5.js → p-fa5aba68.js} +19 -19
- package/dist/components/{p-488d88a8.js → p-fb7666ce.js} +5 -5
- package/dist/components/{p-fa8f6b4a.js → p-fb836f65.js} +1 -1
- package/dist/components/{p-e6710b76.js → p-fb900e8f.js} +4 -4
- package/dist/components/{p-f7430e46.js → p-fefc57f9.js} +6 -6
- package/dist/components/rtk-ai-toggle.js +5 -5
- package/dist/components/rtk-ai-transcriptions.js +1 -1
- package/dist/components/rtk-ai.js +4 -4
- package/dist/components/rtk-audio-grid.js +3 -3
- 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-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 +7 -7
- package/dist/components/rtk-channel-details.js +1 -1
- package/dist/components/rtk-channel-header.js +8 -8
- package/dist/components/rtk-channel-selector-ui.js +7 -7
- package/dist/components/rtk-channel-selector-view.js +1 -1
- package/dist/components/rtk-chat-composer-ui.js +7 -7
- 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 +17 -17
- package/dist/components/rtk-chat-search-results.js +14 -14
- package/dist/components/rtk-chat-selector-ui.js +3 -3
- package/dist/components/rtk-chat-toggle.js +34 -30
- package/dist/components/rtk-chat.js +1 -1
- package/dist/components/rtk-clock.js +6 -6
- package/dist/components/rtk-confirmation-modal.js +1 -1
- package/dist/components/rtk-controlbar-button.js +1 -1
- package/dist/components/rtk-controlbar.js +3 -3
- 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 +6 -6
- package/dist/components/rtk-debugger-video.js +1 -1
- package/dist/components/rtk-debugger.js +1 -1
- package/dist/components/rtk-dialog-manager.js +23 -23
- 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 +4 -4
- 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 +4 -4
- package/dist/components/rtk-grid.js +9 -9
- package/dist/components/rtk-header.js +3 -3
- package/dist/components/rtk-icon.js +1 -1
- package/dist/components/rtk-idle-screen.js +6 -6
- 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 +4 -4
- package/dist/components/rtk-join-stage.js +1 -1
- package/dist/components/rtk-leave-button.js +6 -6
- 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-markdown-view.js +1 -1
- package/dist/components/rtk-meeting-title.js +3 -3
- package/dist/components/rtk-meeting.js +40 -28
- 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 +7 -7
- 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 +7 -7
- package/dist/components/rtk-more-toggle.js +7 -7
- 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 +9 -6
- 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 +5 -5
- 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 +15 -15
- 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 +6 -6
- package/dist/components/rtk-screenshare-view.js +9 -9
- 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 +11 -11
- package/dist/components/rtk-setup-screen.js +7 -7
- package/dist/components/rtk-sidebar-ui.js +1 -1
- package/dist/components/rtk-sidebar.js +10 -10
- package/dist/components/rtk-simple-grid.js +2 -2
- 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 +17 -5
- 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 +372 -82
- package/dist/docs/docs-vscode.json +42 -1
- package/dist/esm/{TextMessage-ca92045e.js → TextMessage-0d8be8c5.js} +1 -1
- package/dist/esm/{chat-ff185374.js → chat-b2bea75f.js} +1 -1
- package/dist/esm/{config-e684aa4d.js → config-325caca3.js} +2 -2
- package/dist/esm/{debounce-3ea4df36.js → debounce-3139f9e3.js} +1 -1
- package/dist/esm/{index-e65afca5.js → index-6eb882e7.js} +1 -1
- package/dist/esm/index.js +7 -7
- package/dist/esm/loader.js +584 -428
- package/dist/esm/{merge-7ffc04b3.js → merge-bc2a0775.js} +1 -1
- package/dist/esm/{notification-78afaabf.js → notification-4beb1e0d.js} +1 -1
- 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 +3 -3
- package/dist/esm/rtk-ai.entry.js +2 -2
- package/dist/esm/rtk-audio-grid.entry.js +3 -3
- 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_24.entry.js +430 -301
- package/dist/esm/rtk-breakout-room-manager_3.entry.js +6 -6
- package/dist/esm/rtk-breakout-rooms-manager_9.entry.js +11 -11
- package/dist/esm/rtk-breakout-rooms-toggle.entry.js +2 -2
- package/dist/esm/rtk-camera-selector_2.entry.js +2 -2
- 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-creator.entry.js +4 -4
- package/dist/esm/rtk-channel-details.entry.js +3 -3
- package/dist/esm/rtk-channel-header.entry.js +2 -2
- package/dist/esm/rtk-channel-selector-ui.entry.js +6 -6
- package/dist/esm/rtk-chat-composer-ui.entry.js +3 -3
- package/dist/esm/rtk-chat-message.entry.js +4 -4
- package/dist/esm/rtk-chat-messages-ui.entry.js +5 -5
- package/dist/esm/rtk-chat-search-results.entry.js +3 -3
- package/dist/esm/rtk-chat-selector-ui.entry.js +3 -3
- package/dist/esm/rtk-chat-toggle.entry.js +30 -25
- package/dist/esm/rtk-clock.entry.js +5 -5
- package/dist/esm/rtk-controlbar-button.entry.js +3 -3
- package/dist/esm/rtk-controlbar.entry.js +3 -3
- package/dist/esm/rtk-debugger-audio_4.entry.js +2 -2
- package/dist/esm/rtk-debugger-toggle.entry.js +3 -3
- package/dist/esm/rtk-dialog-manager.entry.js +2 -2
- package/dist/esm/rtk-dialog.entry.js +2 -2
- package/dist/esm/rtk-ended-screen.entry.js +2 -2
- package/dist/esm/rtk-file-dropzone.entry.js +3 -3
- package/dist/esm/rtk-file-message_3.entry.js +12 -12
- 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 +3 -3
- package/dist/esm/rtk-idle-screen.entry.js +3 -3
- package/dist/esm/rtk-image-viewer.entry.js +3 -3
- package/dist/esm/rtk-information-tooltip.entry.js +3 -3
- package/dist/esm/rtk-leave-button.entry.js +3 -3
- 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-logo.entry.js +2 -2
- package/dist/esm/rtk-meeting-title.entry.js +2 -2
- package/dist/esm/rtk-message-list-view.entry.js +6 -6
- 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 +4 -4
- package/dist/esm/rtk-mute-all-button.entry.js +2 -2
- package/dist/esm/rtk-name-tag.entry.js +3 -3
- package/dist/esm/rtk-network-indicator.entry.js +2 -2
- package/dist/esm/rtk-notification.entry.js +6 -6
- package/dist/esm/rtk-notifications.entry.js +8 -5
- 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 +17 -17
- package/dist/esm/rtk-participants-audio.entry.js +3 -3
- package/dist/esm/rtk-participants-stage-list_4.entry.js +3 -3
- package/dist/esm/rtk-participants-toggle.entry.js +3 -3
- package/dist/esm/rtk-participants.entry.js +3 -3
- package/dist/esm/rtk-pip-toggle.entry.js +2 -2
- package/dist/esm/rtk-plugin-main_2.entry.js +3 -3
- 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 +2 -2
- 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 +2 -2
- package/dist/esm/rtk-sidebar-ui.entry.js +4 -4
- package/dist/esm/rtk-sidebar.entry.js +3 -3
- package/dist/esm/rtk-simple-grid.entry.js +2 -2
- 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 +13 -3
- package/dist/esm/rtk-waiting-screen.entry.js +3 -3
- package/dist/esm/{sidebar-030fff49.js → sidebar-376c9917.js} +1 -1
- package/dist/esm/{ui-store-9e486e1b.js → ui-store-12132d9c.js} +11 -3
- package/dist/realtimekit-ui/index.esm.js +1 -1
- package/dist/realtimekit-ui/{p-385fddbd.entry.js → p-00445029.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-74e1b5a6.entry.js → p-05d1b9d5.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-95f05e26.entry.js → p-0baa78d7.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-12e4cb4a.js → p-11a469d9.js} +1 -1
- package/dist/realtimekit-ui/{p-8f512d69.entry.js → p-14569a57.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-2b373e53.entry.js → p-1462cbd9.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-2fc5ef84.entry.js → p-1669c53d.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-b387e9a1.entry.js → p-1834416c.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-0b8c47d9.entry.js → p-1fe6003b.entry.js} +1 -1
- package/dist/realtimekit-ui/p-21d4bb9c.entry.js +1 -0
- package/dist/realtimekit-ui/{p-61a53713.entry.js → p-2441260e.entry.js} +1 -1
- package/dist/realtimekit-ui/p-25c4d10f.js +1 -0
- package/dist/realtimekit-ui/{p-53ac3d30.entry.js → p-2b054928.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-62e0a141.entry.js → p-30dcb4cc.entry.js} +1 -1
- package/dist/realtimekit-ui/p-322957ed.entry.js +1 -0
- package/dist/realtimekit-ui/{p-36c8dfa0.entry.js → p-323d1aa4.entry.js} +1 -1
- package/dist/realtimekit-ui/p-342b4926.entry.js +1 -0
- package/dist/realtimekit-ui/p-369648b9.entry.js +1 -0
- package/dist/realtimekit-ui/{p-4eba1baa.entry.js → p-3dd04263.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-60a29b69.entry.js → p-3f4120cc.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-3a325310.entry.js → p-426bf45e.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-a9126c12.entry.js → p-43530cd3.entry.js} +1 -1
- package/dist/realtimekit-ui/p-44531a97.entry.js +1 -0
- package/dist/realtimekit-ui/p-4485414e.entry.js +1 -0
- package/dist/realtimekit-ui/p-44d69c6b.entry.js +1 -0
- package/dist/realtimekit-ui/p-45f90b95.js +1 -0
- package/dist/realtimekit-ui/{p-951a7b06.entry.js → p-48c87789.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-949b2b6a.entry.js → p-4b33b435.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-8b189438.entry.js → p-4b638184.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-9ad2c746.entry.js → p-515a17ce.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-7b999408.entry.js → p-532e1a53.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-38f4773b.entry.js → p-53680d55.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-5383fe87.entry.js → p-54a88fdf.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-c7711712.entry.js → p-573187b4.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-f5aa8af7.entry.js → p-5892c1e0.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-54a31e02.entry.js → p-5b00a8fa.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-aa70de39.entry.js → p-612a8d25.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-6adb2de4.entry.js → p-616dc312.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-a9dd63ef.entry.js → p-639601b7.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-c638f666.entry.js → p-64206b62.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-1666857d.entry.js → p-67ead213.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-882d07c9.entry.js → p-685adc5f.entry.js} +1 -1
- package/dist/realtimekit-ui/p-6896e819.entry.js +1 -0
- package/dist/realtimekit-ui/{p-09869644.entry.js → p-6914a616.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-9cbf286a.entry.js → p-701cdf1b.entry.js} +1 -1
- package/dist/realtimekit-ui/p-7108d1cd.entry.js +1 -0
- package/dist/realtimekit-ui/{p-a319e81f.entry.js → p-75f53ae6.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-c1b81873.entry.js → p-7a9a226e.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-3d0c4257.entry.js → p-7d01d588.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-8b341608.entry.js → p-80e51a73.entry.js} +1 -1
- package/dist/realtimekit-ui/p-820dad23.entry.js +1 -0
- package/dist/realtimekit-ui/p-85b3c0c4.entry.js +1 -0
- package/dist/realtimekit-ui/{p-f0f6c282.entry.js → p-85b45c3b.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-2a0ec1c6.entry.js → p-8778b3e6.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-c5c965b8.entry.js → p-94a37c73.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-3369f405.entry.js → p-95fb25d6.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-80c856cd.js → p-9b550ec4.js} +1 -1
- package/dist/realtimekit-ui/{p-643194e4.entry.js → p-a0d39ea3.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-639ab9ad.entry.js → p-a1408db4.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-d0384d90.entry.js → p-a40cc665.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-084b6f30.js → p-a5900df2.js} +1 -1
- package/dist/realtimekit-ui/{p-a1203856.entry.js → p-a67e2a25.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-31f58b98.entry.js → p-a680da64.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-61a16ccf.entry.js → p-a7172c2d.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-91ea043c.js → p-a7e0277f.js} +1 -1
- package/dist/realtimekit-ui/p-a852e0cf.entry.js +1 -0
- package/dist/realtimekit-ui/{p-ae7319ac.entry.js → p-a9190330.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-7613857e.entry.js → p-ac6c8ebe.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-e7b83772.entry.js → p-ad5e9fdb.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-98ee3341.entry.js → p-af58f450.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-6a45f305.js → p-afa7211c.js} +1 -1
- package/dist/realtimekit-ui/{p-4eee77b0.entry.js → p-b25f7d7b.entry.js} +1 -1
- package/dist/realtimekit-ui/p-b51e813e.entry.js +1 -0
- package/dist/realtimekit-ui/{p-38aec474.entry.js → p-be03944b.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-3eefefa3.entry.js → p-be5bdd0a.entry.js} +1 -1
- package/dist/realtimekit-ui/p-bf717b8c.entry.js +1 -0
- package/dist/realtimekit-ui/p-c5f704a3.entry.js +1 -0
- package/dist/realtimekit-ui/{p-de75d48d.entry.js → p-c8773db0.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-5a2d8313.entry.js → p-cb54bd67.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-ba51770e.entry.js → p-cc226b51.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-91fd286c.js → p-cd0c5440.js} +1 -1
- package/dist/realtimekit-ui/{p-e925ca8a.entry.js → p-cd56beb7.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-d7f16f24.entry.js → p-cda276d6.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-93b84c22.js → p-d3e520e5.js} +1 -1
- package/dist/realtimekit-ui/p-d880fb69.entry.js +1 -0
- package/dist/realtimekit-ui/{p-11c964cf.entry.js → p-e0c73820.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-e62593a2.entry.js → p-e5b426fa.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-61d3f74f.entry.js → p-e78ba202.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-7786e9a7.entry.js → p-ebfde234.entry.js} +1 -1
- package/dist/realtimekit-ui/p-ec5ed8a4.entry.js +1 -0
- package/dist/realtimekit-ui/{p-9c1f42dd.entry.js → p-f266302c.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-d9cad67f.entry.js → p-f32aecbc.entry.js} +1 -1
- package/dist/realtimekit-ui/{p-7f76de48.entry.js → p-f6c82f1b.entry.js} +1 -1
- package/dist/realtimekit-ui/p-fa86682c.entry.js +1 -0
- package/dist/realtimekit-ui/{p-788f26c4.entry.js → p-fcb7a6e2.entry.js} +1 -1
- package/dist/realtimekit-ui/realtimekit-ui.esm.js +1 -1
- package/dist/types/components/rtk-chat/rtk-chat.d.ts +6 -1
- package/dist/types/components/rtk-chat-composer-view/rtk-chat-composer-view.d.ts +1 -0
- package/dist/types/components/rtk-chat-messages-ui-paginated/rtk-chat-messages-ui-paginated.d.ts +2 -0
- package/dist/types/components/rtk-chat-toggle/rtk-chat-toggle.d.ts +4 -6
- package/dist/types/components/rtk-meeting/rtk-meeting.d.ts +4 -0
- package/dist/types/components/rtk-menu-item/rtk-menu-item.d.ts +2 -0
- package/dist/types/components/rtk-menu-list/rtk-menu-list.d.ts +2 -0
- package/dist/types/components/rtk-message-view/rtk-message-view.d.ts +7 -0
- package/dist/types/components/rtk-paginated-list/rtk-paginated-list.d.ts +55 -54
- package/dist/types/components/rtk-ui-provider/rtk-ui-provider.d.ts +4 -1
- package/dist/types/components.d.ts +84 -7
- package/dist/types/exports.d.ts +2 -1
- package/dist/types/lib/overrides.d.ts +16 -0
- package/dist/types/utils/flags.d.ts +0 -1
- package/dist/types/utils/sync-with-store/ui-store.d.ts +4 -1
- package/package.json +1 -1
- package/dist/components/p-a9540d93.js +0 -357
- package/dist/components/p-d4e2ac64.js +0 -203
- package/dist/realtimekit-ui/p-0689d68b.entry.js +0 -1
- package/dist/realtimekit-ui/p-1bf58a84.entry.js +0 -1
- package/dist/realtimekit-ui/p-2f641bfa.entry.js +0 -1
- package/dist/realtimekit-ui/p-33228f0a.entry.js +0 -1
- package/dist/realtimekit-ui/p-3e02ec0b.entry.js +0 -1
- package/dist/realtimekit-ui/p-481549ac.entry.js +0 -1
- package/dist/realtimekit-ui/p-50157a65.entry.js +0 -1
- package/dist/realtimekit-ui/p-50e861f9.entry.js +0 -1
- package/dist/realtimekit-ui/p-57277553.entry.js +0 -1
- package/dist/realtimekit-ui/p-5dc40f1a.entry.js +0 -1
- package/dist/realtimekit-ui/p-77e04fb7.entry.js +0 -1
- package/dist/realtimekit-ui/p-7a8ca3f2.entry.js +0 -1
- package/dist/realtimekit-ui/p-930f0255.entry.js +0 -1
- package/dist/realtimekit-ui/p-941f159e.entry.js +0 -1
- package/dist/realtimekit-ui/p-a4e223e8.entry.js +0 -1
- package/dist/realtimekit-ui/p-b564d931.entry.js +0 -1
- package/dist/realtimekit-ui/p-e720b51e.js +0 -1
- package/dist/realtimekit-ui/p-e87928f7.js +0 -1
- package/dist/realtimekit-ui/p-f40a55e3.entry.js +0 -1
- package/dist/realtimekit-ui/p-f645b8bb.entry.js +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{h as r,e as h,O as o,T as a,U as l}from"./p-e87928f7.js";import{S as u}from"./p-80c856cd.js";var c=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;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"]}}};c([u()],d.prototype,"meeting",void 0),c([u()],d.prototype,"t",void 0),c([u()],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}}";const f=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},v=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=g},g=Number.MAX_SAFE_INTEGER||9007199254740991;let p=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}({}),m=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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),y=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var b="manifest",w="level",$="audioTrack",k="subtitleTrack",S="main",T="audio",E="subtitle";class A{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 L{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 A(t),this.fast_=new A(i),this.defaultTTFB_=e,this.ttfb_=new A(t)}update(t,i){const{slow_:s,fast_:e,ttfb_:n}=this;s.halfLife!==t&&(this.slow_=new A(t,s.getEstimate(),s.getTotalWeight())),e.halfLife!==i&&(this.fast_=new A(i,e.getEstimate(),e.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new A(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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function M(t,i,s){return(i=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);if("object"!=typeof e)return e;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof i?i:i+""}(i))in t?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,t}function x(){return x=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var s=arguments[i];for(var e in s)({}).hasOwnProperty.call(s,e)&&(t[e]=s[e])}return t},x.apply(null,arguments)}function I(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 D(t){for(var i=1;i<arguments.length;i++){var s=null!=arguments[i]?arguments[i]:{};i%2?I(Object(s),!0).forEach((function(i){M(t,i,s[i])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):I(Object(s)).forEach((function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(s,i))}))}return t}class P{constructor(t,i){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${t}]:`;this.trace=C,this.debug=i.debug.bind(null,s),this.log=i.log.bind(null,s),this.warn=i.warn.bind(null,s),this.info=i.info.bind(null,s),this.error=i.error.bind(null,s)}}const C=function(){},R={trace:C,debug:C,log:C,warn:C,info:C,error:C};function O(){return x({},R)}function N(t,i,s){return i[t]?i[t].bind(i):function(t,i){const s=self.console[t];return s?s.bind(self.console,`${i?"["+i+"] ":""}[${t}] >`):C}(t,s)}const U=O(),F=U;function B(t=!0){if("undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _(t,i){const s=Object.keys(t),e=Object.keys(i),n=s.length,r=e.length;return!n||!r||n===r&&!s.some((t=>-1===e.indexOf(t)))}function j(t,i=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(t);if(i){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"")}const s=t.length;let e,n,r,h="",o=0;for(;o<s;){if(e=t[o++],0===e&&i)return h;if(0!==e&&3!==e)switch(e>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(e);break;case 12:case 13:n=t[o++],h+=String.fromCharCode((31&e)<<6|63&n);break;case 14:n=t[o++],r=t[o++],h+=String.fromCharCode((15&e)<<12|(63&n)<<6|63&r)}}return h}const G=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};function H(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var K,V,X,W,z,q,Y={exports:{}},Q=K?Y.exports:(K=1,V=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,X=/^(?=([^\/?#]*))\1([^]*)$/,W=/(?:\/|^)\.(?=\/)/g,z=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,Y.exports=q={buildAbsoluteURL:function(t,i,s){if(s=s||{},t=t.trim(),!(i=i.trim())){if(!s.alwaysNormalize)return t;var e=q.parseURL(t);if(!e)throw new Error("Error trying to parse base URL.");return e.path=q.normalizePath(e.path),q.buildURLFromParts(e)}var n=q.parseURL(i);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=q.normalizePath(n.path),q.buildURLFromParts(n)):i;var r=q.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");if(!r.netLoc&&r.path&&"/"!==r.path[0]){var h=X.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=q.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?q.normalizePath(n.path):n.path),q.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(W,"");t.length!==(t=t.replace(z,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}});class J{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 Z="audio",tt="video",it="audiovideo";class st{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,i){const s=ht(t,i);s&&(s.enumerable=!0,Object.defineProperty(t,i,s))}(this,"stats")}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 baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Z]:null,[tt]:null,[it]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new J),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Q.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Z]=null,t[tt]=null,t[it]=null}}function et(t){return"initSegment"!==t.sn}class nt extends st{constructor(t,i){super(i),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=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.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,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 byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange){const t=this.byteRange[0],i=this.byteRange[1];if(f(t)&&f(i))return i-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=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;const t=f(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&this.levelkeys[t[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){this._programDateTime=f(t)?t:this.rawProgramDateTime=null}get ref(){return et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}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}}}class rt extends st{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.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)}}function ht(t,i){const s=Object.getPrototypeOf(t);if(s){return Object.getOwnPropertyDescriptor(s,i)||ht(s,i)}}const ot=Math.pow(2,32)-1,at=[].push,lt={video:1,audio:2,id3:3,text:4};function ut(t){return String.fromCharCode.apply(null,t)}function ct(t,i){const s=t[i]<<8|t[i+1];return s<0?65536+s:s}function dt(t,i){const s=vt(t,i);return s<0?4294967296+s:s}function ft(t,i){let s=dt(t,i);return s*=Math.pow(2,32),s+=dt(t,i+4),s}function vt(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function gt(t,i){const s=[];if(!i.length)return s;const e=t.byteLength;for(let n=0;n<e;){const r=dt(t,n),h=r>1?n+r:e;if(ut(t.subarray(n+4,n+8))===i[0])if(1===i.length)s.push(t.subarray(n+8,h));else{const e=gt(t.subarray(n+8,h),i.slice(1));e.length&&at.apply(s,e)}n=h}return s}function pt(t){const i=[],s=t[0];let e=8;const n=dt(t,e);e+=4;let r=0,h=0;0===s?(r=dt(t,e),h=dt(t,e+4),e+=8):(r=ft(t,e),h=ft(t,e+8),e+=16),e+=2;let o=t.length+h;const a=ct(t,e);e+=2;for(let s=0;s<a;s++){let s=e;const r=dt(t,s);s+=4;const h=2147483647&r;if(1==(2147483648&r)>>>31)return F.warn("SIDX has hierarchical references (not supported)"),null;const a=dt(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 mt(t){const i=[],s=gt(t,["moov","trak"]);for(let t=0;t<s.length;t++){const e=s[t],n=gt(e,["tkhd"])[0];if(n){let t=n[0];const s=dt(n,0===t?12:20),r=gt(e,["mdia","mdhd"])[0];if(r){t=r[0];const n=dt(r,0===t?12:20),h=gt(e,["mdia","hdlr"])[0];if(h){const t=ut(h.subarray(8,12)),r={soun:Z,vide:tt}[t],o=yt(gt(e,["mdia","minf","stbl","stsd"])[0]);r?(i[s]={timescale:n,type:r,stsd:o},i[r]=D({timescale:n,id:s},o)):i[s]={timescale:n,type:t,stsd:o}}}}}return gt(t,["moov","mvex","trex"]).forEach((t=>{const s=dt(t,4),e=i[s];e&&(e.default={duration:dt(t,12),flags:dt(t,20)})})),i}function yt(t){const i=t.subarray(8),s=i.subarray(86),e=ut(i.subarray(4,8));let n,r=e;const h="enca"===e||"encv"===e;if(h){const t=gt(i,[e])[0];gt(t.subarray("enca"===e?28:78),["sinf"]).forEach((t=>{const i=gt(t,["schm"])[0];if(i){const s=ut(i.subarray(4,8));if("cbcs"===s||"cenc"===s){const i=gt(t,["frma"])[0];i&&(r=ut(i))}}}))}const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=gt(s,["avcC"])[0];t&&t.length>3&&(r+="."+$t(t[1])+$t(t[2])+$t(t[3]),n=bt("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const t=gt(i,[e])[0],s=gt(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=wt(s,t),t+=2;const i=s[t++];if(128&i&&(t+=2),64&i&&(t+=s[t++]),4!==s[t++])break;t=wt(s,t);const e=s[t++];if(64!==e)break;if(r+="."+$t(e),t+=12,5!==s[t++])break;t=wt(s,t);const n=s[t++];let h=(248&n)>>3;31===h&&(h+=1+((7&n)<<3)+((224&s[t])>>5)),r+="."+h}break}case"hvc1":case"hev1":{const t=gt(s,["hvcC"])[0];if(t&&t.length>12){const i=t[1],s=["","A","B","C"][i>>6],e=31&i,n=dt(t,2),h=(32&i)>>5?"H":"L",o=t[12],a=t.subarray(6,12);r+="."+s+e,r+="."+function(t){let i=0;for(let s=0;s<32;s++)i|=(t>>s&1)<<31-s;return i>>>0}(n).toString(16).toUpperCase(),r+="."+h+o;let l="";for(let t=a.length;t--;){const i=a[t];(i||l)&&(l="."+i.toString(16).toUpperCase()+l)}r+=l}n=bt("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=bt(r,s)||r;break;case"vp09":{const t=gt(s,["vpcC"])[0];if(t&&t.length>6){const i=t[5],s=t[6]>>4&15;r+="."+kt(t[4])+"."+kt(i)+"."+kt(s)}break}case"av01":{const t=gt(s,["av1C"])[0];if(t&&t.length>2){const i=t[1]>>>5,e=t[2]>>>7?"H":"M",h=(64&t[2])>>6,o=2===i&&h?(32&t[2])>>5?12:10:h?10:8,a=(16&t[2])>>4,l=(8&t[2])>>3,u=(4&t[2])>>2,c=3&t[2],d=1,f=1,v=1,g=0;r+="."+i+"."+kt(31&t[1])+e+"."+kt(o)+"."+a+"."+l+u+c+"."+kt(d)+"."+kt(f)+"."+kt(v)+"."+g,n=bt("dav1",s)}break}}return{codec:r,encrypted:h,supplemental:n}}function bt(t,i){const s=gt(i,["dvvC"]),e=s.length?s[0]:gt(i,["dvcC"])[0];if(e){const i=e[2]<<5&32|e[3]>>3&31;return t+"."+kt(e[2]>>1&127)+"."+kt(i)}}function wt(t,i){const s=i+5;for(;128&t[i++]&&i<s;);return i}function $t(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function kt(t){return(t<10?"0":"")+t}function St(t){const i=gt(t,["schm"])[0];if(i){const s=ut(i.subarray(4,8));if("cbcs"===s||"cenc"===s)return gt(t,["schi","tenc"])[0]}return null}function Tt(t,i){const s=new Uint8Array(t.length+i.length);return s.set(t),s.set(i,t.length),s}function Et(t,i){const s=[],e=i.samples,n=i.timescale,r=i.id;let h=!1;return gt(e,["moof"]).map((o=>{const a=o.byteOffset-8;gt(o,["traf"]).map((o=>{const l=gt(o,["tfdt"]).map((t=>{const i=t[0];let s=dt(t,4);return 1===i&&(s*=Math.pow(2,32),s+=dt(t,8)),s/n}))[0];return void 0!==l&&(t=l),gt(o,["tfhd"]).map((l=>{const u=dt(l,4),c=16777215&dt(l,0);let d=0;const f=!!(16&c);let v=0;const g=!!(32&c);let p=8;u===r&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(d=dt(l,p),p+=4),f&&(v=dt(l,p),p+=4),g&&(p+=4),"video"===i.type&&(h=At(i.codec)),gt(o,["trun"]).map((r=>{const o=r[0],l=16777215&dt(r,0),u=!!(1&l);let c=0;const f=!!(4&l),g=!!(256&l);let p=0;const m=!!(512&l);let y=0;const b=!!(1024&l),w=!!(2048&l);let $=0;const k=dt(r,4);let S=8;u&&(c=dt(r,S),S+=4),f&&(S+=4);let T=c+a;for(let a=0;a<k;a++){if(g?(p=dt(r,S),S+=4):p=d,m?(y=dt(r,S),S+=4):y=v,b&&(S+=4),w&&($=0===o?dt(r,S):vt(r,S),S+=4),i.type===tt){let i=0;for(;i<y;){const r=dt(e,T);T+=4,Lt(h,e[T])&&Mt(e.subarray(T,T+r),h?2:1,t+$/n,s),T+=r,i+=r+4}}t+=p/n}})))}))}))})),s}function At(t){if(!t)return!1;const i=t.substring(0,4);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}function Lt(t,i){if(t){const t=i>>1&63;return 39===t||40===t}return 6==(31&i)}function Mt(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){F.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===h){if(181===n[i++]){const t=ct(n,i);if(i+=2,49===t){const t=dt(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:j(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 It(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=G(new Uint8Array(r,s+12,16));let o=null,a=null,l=0;if(0===n)l=28;else if(1===n){const n=t.getUint32(28);if(!n||e<32+16*n)return{offset:s,size:i};o=[];for(let t=0;t<n;t++)o.push(new Uint8Array(r,s+32+16*t,16));l=32+16*n}if(!l)return{offset:s,size:i};const u=t.getUint32(l);return i-32<u?{offset:s,size:i}:(a=new Uint8Array(r,s+l+4,u),{version:n,systemId:h,kids:o,data:a,offset:s,size:i})}const Dt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Pt={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,dav1:.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 Ct(t,i){const s=Pt[i];return!!s&&!!s[t.slice(0,4)]}function Rt(t,i,s=!0){return!t.split(",").some((t=>!Ot(t,i,s)))}function Ot(t,i,s=!0){var e;const n=B(s);return null!=(e=null==n?void 0:n.isTypeSupported(Nt(t,i)))&&e}function Nt(t,i){return`${i}/mp4;codecs=${t}`}function Ut(t){if(t){const i=t.substring(0,4);return Pt.video[i]}return 2}function Ft(t){const i=Dt();return t.split(",").reduce(((t,s)=>{const e=i&&At(s)?9:Pt.video[s];return e?(2*e+t)/(t?3:2):(Pt.audio[s]+t)/(t?2:1)}),0)}const Bt={},_t=/flac|opus|mp4a\.40\.34/i;function jt(t,i=!0){return t.replace(_t,(t=>function(t,i=!0){if(Bt[t])return Bt[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let n=0;n<s.length;n++){var e;if(Ot(s[n],"audio",i))return Bt[t]=s[n],s[n];if("mp3"===s[n]&&null!=(e=B(i))&&e.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),i)))}function Gt(t,i){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Ht(t,"audio")||Ht(t,"video")))return t;if(i){const s=i.split(",");if(s.length>1){if(t)for(let i=s.length;i--;)if(s[i].substring(0,4)===t.substring(0,4))return s[i];return s[0]}}return i||t}function Ht(t,i){return Ct(t,i)&&Ot(t,i)}function Kt(t){if(t.startsWith("av01.")){const i=t.split("."),s=["0","111","01","01","01","0"];for(let t=i.length;t>4&&t<10;t++)i[t]=s[t-4];return i.join(".")}return t}function Vt(t){const i=B(t)||{isTypeSupported:()=>!1};return{mpeg:i.isTypeSupported("audio/mpeg"),mp3:i.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:i.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Xt(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Wt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function zt(t,i){return{supported:!1,configurations:i,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:t}}function qt(t,i,s,e,n,r){const h=t.videoCodec,o=t.audioCodec?t.audioGroups:null,a=null==r?void 0:r.audioCodec,l=null==r?void 0:r.channels,u=l?parseInt(l):a?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?i.groups[o[0]].channels:o.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!==h&&(h.split(",").some((t=>At(t)))||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&&f(u)&&Object.keys(c).some((t=>parseInt(t)>u))}function Yt(t,i,s,e={}){const n=t.videoCodec;if(!n&&!t.audioCodec||!s)return Promise.resolve(Wt);const r=[],h=function(t){var i;const s=null==(i=t.videoCodec)?void 0:i.split(","),e=Jt(t),n=t.width||640,r=t.height||480,h=t.frameRate||30,o=t.videoRange.toLowerCase();return s?s.map((t=>{const i={contentType:Nt(Kt(t),"video"),width:n,height:r,bitrate:e,framerate:h};return"sdr"!==o&&(i.transferFunction=o),i})):[]}(t),o=h.length,a=function(t,i,s){var e;const n=null==(e=t.audioCodec)?void 0:e.split(","),r=Jt(t);return n&&t.audioGroups?t.audioGroups.reduce(((t,e)=>{var h;const o=e?null==(h=i.groups[e])?void 0:h.tracks:null;return o?o.reduce(((t,i)=>{if(i.groupId===e){const e=parseFloat(i.channels||"");n.forEach((i=>{const n={contentType:Nt(i,"audio"),bitrate:s?Qt(i,r):r};e&&(n.channels=""+e),t.push(n)}))}return t}),t):t}),[]):[]}(t,i,o>0),l=a.length;for(let t=o||1*l||1;t--;){const i={type:"media-source"};if(o&&(i.video=h[t%o]),l){i.audio=a[t%l];const s=i.audio.bitrate;i.video&&s&&(i.video.bitrate-=s)}r.push(i)}if(n){const t=navigator.userAgent;if(n.split(",").some((t=>At(t)))&&Dt())return Promise.resolve(zt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),r))}return Promise.all(r.map((t=>{const i=function(t){let i="";const{audio:s,video:e}=t;return e&&(i+=`${Xt(e.contentType)}_r${e.height}x${e.width}f${Math.ceil(e.framerate)}${e.transferFunction||"sd"}_${Math.ceil(e.bitrate/1e5)}`),s&&(i+=`${e?"_":""}${Xt(s.contentType)}_c${s.channels}`),i}(t);return e[i]||(e[i]=s.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:r,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:r,decodingInfoResults:[],error:t})))}function Qt(t,i){if(i<=1)return 1;let s=128e3;return"ec-3"===t?s=768e3:"ac-3"===t&&(s=64e4),Math.min(i/2,s)}function Jt(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const Zt=["NONE","TYPE-0","TYPE-1",null],ti=["SDR","PQ","HLG"];function ii(t){const{canSkipUntil:i,canSkipDateRanges:s,age:e}=t;return i&&e<i/2?s?"v2":"YES":""}class si{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 ei{constructor(t){if(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.supplemental=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(","),"supplemental"in t){var i;this.supplemental=t.supplemental;const s=null==(i=t.supplemental)?void 0:i.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}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 ni(this._audioGroups,t)}hasSubtitleGroup(t){return ni(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 ni(t,i){return!(!i||!t)&&-1!==t.indexOf(i)}const ri=(t,i)=>JSON.stringify(t,(t=>{const i=new WeakSet;return(s,e)=>{if(t&&(e=t(s,e)),"object"==typeof e&&null!==e){if(i.has(e))return;i.add(e)}return e}})(i));function hi(t,i){F.log(`[abr] start candidates with "${t}" ignored because ${i}`)}function oi(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:{}})}function ai(t){if(!t)return t;const{lang:i,assocLang:s,characteristics:e,channels:n,audioCodec:r}=t;return{lang:i,assocLang:s,characteristics:e,channels:n,audioCodec:r}}function li(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(ui(t,i[e],s))return e;return-1}function ui(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||function(t,i="--"){return t.length===i.length?t===i:t.startsWith(i)||i.startsWith(t)}(r,i.lang))&&(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 ci(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 di(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}function fi(t,i){var s;return!!t&&t!==(null==(s=i.loadLevelObj)?void 0:s.uri)}const vi=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 gi(t,i,s=0,e=0,n=.005){let r=null;if(t){r=i[1+t.sn-i[0].sn]||null;const e=t.endDTS-s;e>0&&e<15e-7&&(s+=15e-7),r&&t.level!==r.level&&r.end<=t.end&&(r=i[2+t.sn-i[0].sn]||null)}else 0===s&&0===i[0].start&&(r=i[0]);if(r&&((!t||t.level===r.level)&&0===pi(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=vi(i,pi.bind(null,s,e));return!h||h===t&&r?r:h}function pi(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 mi(t,i,s){const e=1e3*Math.min(i,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-e>t}function yi(t,i,s){if(t&&t.startCC<=i&&t.endCC>=i){let e=t.fragments;const{fragmentHint:n}=t;let r;return n&&(e=e.concat(n)),vi(e,(t=>t.cc<i?1:t.cc>i?-1:(r=t,t.end<=s?1:t.start>s?-1:0))),r||null}return null}function bi(t){switch(t.details){case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_TIMEOUT:case m.LEVEL_LOAD_TIMEOUT:case m.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function wi(t,i){const s=bi(i);return t.default[(s?"timeout":"error")+"Retry"]}function $i(t,i){const s="linear"===t.backoff?1:Math.pow(2,i);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function ki(t){return D(D({},t),{errorRetry:null,timeoutRetry:null})}function Si(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}function Ti(t){const i={action:0,flags:0};return t&&(i.resolved=!0),i}var Ei="NOT_LOADED",Ai="APPENDING",Li="PARTIAL",Mi="OK";class xi{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.BUFFER_APPENDED,this.onBufferAppended,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.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){return this.getFragAtPos(t,i,!0)}getFragAtPos(t,i,s){const{fragments:e}=this,n=Object.keys(e);for(let r=n.length;r--;){const h=e[n[r]];if((null==h?void 0:h.body.type)===i&&(!s||h.buffered)){const i=h.body;if(i.start<=t&&t<=i.end)return i}}return null}detectEvictedFragments(t,i,s,e,n){this.timeRanges&&(this.timeRanges[t]=i);const r=(null==e?void 0:e.fragment.sn)||-1;Object.keys(this.fragments).forEach((e=>{const h=this.fragments[e];if(!h)return;if(r>=h.body.sn)return;if(!h.buffered&&(!h.loaded||n))return void(h.body.type===s&&this.removeFragment(h.body));const o=h.range[t];o&&(0!==o.time.length?o.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,i);return s&&this.removeFragment(h.body),s})):this.removeFragment(h.body))}))}detectPartialFragments(t){const i=this.timeRanges;if(!i||"initSegment"===t.frag.sn)return;const s=t.frag,e=Di(s),n=this.fragments[e];if(!n||n.buffered&&s.gap)return;const r=!s.relurl;Object.keys(i).forEach((e=>{const h=s.elementaryStreams[e];h&&(n.range[e]=this.getBufferedTimes(s,t.part,r||!0===h.partial,i[e]))})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ii(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}removeParts(t,i){const s=this.activePartLists[i];s&&(this.activePartLists[i]=Pi(s,(i=>i.fragment.sn>=t)))}fragBuffered(t,i){const s=Di(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&&Ii(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||Ii(i))}getState(t){const i=Di(t),s=this.fragments[i];return s?s.buffered?Ii(s)?Li:Mi:Ai:Ei}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}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,i){if("initSegment"===i.frag.sn||i.frag.bitrateTest)return;const s=i.frag,e=i.part?null:i,n=Di(s);this.fragments[n]={body:s,appendedPTS:null,loaded:e,buffered:!1,range:Object.create(null)}}onBufferAppended(t,i){const{frag:s,part:e,timeRanges:n,type:r}=i;if("initSegment"===s.sn)return;const h=s.type;if(e){let t=this.activePartLists[h];t||(this.activePartLists[h]=t=[]),t.push(e)}this.timeRanges=n,this.detectEvictedFragments(r,n[r],h,e)}onFragBuffered(t,i){this.detectPartialFragments(i)}hasFragment(t){const i=Di(t);return!!this.fragments[i]}hasFragments(t){const{fragments:i}=this,s=Object.keys(i);if(!t)return s.length>0;for(let e=s.length;e--;){const n=i[s[e]];if((null==n?void 0:n.body.type)===t)return!0}return!1}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=Di(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const i=t.sn;this.activePartLists[t.type]=Pi(s,(t=>t.fragment.sn!==i))}delete this.fragments[i],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t,i;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const s=null==(t=this.hls)||null==(i=t.latestLevelDetails)?void 0:i.partList;s&&s.forEach((t=>t.clearElementaryStreamInfo()))}}function Ii(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 Di(t){return`${t.type}_${t.level}_${t.sn}`}function Pi(t,i){return t.filter((t=>{const s=i(t);return s||t.clearElementaryStreamInfo(),s}))}class Ci{constructor(t,i,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=i,this.aesMode=s}decrypt(t,i){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},i,t);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},i,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Ri{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],u=o[2],c=o[3],d=new Uint32Array(256);let f=0,v=0,g=0;for(g=0;g<256;g++)d[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){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],g=d[o],p=d[g];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*p^65537*g^257*o^16843008*f,a[s]=m<<24|m>>>8,l[s]=m<<16|m>>>16,u[s]=m<<8|m>>>24,c[s]=m,f?(f=o^d[d[d[p^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),u=this.sBox,c=this.rcon,d=this.invSubMix,f=d[0],v=d[1],g=d[2],p=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=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[255&y],y^=c[h/n|0]<<24):n>6&&h%n==4&&(y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[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[u[y>>>24]]^v[u[y>>>16&255]]^g[u[y>>>8&255]]^p[u[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],u=h[3],c=this.uint8ArrayToUint32Array_(s);let d=c[0],f=c[1],v=c[2],g=c[3];const p=new Int32Array(t),m=new Int32Array(p.length);let y,b,w,$,k,S,T,E,A,L,M,x,I,D;const P=this.networkToHostOrderSwap;for(;i<p.length;){for(A=P(p[i]),L=P(p[i+1]),M=P(p[i+2]),x=P(p[i+3]),k=A^n[0],S=x^n[1],T=M^n[2],E=L^n[3],I=4,D=1;D<e;D++)y=o[k>>>24]^a[S>>16&255]^l[T>>8&255]^u[255&E]^n[I],b=o[S>>>24]^a[T>>16&255]^l[E>>8&255]^u[255&k]^n[I+1],w=o[T>>>24]^a[E>>16&255]^l[k>>8&255]^u[255&S]^n[I+2],$=o[E>>>24]^a[k>>16&255]^l[S>>8&255]^u[255&T]^n[I+3],k=y,S=b,T=w,E=$,I+=4;y=r[k>>>24]<<24^r[S>>16&255]<<16^r[T>>8&255]<<8^r[255&E]^n[I],b=r[S>>>24]<<24^r[T>>16&255]<<16^r[E>>8&255]<<8^r[255&k]^n[I+1],w=r[T>>>24]<<24^r[E>>16&255]<<16^r[k>>8&255]<<8^r[255&S]^n[I+2],$=r[E>>>24]<<24^r[k>>16&255]<<16^r[S>>8&255]<<8^r[255&T]^n[I+3],m[i]=P(y^d),m[i+1]=P($^f),m[i+2]=P(w^v),m[i+3]=P(b^g),d=A,f=L,v=M,g=x,i+=4}return m.buffer}}class Oi{constructor(t,i,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=i,this.aesMode=s}expandKey(){const t=function(t){switch(t){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Ni{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.enableSoftwareAES=void 0,this.enableSoftwareAES=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?t.slice(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,e){return this.useSoftware?new Promise(((n,r)=>{const h=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(h,i,s,e);const o=this.flush();o?n(o.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),i,s,e)}softwareDecrypt(t,i,s,e){const{currentIV:n,currentResult:r,remainderData:h}=this;if(0!==e||16!==i.byteLength)return F.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),h&&(t=Tt(h,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;n&&(s=n);let a=this.softwareDecrypter;a||(a=this.softwareDecrypter=new Ri),a.expandKey(i);const l=r;return this.currentResult=a.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,l||null}webCryptoDecrypt(t,i,s,e){if(this.key!==i||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,i,s,e));this.key=i,this.fastAesKey=new Oi(this.subtle,i,e)}return this.fastAesKey.expandKey().then((i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ci(this.subtle,new Uint8Array(s),e).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized")))).catch((n=>(F.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(t,i,s,e))))}onWebCryptoError(t,i,s,e){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,i,s,e);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let i=t;const s=t.length-t.length%16;return s!==t.length&&(i=t.slice(0,s),this.remainderData=t.slice(s)),i}logOnce(t){this.logEnabled&&(F.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ui=Math.pow(2,17);class Fi{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 ji({type:p.NETWORK_ERROR,details:m.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(_i(t));t.gap=!1}const a=this.loader=n?new n(e):new r(e),l=Bi(t);t.loader=a;const u=ki(e.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ui};t.stats=a.stats;const d={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 ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:D({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 ji({type:p.NETWORK_ERROR,details:m.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:e,stats:i}))},onTimeout:(i,s,e)=>{this.resetLoader(t,a),o(new ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:e,stats:i}))}};i&&(d.onProgress=(s,e,n,r)=>i({frag:t,part:null,payload:n,networkDetails:r})),a.load(l,c,d)}))}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(_i(t,i));const a=this.loader=n?new n(e):new r(e),l=Bi(t,i);t.loader=a;const u=ki(e.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ui};i.stats=a.stats,a.load(l,c,{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 ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:i,response:D({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 ji({type:p.NETWORK_ERROR,details:m.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 ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:i,error:new Error(`Timeout after ${c.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 Bi(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(f(n)&&f(r)){var h;let i=n,s=r;if("initSegment"===t.sn&&("AES-128"===(o=null==(h=t.decryptdata)?void 0:h.method)||"AES-256"===o)){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}var o;return e}function _i(t,i){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),e={type:p.MEDIA_ERROR,details:m.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return i&&(e.part=i),(i||t).stats.aborted=!0,new ji(e)}class ji extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Gi extends P{constructor(t,i){super(t,i),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(){}}class Hi{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}}const Ki={length:0,start:()=>0,end:()=>0};class Vi{static isBuffered(t,i){if(t){const s=Vi.getBuffered(t);for(let t=s.length;t--;)if(i>=s.start(t)&&i<=s.end(t))return!0}return!1}static bufferedRanges(t){if(t){const i=Vi.getBuffered(t);return Vi.timeRangesToArray(i)}return[]}static timeRangesToArray(t){const i=[];for(let s=0;s<t.length;s++)i.push({start:t.start(s),end:t.end(s)});return i}static bufferInfo(t,i,s){if(t){const e=Vi.bufferedRanges(t);if(e.length)return Vi.bufferedInfo(e,i,s)}return{len:0,start:i,end:i,bufferedIndex:-1}}static bufferedInfo(t,i,s){i=Math.max(0,i),t.length>1&&t.sort(((t,i)=>t.start-i.start||i.end-t.end));let e=-1,n=[];if(s)for(let r=0;r<t.length;r++){i>=t[r].start&&i<=t[r].end&&(e=r);const h=n.length;if(h){const i=n[h-1].end;t[r].start-i<s?t[r].end>i&&(n[h-1].end=t[r].end):n.push(t[r])}else n.push(t[r])}else n=t;let r,h=0,o=i,a=i;for(let t=0;t<n.length;t++){const l=n[t].start,u=n[t].end;if(-1===e&&i>=l&&i<=u&&(e=t),i+s>=l&&i<u)o=l,a=u,h=a-i;else if(i+s<l){r=l;break}}return{len:h,start:o||0,end:a||0,nextStart:r,buffered:t,bufferedIndex:e}}static getBuffered(t){try{return t.buffered||Ki}catch(t){return F.log("failed to get media.buffered",t),Ki}}}const Xi=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wi(t){return Xi.test(t)}function zi(t,i){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return i.replace(Xi,(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 qi(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 Yi(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}"`))}const Qi=/^(\d+)x(\d+)$/,Ji=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Zi{constructor(t,i){"string"==typeof t&&(t=Zi.parseAttrList(t,i)),x(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]}enumeratedStringList(t,i){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce(((t,i)=>(t[i.toLowerCase()]=!0,t)),i)}bool(t){return"YES"===this[t]}decimalResolution(t){const i=Qi.exec(this[t]);if(null!==i)return{width:parseInt(i[1],10),height:parseInt(i[2],10)}}static parseAttrList(t,i){let s;const e={};for(Ji.lastIndex=0;null!==(s=Ji.exec(t));){const n=s[1].trim();let r=s[2];const h=0===r.indexOf('"')&&r.lastIndexOf('"')===r.length-1;let o=!1;if(h)r=r.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(i&&(h||o))r=zi(i,r);else if(!o&&!h)switch(n){case"CLOSED-CAPTIONS":if("NONE"===r)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":F.warn(`${t}: attribute ${n} is missing quotes`)}e[n]=r}return e}}function ts(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class is{constructor(t,i,s=0){var e;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(e=null==i?void 0:i.tagOrder)?e:s,i){const s=i.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==s[i]){F.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=x(new Zi({}),s,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==i?void 0:i.endDate)||new Date(this.attr["END-DATE"]);f(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(F.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const i=this.duration;return null!==i?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*i):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(f(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&f(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class ss{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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,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}get hasProgramDateTime(){return!!this.fragments.length&&f(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;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 fragmentStart(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[0].start: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 maxPartIndex(){const t=this.partList;if(t){const i=this.lastPartIndex;if(-1!==i){for(let s=t.length;s--;)if(t[s].index>i)return t[s].index;return i}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){return!!(this.live&&this.age&&this.misses<3)&&this.age>Math.max(this.partEnd-this.fragmentStart,this.totalduration)+this.levelTargetDuration}}function es(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function ns(t){switch(t){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw new Error(`invalid full segment method ${t}`)}}function rs(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function hs(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const os="undefined"!=typeof self?self:void 0;var as={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ls="org.w3.clearkey",us="com.apple.streamingkeydelivery",cs="com.microsoft.playready",ds="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function fs(t){switch(t){case us:return as.FAIRPLAY;case cs:return as.PLAYREADY;case ds:return as.WIDEVINE;case ls:return as.CLEARKEY}}function vs(t){return"edef8ba979d64acea3c827dcd51d21ed"===t?as.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===t?as.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===t||"e2719d58a985b3c9781ab030af78d30e"===t?as.CLEARKEY:void 0}function gs(t){switch(t){case as.FAIRPLAY:return us;case as.PLAYREADY:return cs;case as.WIDEVINE:return ds;case as.CLEARKEY:return ls}}function ps(t){const{drmSystems:i,widevineLicenseUrl:s}=t,e=i?[as.FAIRPLAY,as.WIDEVINE,as.PLAYREADY,as.CLEARKEY].filter((t=>!!i[t])):[];return!e[as.WIDEVINE]&&s&&e.push(as.WIDEVINE),e}const ms=null!=os&&null!=(ys=os.navigator)&&ys.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ys;function bs(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=rs(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}let ws={};class $s{static clearKeyUriToKeyIdMap(){ws={}}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&&!es(t)}isSupported(){if(this.method){if(es(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case us:case ds:case cs:case ls: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(es(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(F.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 $s(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=rs(i)):s=function(t){const i=hs(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 ds:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case cs:{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;e=0,n=new Uint8Array,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([0,0,0,0]),t,r,n,h,s||new Uint8Array)}(t,0,i),this.keyId=bs(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=ws[this.uri];if(!t){const i=Object.keys(ws).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16),new DataView(t.buffer,12,4).setUint32(0,i),ws[this.uri]=t}this.keyId=t}return this}}const ks=/#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,Ss=/#EXT-X-MEDIA:(.*)/g,Ts=/^#EXT(?:INF|-X-TARGETDURATION):/m,Es=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),As=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|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 Ls{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 Q.buildAbsoluteURL(i,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Ts.test(t)}static parseMasterPlaylist(t,i){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Wi(t)},e=[];let n;for(ks.lastIndex=0;null!=(n=ks.exec(t));)if(n[1]){var r;const t=new Zi(n[1],s),h=zi(s,n[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Ls.resolve(h,i)},a=t.decimalResolution("RESOLUTION");a&&(o.width=a.width,o.height=a.height),Ps(t.CODECS,o);const l=t["SUPPLEMENTAL-CODECS"];l&&(o.supplemental={},Ps(l,o.supplemental)),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 Zi(t,s),e=i["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=i);break}case"SESSION-KEY":{const e=Is(t,i,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):F.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${t}"`);break}case"DEFINE":qi(s,new Zi(t,s),i);break;case"CONTENT-STEERING":{const e=new Zi(t,s);s.contentSteering={uri:Ls.resolve(e["SERVER-URI"],i),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Ds(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(Ss.lastIndex=0;null!==(e=Ss.exec(t));){const t=new Zi(e[1],s),r=t.TYPE;if(r){const s=h[r],e=n[r]||[];n[r]=e;const a=t.LANGUAGE,l=t["ASSOC-LANGUAGE"],u=t.CHANNELS,c=t.CHARACTERISTICS,d=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||a||"",type:r,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:a,url:t.URI?Ls.resolve(t.URI,i):""};if(l&&(f.assocLang=l),u&&(f.channels=u),c&&(f.characteristics=c),d&&(f.instreamId=d),null!=s&&s.length){const t=Ls.findGroup(s,f.groupId)||s[0];Cs(f,t,"audioCodec"),Cs(f,t,"textCodec")}e.push(f)}}return n}static parseLevelPlaylist(t,i,s,e,n,r){var h;const o={url:i},a=new ss(i),l=a.fragments,u=[];let c,d,v,g,p=null,m=0,y=0,b=0,w=0,$=0,k=null,S=new nt(e,o),T=-1,E=!1,A=null;if(Es.lastIndex=0,a.m3u8=t,a.hasVariableRefs=Wi(t),"#EXTM3U"!==(null==(h=Es.exec(t))?void 0:h[0]))return a.playlistParsingError=new Error("Missing format identifier #EXTM3U"),a;for(;null!==(c=Es.exec(t));){E&&(E=!1,S=new nt(e,o),S.playlistOffset=b,S.start=b,S.sn=m,S.cc=w,$&&(S.bitrate=$),S.level=s,p&&(S.initSegment=p,p.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),A&&(S.setByteRange(A),A=null)));const t=c[1];if(t){S.duration=parseFloat(t);const i=(" "+c[2]).slice(1);S.title=i||null,S.tagList.push(i?["INF",t,i]:["INF",t])}else if(c[3]){if(f(S.duration)){S.playlistOffset=b,S.start=b,v&&Ns(S,v,a),S.sn=m,S.level=s,S.cc=w,l.push(S);const t=(" "+c[3]).slice(1);S.relurl=zi(a,t),Rs(S,k,u),k=S,b+=S.duration,m++,y=0,E=!0}}else{if(c=c[0].match(As),!c){F.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<c.length&&void 0===c[d];d++);const t=(" "+c[d]).slice(1),n=(" "+c[d+1]).slice(1),h=c[d+2]?(" "+c[d+2]).slice(1):null;switch(t){case"BYTERANGE":k?S.setByteRange(n,k):S.setByteRange(n);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=n,S.tagList.push(["PROGRAM-DATE-TIME",n]),-1===T&&(T=l.length);break;case"PLAYLIST-TYPE":a.type&&Us(a,t,c),a.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==a.startSN?Us(a,t,c):l.length>0&&Fs(a,t,c),m=a.startSN=parseInt(n);break;case"SKIP":{a.skippedSegments&&Us(a,t,c);const i=new Zi(n,a),s=i.decimalInteger("SKIPPED-SEGMENTS");if(f(s)){a.skippedSegments+=s;for(let t=s;t--;)l.push(null);m+=s}const e=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");e&&(a.recentlyRemovedDateranges=(a.recentlyRemovedDateranges||[]).concat(e.split("\t")));break}case"TARGETDURATION":0!==a.targetduration&&Us(a,t,c),a.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==a.version&&Us(a,t,c),a.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":a.live||Us(a,t,c),a.live=!1;break;case"#":(n||h)&&S.tagList.push(h?[n,h]:[n]);break;case"DISCONTINUITY":w++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([t]);break;case"BITRATE":S.tagList.push([t,n]),$=1e3*parseInt(n),f($)?S.bitrate=$:$=0;break;case"DATERANGE":{const t=new Zi(n,a),i=new is(t,a.dateRanges[t.ID],a.dateRangeTagCount);a.dateRangeTagCount++,i.isValid||a.skippedSegments?a.dateRanges[i.id]=i:F.warn(`Ignoring invalid DATERANGE tag: "${n}"`),S.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new Zi(n,a);"IMPORT"in t?Yi(a,t,r):qi(a,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==a.startCC?Us(a,t,c):l.length>0&&Fs(a,t,c),a.startCC=w=parseInt(n);break;case"KEY":{const t=Is(n,i,a);if(t.isSupported()){if("NONE"===t.method){v=void 0;break}v||(v={}),v[t.keyFormat]&&(v=x({},v)),v[t.keyFormat]=t}else F.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${n}"`);break}case"START":a.startTimeOffset=Ds(n);break;case"MAP":{const t=new Zi(n,a);if(S.duration){const i=new nt(e,o);Os(i,t,s,v),p=i,S.initSegment=p,p.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime)}else{const i=S.byteRangeEndOffset;if(i){const t=S.byteRangeStartOffset;A=`${i-t}@${t}`}else A=null;Os(S,t,s,v),p=S,E=!0}p.cc=w;break}case"SERVER-CONTROL":g&&Us(a,t,c),g=new Zi(n),a.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),a.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{a.partTarget&&Us(a,t,c);const i=new Zi(n);a.partTarget=i.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const i=y>0?t[t.length-1]:void 0,s=y++,e=new Zi(n,a),r=new rt(e,S,o,s,i);t.push(r),S.duration+=r.duration;break}case"PRELOAD-HINT":{const t=new Zi(n,a);a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new Zi(n,a);a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:F.warn(`line parsed but not handled: ${c}`)}}}k&&!k.relurl?(l.pop(),b-=k.duration,a.partList&&(a.fragmentHint=k)):a.partList&&(Rs(S,k,u),S.cc=w,a.fragmentHint=S,v&&Ns(S,v,a)),a.targetduration||(a.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const L=l.length,M=l[0],I=l[L-1];if(b+=a.skippedSegments*a.targetduration,b>0&&L&&I){a.averagetargetduration=b/L;const t=I.sn;a.endSN="initSegment"!==t?t:0,a.live||(I.endList=!0),M&&void 0===a.startCC&&(a.startCC=M.cc),T>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}}(l,T),M&&u.unshift(M))}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(b+=a.fragmentHint.duration),a.totalduration=b,u.length&&a.dateRangeTagCount&&M&&Ms(u,a),a.endCC=w,a}}function Ms(t,i){const s=t.length;if(!s)return;const e=t[s-1],n=i.live?1/0:i.totalduration,r=Object.keys(i.dateRanges);for(let h=r.length;h--;){const o=i.dateRanges[r[h]],a=o.startDate.getTime();o.tagAnchor=e.ref;for(let e=s;e--;){const s=xs(i,a,t,e,n);if(-1!==s){o.tagAnchor=i.fragments[s].ref;break}}}}function xs(t,i,s,e,n){const r=s[e];if(r){const o=r.programDateTime;var h;if(i>=o||0===e)if(i<=o+1e3*(((null==(h=s[e+1])?void 0:h.start)||n)-r.start)){const n=s[e].sn-t.startSN,r=t.fragments;if(r.length>s.length)for(let h=(s[e+1]||r[r.length-1]).sn-t.startSN;h>n;h--){const t=r[h].programDateTime;if(i>=t&&i<t+1e3*r[h].duration)return h}return n}}return-1}function Is(t,i,s){var e,n;const r=new Zi(t,s),h=null!=(e=r.METHOD)?e:"",o=r.URI,a=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,u=null!=(n=r.KEYFORMAT)?n:"identity";o&&r.IV&&!a&&F.error(`Invalid IV: ${r.IV}`);const c=o?Ls.resolve(o,i):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new $s(h,c,u,d,a)}function Ds(t){const i=new Zi(t).decimalFloatingPoint("TIME-OFFSET");return f(i)?i:null}function Ps(t,i){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const e=s.filter((i=>Ct(i,t)));e.length&&(i[`${t}Codec`]=e.map((t=>t.split("/")[0])).join(","),s=s.filter((t=>-1===e.indexOf(t))))})),i.unknownCodecs=s}function Cs(t,i,s){const e=i[s];e&&(t[s]=e)}function Rs(t,i,s){t.rawProgramDateTime?s.push(t):null!=i&&i.programDateTime&&(t.programDateTime=i.endProgramDateTime)}function Os(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 Ns(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)}function Us(t,i,s){t.playlistParsingError=new Error(`#EXT-X-${i} must not appear more than once (${s[0]})`)}function Fs(t,i,s){t.playlistParsingError=new Error(`#EXT-X-${i} must appear before the first Media Segment (${s[0]})`)}function Bs(t,i){const s=i.startPTS;if(f(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.setDuration(n)}else i.setStart(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 _s(t,i,s,e,n,r){e-s<=0&&(F.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(f(a)){const t=Math.abs(a-s);i.deltaPTS=f(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 u=s-i.start;0!==i.start&&i.setStart(s),i.setDuration(e-i.start),i.startPTS=s,i.maxStartPTS=h,i.startDTS=n,i.endPTS=e,i.minEndPTS=o,i.endDTS=r;const c=i.sn;if(!t||c<t.startSN||c>t.endSN)return 0;let d;const v=c-t.startSN,g=t.fragments;for(g[v]=i,d=v;d>0;d--)Bs(g[d],g[d-1]);for(d=v;d<g.length-1;d++)Bs(g[d],g[d+1]);return t.fragmentHint&&Bs(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function js(t,i,s,e,n){return new Error(`${t} ${n.url}\nPlaylist starting @${i.startSN}\n${i.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function Gs(t,i,s=!0){const e=i.startSN+i.skippedSegments-t.startSN,n=t.fragments,r=e>=0;let h=0;if(r&&e<n.length)h=n[e].start;else if(r&&i.startSN===t.endSN+1)h=t.fragmentEnd;else if(r&&s)h=t.fragmentStart+e*i.levelTargetDuration;else{if(i.skippedSegments||0!==i.fragmentStart)return;h=t.fragmentStart}Hs(i,h)}function Hs(t,i){if(i){const s=t.fragments;for(let e=t.skippedSegments;e<s.length;e++)s[e].addStart(i);t.fragmentHint&&t.fragmentHint.addStart(i)}}function Ks(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)}function Vs(t,i,s){if(!t)return null;let e=t.fragments[i-t.startSN];return e||(e=t.fragmentHint,e&&e.sn===i?e:i<t.startSN&&s&&s.sn===i?s:null)}function Xs(t,i,s){return t?Ws(t.partList,i,s):null}function Ws(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 zs(t){t.forEach(((t,i)=>{var s;null==(s=t.details)||s.fragments.forEach((t=>{t.level=i,t.initSegment&&(t.initSegment.level=i)}))}))}function qs(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 Ys(t,i){if(t){const s=t.start+i;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Qs(t,i){const s=i.fragments;for(let i=0,e=s.length;i<e;i++)Ys(s[i],t);i.fragmentHint&&Ys(i.fragmentHint,t),i.alignedSliding=!0}function Js(t,i){if(!function(t,i){return!!(t&&i.startCC<t.endCC&&i.endCC>t.startCC)}(i,t))return;const s=Math.min(i.endCC,t.endCC),e=qs(i.fragments,s),n=qs(t.fragments,s);e&&n&&(F.log(`Aligning playlist at start of dicontinuity sequence ${s}`),Qs(e.start-n.start,t))}function Zs(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=qs(e,h),r=qs(s,h)),n&&r||(n=e[Math.floor(e.length/2)],r=qs(s,n.cc)||s[Math.floor(s.length/2)]);const o=n.programDateTime,a=r.programDateTime;o&&a&&Qs((a-o)/1e3-(r.start-n.start),t)}const te={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ie extends Gi{constructor(t,i,s,e,n){super(e,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=te.STOPPED,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.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.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:i,media:s,mediaBuffer:e,state:n}=this,r=s?s.currentTime:0,h=Vi.bufferInfo(e||s,r,t.maxBufferHole),o=!h.len;if(this.log(`Media seeking to ${f(r)?r.toFixed(3):r}, state: ${n}, ${o?"out of":"in"} buffer`),this.state===te.ENDED)this.resetLoadingState();else if(i){const s=t.maxFragLookUpTolerance,e=i.start-s,n=i.start+i.duration+s;if(o||n<h.start||e>h.end){const t=r>n;(r<e||t)&&(t&&i.loader&&(this.log(`Cancelling fragment load for seek (sn: ${i.sn})`),i.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,this.playlistType,!0),r>this.lastCurrentTime&&(this.lastCurrentTime=r),!this.loadingParts)){const t=Math.max(h.end,r),i=this.shouldLoadParts(this.getLevelDetails(),t);i&&(this.log(`LL-Part loading ON after seeking to ${r.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=i)}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${r} for seek without enough to start`),this.nextLoadPosition=r,o&&(this.startPosition=r)),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new Fi(t.config),this.keyLoader=s,this.fragmentTracker=i,this.config=t.config,this.decrypter=new Ni(t.config)}registerListeners(){const{hls:t}=this;t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===te.STOPPED)return;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=te.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:i}=this;return-1===i&&t?t:i}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,i){if(i.live||!this.media)return!1;const s=this.config.timelineOffset||0;if((t.end||0)<=s)return!1;const e=t.buffered;this.config.maxBufferHole&&e&&e.length>1&&(t=Vi.bufferedInfo(e,t.start,0));const n=t.nextStart;if(n&&n>s&&n<i.edge)return!1;if(this.media.currentTime<t.start)return!1;const r=i.partList;if(null!=r&&r.length){const t=r[r.length-1];return Vi.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}get timelineOffset(){const t=this.config.timelineOffset;var i;return t?(null==(i=this.getLevelDetails())?void 0:i.appliedTimelineOffset)||t:0}onMediaAttached(t,i){const s=this.media=this.mediaBuffer=i.media;s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),s.addEventListener("seeking",this.onMediaSeeking),s.addEventListener("ended",this.onMediaEnded);const e=this.config;this.levels&&e.autoStartLoad&&this.state===te.STOPPED&&this.startLoad(e.startPosition)}onMediaDetaching(t,i){const s=!!i.transferMedia,e=this.media;if(null!==e){if(e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e.removeEventListener("seeking",this.onMediaSeeking),e.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,i){}onManifestLoaded(t,i){this.startTimeOffset=i.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=te.STOPPED,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.startFragRequested=!0,this._loadFragForPlayback(t,i,s)}_loadFragForPlayback(t,i,s){this._doFragLoad(t,i,s,(t=>{const i=t.frag;if(this.fragContextChanged(i))return this.warn(`${i.type} sn: ${i.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(i,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(i);i.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const i=this.state,s=t.frag;this.fragContextChanged(s)?(i===te.FRAG_LOADING||!this.fragCurrent&&i===te.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=te.IDLE):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(y.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((i=>{this.state!==te.STOPPED&&this.state!==te.ERROR&&(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)===Ai){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)===Li&&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)}waitForLive(t){const i=t.details;return(null==i?void 0:i.live)&&"EVENT"!==i.type&&(this.levelLastLoaded!==t||i.expired)}flushMainBuffer(t,i,s=null){t-i&&this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:t,endOffset:i,type:s})}_loadInitSegment(t,i){this._doFragLoad(t,i).then((t=>{const i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:i}=this,{frag:s,payload:e}=t,n=s.decryptdata;if(e&&e.byteLength>0&&null!=n&&n.key&&n.iv&&es(n.method)){const r=self.performance.now();return this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer,ns(n.method)).catch((t=>{throw i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),t})).then((e=>{const n=self.performance.now();return i.trigger(y.FRAG_DECRYPTED,{frag:s,payload:e,stats:{tstart:r,tdecrypt:n}}),t.payload=e,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((i=>{this.state!==te.STOPPED&&this.state!==te.ERROR&&(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!==te.STOPPED&&(this.state=te.IDLE),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){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${i?" part: "+i.index:""} of ${this.fragInfo(t,!1,i)} > buffer:${s?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}(Vi.getBuffered(s)):"(detached)"})`),et(t)){var e;if(t.type!==E){const i=t.elementaryStreams;if(!Object.keys(i).some((t=>!!i[t])))return void(this.state=te.IDLE)}const i=null==(e=this.levels)?void 0:e[t.level];null!=i&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=te.IDLE}_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 Hi(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;this.fragCurrent=t;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;!t.encrypted||null!=(n=t.decryptdata)&&n.key?t.encrypted||(h=this.keyLoader.loadClear(t,r.encryptedFragments),h&&this.log("[eme] blocking frag load until media-keys acquired")):(this.log(`Loading key for ${t.sn} of [${r.startSN}-${r.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=te.KEY_LOADING,this.fragCurrent=t,h=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(y.KEY_LOADED,t),this.state===te.KEY_LOADING&&(this.state=te.IDLE),t})),this.hls.trigger(y.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(h=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const o=this.fragPrevious;if(et(t)&&(!o||t.sn!==o.sn)){const s=this.shouldLoadParts(i.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts&&et(t)){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 t=this.fragCurrent=a.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${a.index} (${o}/${n.length-1}) of ${this.fragInfo(t,!1,a)}) cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=a.start+a.duration,this.state=te.FRAG_LOADING,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(y.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)}}if(et(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${r?"["+r.startSN+"-"+r.endSN+"]":""}, target: ${parseFloat(s.toFixed(3))}`),f(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=te.FRAG_LOADING;const a=this.config.progressive;let l;return l=a&&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,a?e:void 0),h]).then((([t])=>(!a&&t&&e&&e(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(y.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}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(y.FRAG_LOADED,e);const h=Xs(s.details,t.sn,i.index+1)||Ws(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===m.INTERNAL_ABORTED?this.handleFragLoadAborted(i.frag,i.part):this.hls.trigger(y.ERROR,i)}else this.hls.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const i=this.getCurrentContext(t);if(!i||this.state!==te.PARSING)return void(this.fragCurrent||this.state===te.STOPPED||this.state===te.ERROR||(this.state=te.IDLE));const{frag:s,part:e,level:n}=i,r=self.performance.now();s.stats.parsing.end=r,e&&(e.stats.parsing.end=r);const h=this.getLevelDetails(),o=h&&s.sn>h.endSN||this.shouldLoadParts(h,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,e,n,t.partial)}shouldLoadParts(t,i){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(null!=t&&t.partList){var s;const n=t.partList[0];var e;if(i>=n.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0))if((this.hls.hasEnoughToStart?(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}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 ${this.playlistLabel()} ${e}. The current chunk will not be buffered.`),null;const h=i[e],o=h.details,a=r>-1?Xs(o,n,r):null,l=a?a.fragment:Vs(o,n,s);return l?(s&&s!==l&&(l.stats=s.stats),{frag:l,part:a,level:h}):null}bufferFragmentData(t,i,s,e,n){var r;if(!t||this.state!==te.PARSING)return;const{data1:h,data2:o}=t;let a=h;if(h&&o&&(a=Tt(h,o)),null==(r=a)||!r.length)return;const l=this.initPTS[i.cc];if(this.hls.trigger(y.BUFFER_APPENDING,{type:t.type,frag:i,part:s,chunkMeta:e,offset:l?-l.baseTime/l.timescale:void 0,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(!Vi.isBuffered(i,i.currentTime))return void this.flushMainBuffer(0,t.start);const s=i.currentTime,e=Vi.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){var s;const e=this.getLoadPosition();if(!f(e))return null;const n=this.lastCurrentTime>e||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,e,i,n)}getFwdBufferInfoAtPos(t,i,s,e){const n=Vi.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||r.gap)){const s=Math.max(Math.min(n.nextStart,r.end)-i,e);return Vi.bufferInfo(t,i,s)}}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=S){var s;const e=null==(s=this.fragmentTracker)?void 0:s.getAppendedFrag(t,i);return e&&"fragment"in e?e.fragment:e}getNextFragment(t,i){const s=i.fragments,e=s.length;if(!e)return null;const{config:n}=this,r=s[0].start,h=n.lowLatencyMode&&!!i.partList;let o=null;if(i.live){const s=n.initialLiveManifestSize;if(e<s)return this.warn(`Not enough fragments to start playback (have: ${e}, need: ${s})`),null;if(!i.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<r){var a;h&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(i);const s=this.hls.startPosition,e=this.hls.liveSyncPosition,n=o?(-1!==s&&s>=r?s:e)||o.start:t;this.log(`Setting startPosition to ${n} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${e} frag.start: ${null==(a=o)?void 0:a.start}`),this.startPosition=this.nextLoadPosition=n}}else t<=r&&(o=s[0]);o||(o=this.getFragmentAtPosition(t,this.loadingParts?i.partEnd:i.fragmentEnd,i));let l=this.filterReplacedPrimary(o,i);return!l&&o&&(l=this.filterReplacedPrimary(s[o.sn-i.startSN+1]||null,i)),this.mapToInitFragWhenRequired(l)}isLoopLoading(t,i){const s=this.fragmentTracker.getState(t);return(s===Mi||s===Li&&!!t.gap)&&this.nextLoadPosition>i}getNextFragmentLoopLoading(t,i,s,e,n){let r=null;if(t.gap&&(r=this.getNextFragment(this.nextLoadPosition,i),r&&!r.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,e,0);if(null!==t&&s.len+t.len>=n){const t=r.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${e}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,r}get primaryPrefetch(){var t,i;if(se(this.hls.config)&&(null==(t=this.hls.interstitialsManager)||null==(i=t.playingItem)?void 0:i.event))return!0;return!1}filterReplacedPrimary(t,i){if(!t)return t;if(se(this.hls.config)&&t.type!==E){const s=this.hls.interstitialsManager,e=null==s?void 0:s.bufferingItem;if(e){const s=e.event;if(s){if(s.appendInPlace||Math.abs(t.start-e.start)>1||0===e.start)return null}else{if(t.end<=e.start&&!1===(null==i?void 0:i.live))return null;if(t.start>e.end&&e.nextEvent&&(e.nextEvent.appendInPlace||t.start-e.end>1))return null}}const n=null==s?void 0:s.playerQueue;if(n)for(let i=n.length;i--;){const s=n[i].interstitial;if(s.appendInPlace&&t.start>=s.startTime&&t.end<=s.resumeTime)return 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){const i=t.fragments,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||!f(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;for(let e=0;e<t.length;++e){const n=t[e];if(mi(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=yi(t,s.cc,s.end),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,u=!!(this.loadingParts&&null!=l&&l.length&&o);let c;var d;(u&&o&&!this.bitrateTest&&l[l.length-1].fragment.sn===o.sn&&(r=r.concat(o),h=o.sn),t<i)?c=gi(n,r,t,t<this.lastCurrentTime||t>i-a||null!=(d=this.media)&&d.paused||!this.startFragRequested?0:a):c=r[r.length-1];if(c){const t=c.sn-s.startSN,i=this.fragmentTracker.getState(c);if((i===Mi||i===Li&&c.gap)&&(n=c),n&&c.sn===n.sn&&(!u||l[0].fragment.sn>c.sn||!s.live&&!u)&&n&&c.level===n.level){const i=r[t+1];c=c.sn<h&&this.fragmentTracker.getState(i)!==Mi?i:null}}return c}alignPlaylists(t,i,s){const e=t.fragments.length;if(!e)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,r=!i,h=t.alignedSliding&&f(n);if(r||!h&&!n){!function(t,i){t&&(Js(i,t),!i.alignedSliding&&t&&Zs(i,t),i.alignedSliding||!t||i.skippedSegments||Gs(t,i,!1))}(s,t);const n=t.fragmentStart;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${e}`),n}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;s<i&&(s=-1);const e=this.timelineOffset;if(-1===s){const n=null!==this.startTimeOffset,r=n?this.startTimeOffset:t.startTimeOffset;null!==r&&f(r)?(s=i+r,r<0&&(s+=t.edge),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${r} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):t.live?(s=this.hls.liveSyncPosition||i,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+e}this.nextLoadPosition=s+e}getLoadPosition(){var t;const{media:i}=this;let s=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&i?s=i.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(t,i){this.transmuxer&&t.type===this.playlistType&&et(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${i?" part "+i.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===te.FRAG_LOADING_WAITING_RETRY)||(this.state=te.IDLE)}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===m.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const r=i.errorAction,{action:h,flags:o,retryCount:a=0,retryConfig:l}=r||{},u=!!r&&!!l,c=u&&5===h,d=u&&!r.resolved&&1===o;if(!c&&d&&et(s)&&!s.endList)this.resetFragmentErrors(t),this.treatAsGap(s),r.resolved=!0;else if((c||d)&&a<l.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const e=$i(l,a);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${i.details}, retrying loading ${a+1}/${l.maxNumRetry} in ${e}ms`),r.resolved=!0,this.retryDate=self.performance.now()+e,this.state=te.FRAG_LOADING_WAITING_RETRY}else if(l&&r){if(this.resetFragmentErrors(t),!(a<l.maxNumRetry))return void this.warn(`${i.details} reached or exceeded max retry (${a})`);n||3===h||(r.resolved=!0)}else this.state=2===h?te.WAITING_LEVEL:te.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===te.PARSING||this.state===te.PARSED){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===T&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==te.STOPPED&&(this.state=te.IDLE)}afterBufferFlushed(t,i,s){if(!t)return;const e=Vi.getBuffered(t);this.fragmentTracker.detectEvictedFragments(i,e,s),this.state===te.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==te.STOPPED&&(this.state=te.IDLE)}resetStartWhenNotLoaded(t){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const i=t?t.details:null;null!=i&&i.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(i,i.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of ${this.playlistLabel()} ${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){const n=s.details;if(n){var r;if(!Object.keys(t.elementaryStreams).reduce(((i,r)=>{const h=t.elementaryStreams[r];if(h){const o=h.endPTS-h.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${o})`),i||!1;const a=e?0:_s(n,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:s,drift:a,type:r,frag:t,start:h.startPTS,end:h.endPTS}),!0}return i}),!1)&&(0===s.fragmentError&&this.treatAsGap(t,s),null===(null==(r=this.transmuxer)?void 0:r.error))){const i=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(i.message),this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=te.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${i?" part: "+i.index:""} of ${this.fragInfo(t,!1,i)})`),this.hls.trigger(y.FRAG_PARSED,{frag:t,part:i})}else this.warn("level.details undefined")}playlistLabel(){return this.playlistType===S?"level":"track"}fragInfo(t,i=!0,s){var e,n;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${(null!=(e=i&&!s?t.startPTS:(s||t).start)?e:NaN).toFixed(3)}-${(null!=(n=i&&!s?t.endPTS:(s||t).end)?n:NaN).toFixed(3)}]${s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(t,i){i&&i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),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}}function se(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class ee{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}}var ne,re={exports:{}},he=(ne||(ne=1,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,u=this._events[o],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,i),!0;case 3:return u.fn.call(u.context,i,e),!0;case 4:return u.fn.call(u.context,i,e,n),!0;case 5:return u.fn.call(u.context,i,e,n,r),!0;case 6:return u.fn.call(u.context,i,e,n,r,h),!0}for(l=1,a=new Array(c-1);l<c;l++)a[l-1]=arguments[l];u.fn.apply(u.context,a)}else{var d,f=u.length;for(l=0;l<f;l++)switch(u[l].once&&this.removeListener(t,u[l].fn,void 0,!0),c){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,i);break;case 3:u[l].fn.call(u[l].context,i,e);break;case 4:u[l].fn.call(u[l].context,i,e,n);break;default:if(!a)for(d=1,a=new Array(c-1);d<c;d++)a[d-1]=arguments[d];u[l].fn.apply(u[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=[],u=o.length;a<u;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}(re)),re.exports),oe=H(he);const ae="1.6.6",le={};function ue(t,i){return 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}function ce(t,i){return 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}function de(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}function fe(t,i){const s=i;let e=0;for(;ce(t,i);)e+=10,e+=de(t,i+6),ue(t,i+10)&&(e+=10),i+=e;if(e>0)return t.subarray(s,s+e)}function ve(t,i){return 255===t[i]&&240==(246&t[i+1])}function ge(t,i){return 1&t[i+1]?7:9}function pe(t,i){return(3&t[i+3])<<11|t[i+4]<<3|(224&t[i+5])>>>5}function me(t,i){return i+1<t.length&&ve(t,i)}function ye(t,i){if(me(t,i)){const s=ge(t,i);if(i+s>=t.length)return!1;const e=pe(t,i);if(e<=s)return!1;const n=i+e;return n===t.length||me(t,n)}return!1}function be(t,i,s,e,n){if(!t.samplerate){const r=function(t,i,s,e){const n=i[s+2],r=n>>2&15;if(r>12){const i=new Error(`invalid ADTS sampling index:${r}`);return void t.emit(y.ERROR,y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!0,error:i,reason:i.message})}const h=1+(n>>6&3),o=i[s+3]>>6&3|(1&n)<<2,a="mp4a.40."+h,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][r];let u=r;5!==h&&29!==h||(u-=3);const c=[h<<3|(14&u)>>1,(1&u)<<7|o<<3];return F.log(`manifest codec:${e}, parsed codec:${a}, channels:${o}, rate:${l} (ADTS object type:${h} sampling index:${r})`),{config:c,samplerate:l,channelCount:o,codec:a,parsedCodec:a,manifestCodec:e}}(i,s,e,n);if(!r)return;x(t,r)}}function we(t){return 9216e4/t}function $e(t,i,s,e,n){const r=e+n*we(t.samplerate),h=function(t,i){const s=ge(t,i);if(i+s<=t.length){const e=pe(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 u={unit:o,pts:r};return l||t.samples.push(u),{sample:u,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}}function ke(t,i){return ce(t,i)&&de(t,i+6)+10<=t.length-i}function Se(t,i=0,s=1/0){return function(t,i,s,e){const n=(r=t)instanceof ArrayBuffer?r:r.buffer;var r;let h=1;"BYTES_PER_ELEMENT"in e&&(h=e.BYTES_PER_ELEMENT);const o=(u=t)&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0,a=(o+t.byteLength)/h,l=Math.floor(Math.max(0,Math.min((o+i)/h,a)));var u;return new e(n,l,Math.floor(Math.min(l+Math.max(s,0),a))-l)}(t,i,s,Uint8Array)}function Te(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const i=j(t.data,!0),s=new Uint8Array(t.data.subarray(i.length+1));return{key:t.type,info:i,data:s.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let i=1;const s=j(t.data.subarray(i),!0);i+=s.length+1;const e=j(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=j(t.data);return{key:t.type,info:"",data:i}}(t):"APIC"===t.type?function(t){const i={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=t.data.subarray(1).indexOf(0);if(-1===s)return;const e=j(Se(t.data,1,s)),n=t.data[2+s],r=t.data.subarray(3+s).indexOf(0);if(-1===r)return;const h=j(Se(t.data,3+s,r));let o;return o="--\x3e"===e?j(Se(t.data,4+s+r)):(a=t.data.subarray(4+s+r))instanceof ArrayBuffer?a:0==a.byteOffset&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer,i.mimeType=e,i.pictureType=n,i.description=h,i.data=o,i;var a}(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let i=1;const s=j(t.data.subarray(i),!0);i+=s.length+1;const e=j(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=j(t.data.subarray(1));return{key:t.type,info:"",data:i}}(t)}function Ee(t){const i=String.fromCharCode(t[0],t[1],t[2],t[3]),s=de(t,4);return{type:i,size:s,data:t.subarray(10,10+s)}}const Ae=10,Le=10;function Me(t){let i=0;const s=[];for(;ce(t,i);){const e=de(t,i+6);t[i+5]>>6&1&&(i+=Ae),i+=Ae;const n=i+e;for(;i+Le<n;){const e=Ee(t.subarray(i)),n=Te(e);n&&s.push(n),i+=e.size+Ae}ue(t,i)&&(i+=Ae)}return s}function xe(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Ie(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)}}function De(t){const i=Me(t);for(let t=0;t<i.length;t++){const s=i[t];if(xe(s))return Ie(s)}}let Pe=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Ce(t="",i=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:i,sequenceNumber:-1,samples:[],dropped:0}}class Re{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=Tt(this.cachedData,t),this.cachedData=null);let s,e=fe(t,0),n=e?e.length:0;const r=this._audioTrack,h=this._id3Track,o=e?De(e):void 0,a=t.length;for((null===this.basePTS||0===this.frameIndex&&f(o))&&(this.basePTS=Oe(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:Pe.audioId3,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 ke(t,n)?(e=fe(t,n),h.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:e,type:Pe.audioId3,duration:Number.POSITIVE_INFINITY}),n+=e.length,s=n):n++;if(n===a&&s!==a){const i=t.slice(s);this.cachedData=this.cachedData?Tt(this.cachedData,i):i}}return{audioTrack:r,videoTrack:Ce(),id3Track:h,textTrack:Ce()}}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:Ce(),id3Track:this._id3Track,textTrack:Ce()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Oe=(t,i,s)=>f(t)?90*t:9e4*i+(s?9e4*s.baseTime/s.timescale:0);let Ne=null;const Ue=[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],Fe=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Be=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],_e=[0,1,1,4];function je(t,i,s,e,n){if(s+24>i.length)return;const r=Ge(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 Ge(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*Ue[14*(3===s?3-e:3===e?3:4)+n-1],a=Fe[3*(3===s?0:2===s?1:2)+r],l=3===h?1:2,u=Be[s][e],c=_e[e],d=8*u*c,f=Math.floor(u*o/a+(t[i+2]>>1&1))*c;if(null===Ne){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ne=t?parseInt(t[1]):0}return!!Ne&&Ne<=87&&2===e&&o>=224e3&&0===h&&(t[i+3]=128|t[i+3]),{sampleRate:a,channelCount:l,frameLength:f,samplesPerFrame:d}}}function He(t,i){return!(255!==t[i]||224&~t[i+1]||!(6&t[i+1]))}function Ke(t,i){return i+1<t.length&&He(t,i)}function Ve(t,i){if(i+1<t.length&&He(t,i)){const s=4,e=Ge(t,i);let n=s;null!=e&&e.frameLength&&(n=e.frameLength);const r=i+n;return r===t.length||Ke(t,r)}return!1}const Xe=(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 We(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 u=0;2===l?u+=2:(1&l&&1!==l&&(u+=2),4&l&&(u+=2));const c=(i[s+6]<<8|i[s+7])>>12-u&1,d=[2,1,2,3,3,4,4,5][l]+c,f=7&i[s+5],v=new Uint8Array([r<<6|i[s+5]>>3<<1|f>>2,(3&f)<<6|l<<3|c<<2|o>>4,o<<4&224]),g=e+n*(1536/h*9e4),p=i.subarray(s,s+a);return t.config=v,t.channelCount=d,t.samplerate=h,t.samples.push({unit:p,pts:g}),a}const ze=/\/emsg[-/]ID3/i;function qe(t,i){return f(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class Ye{constructor(t,i,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ni(i,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,0)}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}}}}class Qe{constructor(){this.VideoSample=null}createVideoSample(t,i,s){return{key:t,frame:!1,pts:i,dts:s,units:[],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)}}parseNALu(t,i,s){const e=i.byteLength;let n=t.naluState||0;const r=n,h=[];let o,a,l,u=0,c=-1,d=0;for(-1===n&&(c=0,d=this.getNALuType(i,0),n=0,u=1);u<e;)if(o=i[u++],n)if(1!==n)if(o)if(1===o){if(a=u-n-1,c>=0){const t={data:i.subarray(c,a),type:d};h.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(r&&u<=4-r&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-r)),a>0&&(s.data=Tt(s.data,i.subarray(0,a)),s.state=0))}u<e?(l=this.getNALuType(i,u),c=u,d=l,n=0):n=-1}else n=0;else n=3;else n=o?0:2;else n=o?0:1;if(c>=0&&n>=0){const t={data:i.subarray(c,e),type:d,state:n};h.push(t)}if(0===h.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Tt(s.data,i))}return t.naluState=n,h}}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&&F.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)}}class Ze extends Qe{parsePES(t,i,s,e){const n=this.parseNALu(t,s.data,e);let r,h=this.VideoSample,o=!1;s.data=null,h&&n.length&&!t.audFound&&(this.pushAccessUnit(h,t),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach((e=>{var n,a;switch(e.type){case 1:{let i=!1;r=!0;const n=e.data;if(o&&n.length>4){const t=this.readSliceType(n);2!==t&&4!==t&&7!==t&&9!==t||(i=!0)}var l;i&&null!=(l=h)&&l.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.frame=!0,h.key=i;break}case 5:r=!0,null!=(n=h)&&n.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 6:r=!0,Mt(e.data,1,s.pts,i.samples);break;case 7:{var u,c;r=!0,o=!0;const i=e.data,s=this.readSPS(i);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(u=t.pixelRatio)?void 0:u[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[i];const e=i.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let i=e[t].toString(16);i.length<2&&(i="0"+i),n+=i}t.codec=n}break}case 8:r=!0,t.pps=[e.data];break;case 9:r=!0,t.audFound=!0,null!=(a=h)&&a.frame&&(this.pushAccessUnit(h,t),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:r=!0;break;default:r=!1}h&&r&&h.units.push(e)})),e&&h&&(this.pushAccessUnit(h,t),this.VideoSample=null)}getNALuType(t,i){return 31&t[i]}readSliceType(t){const i=new Je(t);return i.readUByte(),i.readUEG(),i.readUEG()}skipScalingList(t,i){let s,e=8,n=8;for(let r=0;r<t;r++)0!==n&&(s=i.readEG(),n=(e+s+256)%256),e=0===n?e:n}readSPS(t){const i=new Je(t);let s,e,n,r=0,h=0,o=0,a=0;const l=i.readUByte.bind(i),u=i.readBits.bind(i),c=i.readUEG.bind(i),d=i.readBoolean.bind(i),f=i.skipBits.bind(i),v=i.skipEG.bind(i),g=i.skipUEG.bind(i),p=this.skipScalingList.bind(this);l();const m=l();if(u(5),f(3),l(),g(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const t=c();if(3===t&&f(1),g(),g(),f(1),d())for(e=3!==t?8:12,n=0;n<e;n++)d()&&p(n<6?16:64,i)}g();const y=c();if(0===y)c();else if(1===y)for(f(1),v(),v(),s=c(),n=0;n<s;n++)v();g(),f(1);const b=c(),w=c(),$=u(1);0===$&&f(1),f(1),d()&&(r=c(),h=c(),o=c(),a=c());let k=[1,1];if(d()&&d())switch(l()){case 1:k=[1,1];break;case 2:k=[12,11];break;case 3:k=[10,11];break;case 4:k=[16,11];break;case 5:k=[40,33];break;case 6:k=[24,11];break;case 7:k=[20,11];break;case 8:k=[32,11];break;case 9:k=[80,33];break;case 10:k=[18,11];break;case 11:k=[15,11];break;case 12:k=[64,33];break;case 13:k=[160,99];break;case 14:k=[4,3];break;case 15:k=[3,2];break;case 16:k=[2,1];break;case 255:k=[l()<<8|l(),l()<<8|l()]}return{width:Math.ceil(16*(b+1)-2*r-2*h),height:(2-$)*(w+1)*16-($?2:4)*(o+a),pixelRatio:k}}}class tn extends Qe{constructor(...t){super(...t),this.initVPS=null}parsePES(t,i,s,e){const n=this.parseNALu(t,s.data,e);let r,h=this.VideoSample,o=!1;s.data=null,h&&n.length&&!t.audFound&&(this.pushAccessUnit(h,t),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach((e=>{var n,a;switch(e.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),h.frame=!0,r=!0;break;case 16:case 17:case 18:case 21:var l;r=!0,o&&null!=(l=h)&&l.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 19:case 20:r=!0,null!=(n=h)&&n.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 39:r=!0,Mt(e.data,2,s.pts,i.samples);break;case 32:r=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=x(t.params,this.readVPS(e.data)),this.initVPS=e.data),t.vps=[e.data];break;case 33:if(r=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],e.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const i=this.readSPS(e.data);t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.codec=i.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const s in i.params)t.params[s]=i.params[s]}this.pushParameterSet(t.sps,e.data,t.vps),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0;break;case 34:if(r=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const i=this.readPPS(e.data);for(const s in i)t.params[s]=i[s]}this.pushParameterSet(t.pps,e.data,t.vps)}break;case 35:r=!0,t.audFound=!0,null!=(a=h)&&a.frame&&(this.pushAccessUnit(h,t),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:r=!1}h&&r&&h.units.push(e)})),e&&h&&(this.pushAccessUnit(h,t),this.VideoSample=null)}pushParameterSet(t,i,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(i)}getNALuType(t,i){return(126&t[i])>>>1}ebsp2rbsp(t){const i=new Uint8Array(t.byteLength);let s=0;for(let e=0;e<t.byteLength;e++)e>=2&&3===t[e]&&0===t[e-1]&&0===t[e-2]||(i[s]=t[e],s++);return new Uint8Array(i.buffer,0,s)}pushAccessUnit(t,i){super.pushAccessUnit(t,i),this.initVPS&&(this.initVPS=null)}readVPS(t){const i=new Je(t);return i.readUByte(),i.readUByte(),i.readBits(4),i.skipBits(2),i.readBits(6),{numTemporalLayers:i.readBits(3)+1,temporalIdNested:i.readBoolean()}}readSPS(t){const i=new Je(this.ebsp2rbsp(t));i.readUByte(),i.readUByte(),i.readBits(4);const s=i.readBits(3);i.readBoolean();const e=i.readBits(2),n=i.readBoolean(),r=i.readBits(5),h=i.readUByte(),o=i.readUByte(),a=i.readUByte(),l=i.readUByte(),u=i.readUByte(),c=i.readUByte(),d=i.readUByte(),f=i.readUByte(),v=i.readUByte(),g=i.readUByte(),p=i.readUByte(),m=[],y=[];for(let t=0;t<s;t++)m.push(i.readBoolean()),y.push(i.readBoolean());if(s>0)for(let t=s;t<8;t++)i.readBits(2);for(let t=0;t<s;t++)m[t]&&(i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte()),y[t]&&i.readUByte();i.readUEG();const b=i.readUEG();3==b&&i.skipBits(1);const w=i.readUEG(),$=i.readUEG(),k=i.readBoolean();let S=0,T=0,E=0,A=0;k&&(S+=i.readUEG(),T+=i.readUEG(),E+=i.readUEG(),A+=i.readUEG());const L=i.readUEG(),M=i.readUEG(),x=i.readUEG();for(let t=i.readBoolean()?0:s;t<=s;t++)i.skipUEG(),i.skipUEG(),i.skipUEG();if(i.skipUEG(),i.skipUEG(),i.skipUEG(),i.skipUEG(),i.skipUEG(),i.skipUEG(),i.readBoolean()&&i.readBoolean())for(let t=0;t<4;t++)for(let s=0;s<(3===t?2:6);s++)if(i.readBoolean()){const s=Math.min(64,1<<4+(t<<1));t>1&&i.readEG();for(let t=0;t<s;t++)i.readEG()}else i.readUEG();i.readBoolean(),i.readBoolean(),i.readBoolean()&&(i.readUByte(),i.skipUEG(),i.skipUEG(),i.readBoolean());const I=i.readUEG();let D=0;for(let t=0;t<I;t++){let s=!1;if(0!==t&&(s=i.readBoolean()),s){t===I&&i.readUEG(),i.readBoolean(),i.readUEG();let s=0;for(let t=0;t<=D;t++){const t=i.readBoolean();let e=!1;t||(e=i.readBoolean()),(t||e)&&s++}D=s}else{const t=i.readUEG(),s=i.readUEG();D=t+s;for(let s=0;s<t;s++)i.readUEG(),i.readBoolean();for(let t=0;t<s;t++)i.readUEG(),i.readBoolean()}}if(i.readBoolean()){const t=i.readUEG();for(let s=0;s<t;s++){for(let t=0;t<x+4;t++)i.readBits(1);i.readBits(1)}}let P=0,C=1,R=1,O=!0,N=1,U=0;i.readBoolean(),i.readBoolean();let F=!1;if(i.readBoolean()){if(i.readBoolean()){const t=i.readUByte();t>0&&t<16?(C=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],R=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(C=i.readBits(16),R=i.readBits(16))}if(i.readBoolean()&&i.readBoolean(),i.readBoolean()&&(i.readBits(3),i.readBoolean(),i.readBoolean()&&(i.readUByte(),i.readUByte(),i.readUByte())),i.readBoolean()&&(i.readUEG(),i.readUEG()),i.readBoolean(),i.readBoolean(),i.readBoolean(),F=i.readBoolean(),F&&(S+=i.readUEG(),T+=i.readUEG(),E+=i.readUEG(),A+=i.readUEG()),i.readBoolean()&&(N=i.readBits(32),U=i.readBits(32),i.readBoolean()&&i.readUEG(),i.readBoolean())){const t=i.readBoolean(),e=i.readBoolean();let n=!1;(t||e)&&(n=i.readBoolean(),n&&(i.readUByte(),i.readBits(5),i.readBoolean(),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5));for(let r=0;r<=s;r++){O=i.readBoolean();let s=!1;O||i.readBoolean()?i.readEG():s=i.readBoolean();const r=s?1:i.readUEG()+1;if(t)for(let t=0;t<r;t++)i.readUEG(),i.readUEG(),n&&(i.readUEG(),i.readUEG()),i.skipBits(1);if(e)for(let t=0;t<r;t++)i.readUEG(),i.readUEG(),n&&(i.readUEG(),i.readUEG()),i.skipBits(1)}}i.readBoolean()&&(i.readBoolean(),i.readBoolean(),i.readBoolean(),P=i.readUEG())}let B=w,_=$;if(k||F){let t=1,i=1;1===b?t=i=2:2==b&&(t=2),B=w-t*T-t*S,_=$-i*A-i*E}const j=e?["A","B","C"][e]:"",G=h<<24|o<<16|a<<8|l;let H=0;for(let t=0;t<32;t++)H=(H|(G>>t&1)<<31-t)>>>0;let K=H.toString(16);return 1===r&&"2"===K&&(K="6"),{codecString:`hvc1.${j}${r}.${K}.${n?"H":"L"}${p}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:e,general_profile_compatibility_flags:[h,o,a,l],general_constraint_indicator_flags:[u,c,d,f,v,g],general_level_idc:p,bit_depth:L+8,bit_depth_luma_minus8:L,bit_depth_chroma_minus8:M,min_spatial_segmentation_idc:P,chroma_format_idc:b,frame_rate:{fixed:O,fps:U/N}},width:B,height:_,pixelRatio:[C,R]}}readPPS(t){const i=new Je(this.ebsp2rbsp(t));i.readUByte(),i.readUByte(),i.skipUEG(),i.skipUEG(),i.skipBits(2),i.skipBits(3),i.skipBits(2),i.skipUEG(),i.skipUEG(),i.skipEG(),i.skipBits(2),i.readBoolean()&&i.skipUEG(),i.skipEG(),i.skipEG(),i.skipBits(4);const s=i.readBoolean(),e=i.readBoolean();let n=1;return e&&s?n=0:e?n=3:s&&(n=2),{parallelismType:n}}matchSPS(t,i){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,i).substr(3)}}const sn=188;class en{constructor(t,i,s,e){this.logger=void 0,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._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.logger=e,this.videoParser=null}static probe(t,i){const s=en.syncOffset(t);return s>0&&i.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(t){const i=t.length;let s=Math.min(940,i-sn)+1,e=0;for(;e<s;){let n=!1,r=-1,h=0;for(let o=e;o<i;o+=sn){if(71!==t[o]||i-o!==sn&&71!==t[o+sn]){if(h)return-1;break}if(h++,-1===r&&(r=o,0!==r&&(s=Math.min(r+18612,t.length-sn)+1)),n||(n=0===nn(t,o)),n&&h>1&&(0===r&&h>2||o+sn>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=en.createTrack("video"),this._videoTrack.duration=e,this._audioTrack=en.createTrack("audio",e),this._id3Track=en.createTrack("id3"),this._txtTrack=en.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=s}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,u=r.pesData,c=h.pid,d=o.pid,f=h.pesData,v=o.pesData,g=null,p=this.pmtParsed,m=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=Tt(this.remainderData,t)).length,this.remainderData=null),y<sn&&!e)return this.remainderData=t,{audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};const b=Math.max(0,en.syncOffset(t));y-=(y-b)%sn,y<t.byteLength&&!e&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let w=0;for(let i=b;i<y;i+=sn)if(71===t[i]){const e=!!(64&t[i+1]),y=nn(t,i);let w;if((48&t[i+3])>>4>1){if(w=i+5+t[i+4],w===i+sn)continue}else w=i+4;switch(y){case l:if(e){if(u&&(n=ln(u,this.logger))){if(null===this.videoParser)switch(r.segmentCodec){case"avc":this.videoParser=new Ze;break;case"hevc":this.videoParser=new tn}null!==this.videoParser&&this.videoParser.parsePES(r,a,n,!1)}u={data:[],size:0}}u&&(u.data.push(t.subarray(w,i+sn)),u.size+=i+sn-w);break;case c:if(e){if(f&&(n=ln(f,this.logger)))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(w,i+sn)),f.size+=i+sn-w);break;case d:e&&(v&&(n=ln(v,this.logger))&&this.parseID3PES(o,n),v={data:[],size:0}),v&&(v.data.push(t.subarray(w,i+sn)),v.size+=i+sn-w);break;case 0:e&&(w+=t[w]+1),m=this._pmtId=rn(t,w);break;case m:{e&&(w+=t[w]+1);const n=hn(t,w,this.typeSupported,s,this.observer,this.logger);l=n.videoPid,l>0&&(r.pid=l,r.segmentCodec=n.segmentVideoCodec),c=n.audioPid,c>0&&(h.pid=c,h.segmentCodec=n.segmentAudioCodec),d=n.id3Pid,d>0&&(o.pid=d),null===g||p||(this.logger.warn(`MPEG-TS PMT found at ${i} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,i=b-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=y}}else w++;w>0&&on(this.observer,new Error(`Found ${w} TS packet/s that do not start with 0x47`),void 0,this.logger),r.pesData=u,h.pesData=f,o.pesData=v;const $={audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};return e&&this.extractRemainingSamples($),$}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=ln(r,this.logger))){if(null===this.videoParser)switch(s.segmentCodec){case"avc":this.videoParser=new Ze;break;case"hevc":this.videoParser=new tn}null!==this.videoParser&&(this.videoParser.parsePES(s,n,a,!0),s.pesData=null)}else s.pesData=r;if(h&&(a=ln(h,this.logger))){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&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=h;o&&(a=ln(o,this.logger))?(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 Ye(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.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 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=Tt(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&&!me(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",on(this.observer,new Error(t),i,this.logger),!i)return}if(be(t,this.observer,o,n,this.audioCodec),void 0!==i.pts)h=i.pts;else{if(!e)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const i=we(t.samplerate);h=e.sample.pts+i}}let a,l=0;for(;n<r;){if(a=$e(t,o,n,h,l),n+=a.length,a.missing){this.aacOverFlow=a;break}for(l++;n<r-1&&!me(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(Ke(s,r)){const i=je(t,s,r,h,n);if(!i)break;r+=i.length,n++}else r++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,i){{const s=i.data,e=i.pts;if(void 0===e)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const n=s.length;let r,h=0,o=0;for(;o<n&&(r=We(t,s,o,e,h++))>0;)o+=r}}parseID3PES(t,i){if(void 0===i.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=x({},i,{type:this._videoTrack?Pe.emsg:Pe.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function nn(t,i){return((31&t[i+1])<<8)+t[i+2]}function rn(t,i){return(31&t[i+10])<<8|t[i+11]}function hn(t,i,s,e,n,r){const h={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=i+3+((15&t[i+1])<<8|t[i+2])-4;for(i+=12+((15&t[i+10])<<8|t[i+11]);i<o;){const o=nn(t,i),a=(15&t[i+3])<<8|t[i+4];switch(t[i]){case 207:if(!e){an("ADTS AAC",r);break}case 15:-1===h.audioPid&&(h.audioPid=o);break;case 21:-1===h.id3Pid&&(h.id3Pid=o);break;case 219:if(!e){an("H.264",r);break}case 27:-1===h.videoPid&&(h.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===h.audioPid&&(h.audioPid=o,h.segmentAudioCodec="mp3"):r.log("MPEG audio found, not supported in this browser");break;case 193:if(!e){an("AC-3",r);break}case 129:s.ac3?-1===h.audioPid&&(h.audioPid=o,h.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===h.audioPid&&a>0){let e=i+5,n=a;for(;n>2;){106===t[e]&&(!0!==s.ac3?r.log("AC-3 audio found, not supported in this browser for now"):(h.audioPid=o,h.segmentAudioCodec="ac3"));const i=t[e+1]+2;e+=i,n-=i}}break;case 194:case 135:return on(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),h;case 36:-1===h.videoPid&&(h.videoPid=o,h.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"))}i+=a+5}return h}function on(t,i,s,e){e.warn(`parsing error: ${i.message}`),t.emit(y.ERROR,y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:i,reason:i.message})}function an(t,i){i.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function ln(t,i){let s,e,n,r,h,o=0;const a=t.data;if(!t||0===t.size)return null;for(;a[0].length<19&&a.length>1;)a[0]=Tt(a[0],a[1]),a.splice(1,1);if(s=a[0],1===(s[0]<<16)+(s[1]<<8)+s[2]){if(e=(s[4]<<8)+s[5],e&&e>t.size-6)return null;const l=s[7];192&l&&(r=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&l?(h=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,r-h>54e5&&(i.warn(`${Math.round((r-h)/9e4)}s delta between PTS and DTS, align them`),r=h)):h=r),n=s[8];let u=n+9;if(t.size<=u)return null;t.size-=u;const c=new Uint8Array(t.size);for(let t=0,i=a.length;t<i;t++){s=a[t];let i=s.byteLength;if(u){if(u>i){u-=i;continue}s=s.subarray(u),i-=u,u=0}c.set(s,o),o+=i}return e&&(e-=n+3),{data:c,pts:r,dts:h,len:e}}return null}class un{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 cn=Math.pow(2,32)-1;class dn{static init(){let t;for(t in dn.types={avc1:[],avcC:[],hvc1:[],hvcC:[],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:[]},dn.types)dn.types.hasOwnProperty(t)&&(dn.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]);dn.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]);dn.STTS=dn.STSC=dn.STCO=n,dn.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),dn.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),dn.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),dn.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]);dn.FTYP=dn.box(dn.types.ftyp,r,o,r,h),dn.DINF=dn.box(dn.types.dinf,dn.box(dn.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 dn.box(dn.types.hdlr,dn.HDLR_TYPES[t])}static mdat(t){return dn.box(dn.types.mdat,t)}static mdhd(t,i){i*=t;const s=Math.floor(i/(cn+1)),e=Math.floor(i%(cn+1));return dn.box(dn.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 dn.box(dn.types.mdia,dn.mdhd(t.timescale||0,t.duration||0),dn.hdlr(t.type),dn.minf(t))}static mfhd(t){return dn.box(dn.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return dn.box(dn.types.minf,"audio"===t.type?dn.box(dn.types.smhd,dn.SMHD):dn.box(dn.types.vmhd,dn.VMHD),dn.DINF,dn.stbl(t))}static moof(t,i,s){return dn.box(dn.types.moof,dn.mfhd(t),dn.traf(s,i))}static moov(t){let i=t.length;const s=[];for(;i--;)s[i]=dn.trak(t[i]);return dn.box.apply(null,[dn.types.moov,dn.mvhd(t[0].timescale||0,t[0].duration||0)].concat(s).concat(dn.mvex(t)))}static mvex(t){let i=t.length;const s=[];for(;i--;)s[i]=dn.trex(t[i]);return dn.box.apply(null,[dn.types.mvex,...s])}static mvhd(t,i){i*=t;const s=Math.floor(i/(cn+1)),e=Math.floor(i%(cn+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 dn.box(dn.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 dn.box(dn.types.sdtp,s)}static stbl(t){return dn.box(dn.types.stbl,dn.stsd(t),dn.box(dn.types.stts,dn.STTS),dn.box(dn.types.stsc,dn.STSC),dn.box(dn.types.stsz,dn.STSZ),dn.box(dn.types.stco,dn.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=dn.box(dn.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],u=t.pixelRatio[1];return dn.box(dn.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,dn.box(dn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),dn.box(dn.types.pasp,new Uint8Array([l>>24,l>>16&255,l>>8&255,255&l,u>>24,u>>16&255,u>>8&255,255&u])))}static esds(t){return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t.config,6,1,2])}static audioStsd(t){const i=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,i>>8&255,255&i,0,0])}static mp4a(t){return dn.box(dn.types.mp4a,dn.audioStsd(t),dn.box(dn.types.esds,dn.esds(t)))}static mp3(t){return dn.box(dn.types[".mp3"],dn.audioStsd(t))}static ac3(t){return dn.box(dn.types["ac-3"],dn.audioStsd(t),dn.box(dn.types.dac3,t.config))}static stsd(t){const{segmentCodec:i}=t;if("audio"===t.type){if("aac"===i)return dn.box(dn.types.stsd,dn.STSD,dn.mp4a(t));if("ac3"===i&&t.config)return dn.box(dn.types.stsd,dn.STSD,dn.ac3(t));if("mp3"===i&&"mp3"===t.codec)return dn.box(dn.types.stsd,dn.STSD,dn.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===i)return dn.box(dn.types.stsd,dn.STSD,dn.avc1(t));if("hevc"===i&&t.vps)return dn.box(dn.types.stsd,dn.STSD,dn.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${i}/${t.codec})`)}static tkhd(t){const i=t.id,s=(t.duration||0)*(t.timescale||0),e=t.width||0,n=t.height||0,r=Math.floor(s/(cn+1)),h=Math.floor(s%(cn+1));return dn.box(dn.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=dn.sdtp(t),e=t.id,n=Math.floor(i/(cn+1)),r=Math.floor(i%(cn+1));return dn.box(dn.types.traf,dn.box(dn.types.tfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e])),dn.box(dn.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])),dn.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,dn.box(dn.types.trak,dn.tkhd(t),dn.mdia(t))}static trex(t){const i=t.id;return dn.box(dn.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,u,c;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,u=o.flags,c=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,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*h);return dn.box(dn.types.trun,r)}static initSegment(t){dn.types||dn.init();const i=dn.moov(t);return Tt(dn.FTYP,i)}static hvc1(t){const i=t.params,s=[t.vps,t.sps,t.pps],e=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),s.length]);let n=e.length;for(let t=0;t<s.length;t+=1){n+=3;for(let i=0;i<s[t].length;i+=1)n+=2+s[t][i].length}const r=new Uint8Array(n);r.set(e,0),n=e.length;const h=s.length-1;for(let t=0;t<s.length;t+=1){r.set(new Uint8Array([32+t|(t===h?128:0),0,s[t].length]),n),n+=3;for(let i=0;i<s[t].length;i+=1)r.set(new Uint8Array([s[t][i].length>>8,255&s[t][i].length]),n),n+=2,r.set(s[t][i],n),n+=s[t][i].length}const o=dn.box(dn.types.hvcC,r),a=t.width,l=t.height,u=t.pixelRatio[0],c=t.pixelRatio[1];return dn.box(dn.types.hvc1,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,a>>8&255,255&a,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,dn.box(dn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),dn.box(dn.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))}}dn.types=void 0,dn.HDLR_TYPES=void 0,dn.STTS=void 0,dn.STSC=void 0,dn.STCO=void 0,dn.STSZ=void 0,dn.VMHD=void 0,dn.SMHD=void 0,dn.STSD=void 0,dn.FTYP=void 0,dn.DINF=void 0;function fn(t,i,s=1,e=!1){const n=t*i*s;return e?Math.round(n):n}function vn(t,i=!1){return fn(t,1e3,1/9e4,i)}let gn,pn=null,mn=null;function yn(t,i,s,e){return{duration:i,size:s,cts:e,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class bn extends P{constructor(t,i,s,e){if(super("mp4-remuxer",e),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=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===pn){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);pn=t?parseInt(t[1]):0}if(null===mn){const t=navigator.userAgent.match(/Safari\/(\d+)/i);mn=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){this.log("initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("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=wn(n,s),r=n-t),r>0?t:n}),s);return i&&this.debug("PTS rollover detected"),e}remux(t,i,s,e,n,r,h,o){let a,l,u,c,d,f,v=n,g=n;const p=i.pid>-1,m=i.samples.length,y=t.samples.length>0,b=h&&m>0||m>1;if((!(t.pid>-1)||y)&&(!p||b)||this.ISGenerated||h){if(this.ISGenerated){var w,$,k,S;const t=this.videoTrackConfig;(t&&(i.width!==t.width||i.height!==t.height||(null==(w=i.pixelRatio)?void 0:w[0])!==(null==($=t.pixelRatio)?void 0:$[0])||(null==(k=i.pixelRatio)?void 0:k[1])!==(null==(S=t.pixelRatio)?void 0:S[1]))||!t&&b||null===this.nextAudioTs&&y)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(t,i,n,r));const s=this.isVideoContiguous;let e,h=-1;if(b&&(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){this.warn(`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,g+=(i.samples[0].pts-t)/i.inputTimeScale,e=g}else-1===h&&(this.warn(`No keyframe found out of ${m} video samples`),f=!1);if(this.ISGenerated){if(y&&b){const s=this.getVideoStartPts(i.samples),e=(wn(t.samples[0].pts,s)-s)/i.inputTimeScale;v+=Math.max(0,e),g+=Math.max(0,-e)}if(y){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(t,i,n,r)),l=this.remuxAudio(t,v,this.isAudioContiguous,r,p||b||o===T?g:void 0),b){const e=l?l.endPTS-l.startPTS:0;i.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(t,i,n,r)),a=this.remuxVideo(i,g,s,e)}}else b&&(a=this.remuxVideo(i,g,s,0));a&&(a.firstKeyFrame=h,a.independent=-1!==h,a.firstKeyFramePTS=e)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(d=$n(s,n,this._initPTS,this._initDTS)),e.samples.length&&(c=kn(e,n,this._initPTS))),{audio:l,video:a,initSegment:u,independent:f,text:c,id3:d}}generateIS(t,i,s,e){const n=t.samples,r=i.samples,h=this.typeSupported,o={},a=this._initPTS;let l,u,c,d,f=!a||e,v="audio/mp4";if(f&&(l=u=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":h.mpeg?(v="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:v,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):dn.initSegment([t]),metadata:{channelCount:t.channelCount}},f&&(d=t.id,c=t.inputTimeScale,a&&c===a.timescale?f=!1:l=u=n[0].pts-Math.round(c*s))}if(i.sps&&i.pps&&r.length){if(i.timescale=i.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:i.codec,initSegment:dn.initSegment([i]),metadata:{width:i.width,height:i.height}},f)if(d=i.id,c=i.inputTimeScale,a&&c===a.timescale)f=!1;else{const t=this.getVideoStartPts(r),i=Math.round(c*s);u=Math.min(u,wn(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,f?(this._initPTS={baseTime:l,timescale:c},this._initDTS={baseTime:u,timescale:c}):l=c=void 0,{tracks:o,initPTS:l,timescale:c,trackId:d}}remuxVideo(t,i,s,e){const n=t.inputTimeScale,r=t.samples,h=[],o=r.length,a=this._initPTS,l=a.baseTime*n/a.timescale;let u,c,d=this.nextVideoTs,f=8,v=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,w=!1;if(!s||null===d){const t=l+i*n,e=r[0].pts-wn(r[0].dts,r[0].pts);pn&&null!==d&&Math.abs(t-e-(d+l))<15e3?s=!0:d=t-e-l}const $=d+l;for(let t=0;t<o;t++){const i=r[t];i.pts=wn(i.pts,$),i.dts=wn(i.dts,$),i.dts<r[t>0?t-1:t].dts&&(w=!0)}w&&r.sort((function(t,i){return t.dts-i.dts||t.pts-i.pts})),u=r[0].dts,c=r[r.length-1].dts;const k=c-u,S=k?Math.round(k/(o-1)):v||t.inputTimeScale/30;if(s){const s=u-$,e=s>S,n=s<-1;if((e||n)&&(this.warn(e?`${(t.segmentCodec||"").toUpperCase()}: ${vn(s,!0)} ms (${s}dts) hole between fragments detected at ${i.toFixed(3)}`:`${(t.segmentCodec||"").toUpperCase()}: ${vn(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${i.toFixed(3)}`),!n||$>=r[0].pts||pn)){u=$;const t=r[0].pts-s;if(e)r[0].dts=u,r[0].pts=t;else{let i=!0;for(let e=0;e<r.length&&!(r[e].dts>t&&i);e++){const t=r[e].pts;if(r[e].dts-=s,r[e].pts-=s,e<r.length-1){const s=r[e+1].pts;i=s<=r[e].pts==s<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${vn(t,!0)}/${vn(u,!0)}, delta: ${vn(s,!0)} ms`)}}u=Math.max(0,u);let T=0,E=0,A=u;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;E+=n,T+=e,i.length=n,i.dts<A?(i.dts=A,A+=S/4|0||1):A=i.dts,g=Math.min(i.pts,g),b=Math.max(i.pts,b)}c=r[o-1].dts;const L=E+4*T+8;let M;try{M=new Uint8Array(L)}catch(t){return void this.observer.emit(y.ERROR,y.ERROR,{type:p.MUX_ERROR,details:m.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:L,reason:`fail allocating video mdat ${L}`})}const I=new DataView(M.buffer);I.setUint32(0,L),M.set(dn.types.mdat,4);let D=!1,P=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const i=r[t],s=i.units;let a,u=0;for(let t=0,i=s.length;t<i;t++){const i=s[t],e=i.data,n=i.data.byteLength;I.setUint32(f,n),f+=4,M.set(e,f),f+=n,u+=4+n}if(t<o-1)v=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:S;if(a=t>0?i.pts-r[t-1].pts:S,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(s.maxBufferHole*n),r=(e?g+e*n:this.nextAudioTs+l)-i.pts;r>t?(v=r-h,v<0?v=h:D=!0,this.log(`It is approximately ${r/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=h}else v=h}const c=Math.round(i.pts-i.dts);P=Math.min(P,v),R=Math.max(R,v),C=Math.min(C,a),O=Math.max(O,a),h.push(yn(i.key,v,u,c))}if(h.length)if(pn){if(pn<70){const t=h[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(mn&&O-C<R-P&&S/R<.025&&0===h[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=u;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:S,h[i].cts=0,t=e}}v=D||!v?S:v,this.nextVideoTs=d=c+v-l,this.videoSampleDuration=v,this.isVideoContiguous=!0;const N={data1:dn.moof(t.sequenceNumber++,u,x(t,{samples:h})),data2:M,startPTS:(g-l)/n,endPTS:(b+v-l)/n,startDTS:(u-l)/n,endDTS:d/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,u="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],d=void 0!==n;let f=t.samples,v=u?0:8,g=this.nextAudioTs||-1;const b=l.baseTime*r/l.timescale,w=b+i*r;if(this.isAudioContiguous=s=s||f.length&&g>0&&(e&&Math.abs(w-(g+b))<9e3||Math.abs(wn(f[0].pts,w)-(g+b))<20*a),f.forEach((function(t){t.pts=wn(t.pts,w)})),!s||g<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;g=0===n?0:e&&!d?Math.max(0,w-b):f[0].pts-b}if("aac"===t.segmentCodec){const i=this.config.maxAudioFramesDrift;for(let s=0,e=g+b;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&&(this.warn(`Audio frame @ ${(h/r).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/r)} ms.`),this.nextAudioTs=g=h-b,e=h);else if(o>=i*a&&l<1e4&&d){let i=Math.round(o/a);for(e=h-i*a;e<0&&i&&a;)i--,e+=a;0===s&&(this.nextAudioTs=g=e-b),this.warn(`Injecting ${i} audio frames @ ${((e-b)/r).toFixed(3)}s due to ${Math.round(1e3*o/r)} ms gap.`);for(let r=0;r<i;r++){let i=un.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);i||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),i=n.unit.subarray()),f.splice(s,0,{unit:i,pts:e}),e+=a,s++}}n.pts=e,e+=a}}let $,k=null,S=null,T=0,E=f.length;for(;E--;)T+=f[E].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!==S)c[i-1].duration=Math.round((r-S)/h);else{if(s&&"aac"===t.segmentCodec&&(r=g+b),k=r,!(T>0))return;T+=v;try{$=new Uint8Array(T)}catch(t){return void this.observer.emit(y.ERROR,y.ERROR,{type:p.MUX_ERROR,details:m.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:T,reason:`fail allocating audio mdat ${T}`})}u||(new DataView($.buffer).setUint32(0,T),$.set(dn.types.mdat,4))}$.set(n,v);const a=n.byteLength;v+=a,c.push(yn(!0,o,a,0)),S=r}const A=c.length;if(!A)return;g=S-b,this.nextAudioTs=g+h*c[c.length-1].duration;const L=u?new Uint8Array(0):dn.moof(t.sequenceNumber++,k/h,x({},t,{samples:c}));t.samples=[];const M=(k-b)/r,I=g/r,D={data1:L,data2:$,startPTS:M,endPTS:I,startDTS:M,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,D}}function wn(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 $n(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=wn(n.pts-s.baseTime*r/s.timescale,i*r)/r,n.dts=wn(n.dts-e.baseTime*r/e.timescale,i*r)/r}const h=t.samples;return t.samples=[],{samples:h}}function kn(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=wn(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}}function Sn(t,i,s=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(s?t.duration:0))/t.timescale:i}function Tn(t,i,s){const e=null==t?void 0:t.codec;return e&&e.length>4?e:i===Z?"ec-3"===e||"ac-3"===e||"alac"===e?e:"fLaC"===e||"Opus"===e?jt(e,!1):(s.warn(`Unhandled audio codec "${e}" in mp4 MAP`),e||"mp4a"):(s.warn(`Unhandled video codec "${e}" in mp4 MAP`),e||"avc1")}try{gn=self.performance.now.bind(self.performance)}catch(t){gn=Date.now}const En=[{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=Ce("video",1),r=this.audioTrack=Ce("audio",1),h=this.txtTrack=Ce("text",1);if(this.id3Track=Ce("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=mt(t);if(o.video){const{id:t,timescale:i,codec:s,supplemental:e}=o.video;n.id=t,n.timescale=h.timescale=i,n.codec=s,n.supplemental=e}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=dt(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=Tt(this.remainderData,t));const i=function(t){const i={valid:null,remainder:null},s=gt(t,["moof"]);if(s.length<2)return i.remainder=t,i;const e=s[s.length-1];return i.valid=t.slice(0,e.byteOffset-8),i.remainder=t.slice(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=Et(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=Et(t,i),{videoTrack:i,audioTrack:Ce(),id3Track:e,textTrack:Ce()}}extractID3Track(t,i){const s=this.id3Track;if(t.samples.length){const e=gt(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"!==ut(t.subarray(l,l+1));)s+=ut(t.subarray(l,l+1)),l+=1;for(s+=ut(t.subarray(l,l+1)),l+=1;"\0"!==ut(t.subarray(l,l+1));)e+=ut(t.subarray(l,l+1)),l+=1;e+=ut(t.subarray(l,l+1)),l+=1,n=dt(t,12),r=dt(t,16),o=dt(t,20),a=dt(t,24),l=28}else if(1===i){l+=4,n=dt(t,l),l+=4;const i=dt(t,l);l+=4;const r=dt(t,l);for(l+=4,h=2**32*i+r,v(h)||(h=Number.MAX_SAFE_INTEGER,F.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=dt(t,l),l+=4,a=dt(t,l),l+=4;"\0"!==ut(t.subarray(l,l+1));)s+=ut(t.subarray(l,l+1)),l+=1;for(s+=ut(t.subarray(l,l+1)),l+=1;"\0"!==ut(t.subarray(l,l+1));)e+=ut(t.subarray(l,l+1)),l+=1;e+=ut(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(ze.test(e.schemeIdUri)){const t=qe(e,i);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:Pe.emsg,duration:n})}else if(this.config.enableEmsgKLVMetadata&&e.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=qe(e,i);s.samples.push({data:e.payload,len:e.payload.byteLength,dts:t,pts:t,type:Pe.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(t,i,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends P{constructor(t,i,s,e){super("passthrough-remuxer",e),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,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const i=this.initPTS;i&&t&&i.baseTime===t.baseTime&&i.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,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&>(t,["moov","trak"]).forEach((t=>{const i=gt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let e=gt(i,["enca"]);const n=e.length>0;n||(e=gt(i,["encv"])),e.forEach((t=>{gt(t.subarray(n?28:78),["sinf"]).forEach((t=>{const i=St(t);if(i){const t=i.subarray(8,24);t.some((t=>0!==t))||(F.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${G(t)} -> ${G(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=mt(t);e.audio&&(i=Tn(e.audio,Z,this)),e.video&&(s=Tn(e.video,tt,this));const n={};e.audio&&e.video?n.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:e.video.supplemental,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,supplemental:e.video.supplemental,initSegment:t,id:"main"}:this.warn("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 u={audio:void 0,video:void 0,text:e,id3:s,initSegment:void 0};f(l)||(l=this.lastEndTime=n||0);const c=i.samples;if(null==c||!c.length)return u;const d={initPTS:void 0,timescale:void 0,trackId:void 0};let v=this.initData;if(null!=(h=v)&&h.length||(this.generateInitSegment(c),v=this.initData),null==(o=v)||!o.length)return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,i,s){const e={},n=gt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const r=n[t],h=gt(r,["tfhd"])[0],o=dt(h,4),a=i[o];if(!a)continue;const l=e[o]||(e[o]={start:NaN,duration:0,sampleCount:0,timescale:a.timescale,type:a.type}),u=gt(r,["tfdt"])[0];if(u){const t=u[0];let i=dt(u,4);1===t&&(i===ot?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(i*=ot+1,i+=dt(u,8))),f(i)&&(!f(l.start)||i<l.start)&&(l.start=i)}const c=a.default,d=dt(h,0)|(null==c?void 0:c.flags);let v=(null==c?void 0:c.duration)||0;8&d&&(v=dt(h,2&d?12:8));const g=gt(r,["trun"]);let p=l.start||0,m=0,y=v;for(let t=0;t<g.length;t++){const i=g[t],s=dt(i,4),e=l.sampleCount;l.sampleCount+=s;const n=1&i[2],r=2&i[2],h=4&i[2],o=8&i[2];let a=8,u=s;for(1&i[3]&&(a+=4),4&i[3]&&s&&(1&i[a+1]||void 0!==l.keyFrameIndex||(l.keyFrameIndex=e),a+=4,n?(y=dt(i,a),a+=4):y=v,r&&(a+=4),o&&(a+=4),p+=y,m+=y,u--);u--;)n?(y=dt(i,a),a+=4):y=v,r&&(a+=4),h&&(1&i[a+1]||void 0===l.keyFrameIndex&&(l.keyFrameIndex=l.sampleCount-(u+1),l.keyFrameStart=p),a+=4),o&&(a+=4),p+=y,m+=y;!m&&v&&(m+=v*s)}l.duration+=m}if(!Object.keys(e).some((t=>e[t].duration))){let i=0;const s=gt(t,["sidx"]);for(let t=0;t<s.length;t++){const e=pt(s[t]);if(null!=e&&e.references){const t=e.references.reduce(((t,i)=>t+i.info.duration||0),0);i=Math.max(i,t+e.earliestPresentationTime/e.timescale)}}i&&f(i)&&Object.keys(e).forEach((t=>{e[t].duration||(e[t].duration=i*e[t].timescale-e[t].start)}))}return e}(c,v,this),p=v.audio?g[v.audio.id]:null,m=v.video?g[v.video.id]:null,y=Sn(m,1/0),b=Sn(p,1/0),w=Sn(m,0,!0),$=Sn(p,0,!0);let k,S=n,T=0;if(p&&(!m||!a&&b<y||a&&a.trackId===v.audio.id)?(d.trackId=v.audio.id,k=p,T=$-b):m&&(d.trackId=v.video.id,k=m,T=w-y),k){const t=k.timescale;S=k.start/t,d.initPTS=k.start-n*t,d.timescale=t,a||(this.initPTS=a={baseTime:d.initPTS,timescale:t,trackId:d.trackId})}!r&&a||!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,S,n,T)&&d.timescale===a.timescale||(d.initPTS=S-n,d.timescale=1,a&&1===a.timescale&&this.warn(`Adjusting initPTS @${n} from ${a.baseTime/a.timescale} to ${d.initPTS}`),this.initPTS=a={baseTime:d.initPTS,timescale:1});const E=t?S-a.baseTime/a.timescale:l,A=E+T;T>0?this.lastEndTime=A:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const L=!!v.audio,M=!!v.video;let x="";L&&(x+="audio"),M&&(x+="video");const I={data1:c,startPTS:E,startDTS:E,endPTS:A,endDTS:A,type:x,hasAudio:L,hasVideo:M,nb:1,dropped:0};u.audio=L&&!M?I:void 0,u.video=M?I:void 0;const D=null==m?void 0:m.sampleCount;if(D){const t=m.keyFrameIndex,i=-1!==t;I.nb=D,I.dropped=0===t||this.isVideoContiguous?0:i?t:D,I.independent=i,I.firstKeyFrame=t,i&&m.keyFrameStart&&(I.firstKeyFramePTS=(m.keyFrameStart-a.baseTime)/a.timescale),this.isVideoContiguous||(u.independent=i),this.isVideoContiguous||(this.isVideoContiguous=i),I.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${D} dropped: ${I.dropped} start: ${I.firstKeyFramePTS||"NA"}`)}return u.initSegment=d,u.id3=$n(s,n,a,a),e.samples.length&&(u.text=kn(e,n,a)),u}}},{demux:en,remux:bn},{demux:class extends Re{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,i){if(!t)return!1;const s=fe(t,0);let e=(null==s?void 0:s.length)||0;if(Ve(t,e))return!1;for(let s=t.length;e<s;e++)if(ye(t,e))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)&&ve(t,i)&&pe(t,i)<=t.length-i}(t,i)}appendFrame(t,i,s){be(t,this.observer,i,s,t.manifestCodec);const e=$e(t,i,s,this.basePTS,this.frameIndex);if(e&&0===e.missing)return e}},remux:bn},{demux:class extends Re{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=fe(t,0);let s=(null==i?void 0:i.length)||0;if(i&&11===t[s]&&119===t[s+1]&&void 0!==De(i)&&Xe(t,s)<=16)return!1;for(let i=t.length;s<i;s++)if(Ve(t,s))return F.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,i){return function(t,i){return He(t,i)&&4<=t.length-i}(t,i)}appendFrame(t,i,s){if(null!==this.basePTS)return je(t,i,s,this.basePTS,this.frameIndex)}},remux:bn}];En.splice(2,0,{demux:class extends Re{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=We(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=fe(t,0);if(!i)return!1;const s=i.length;return 11===t[s]&&119===t[s+1]&&void 0!==De(i)&&Xe(t,s)<16}},remux:bn});class An{constructor(t,i,s,e,n,r){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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.id=n,this.logger=r}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,i,s,e){const n=s.transmuxing;n.executeStart=gn();let r=new Uint8Array(t);const{currentTransmuxState:h,transmuxConfig:o}=this;e&&(this.currentTransmuxState=e);const{contiguous:a,discontinuity:l,trackSwitch:u,accurateTimeOffset:c,timeOffset:d,initSegmentChange:f}=e||h,{audioCodec:v,videoCodec:g,defaultInitPts:b,duration:w,initSegmentData:$}=o,k=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(k&&es(k.method)){const t=this.getDecrypter(),i=ns(k.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(r,k.key.buffer,k.iv.buffer,i).then((t=>{const i=this.push(t,null,s);return this.decryptionPromise=null,i})),this.decryptionPromise;{let e=t.softwareDecrypt(r,k.key.buffer,k.iv.buffer,i);if(s.part>-1){const i=t.flush();e=i?i.buffer:i}if(!e)return n.executeEnd=gn(),Ln(s);r=new Uint8Array(e)}}const S=this.needsProbing(l,u);if(S){const t=this.configureTransmuxer(r);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),n.executeEnd=gn(),Ln(s)}(l||u||f||S)&&this.resetInitSegment($,v,g,w,i),(l||f||S)&&this.resetInitialTimestamp(b),a||this.resetContiguity();const T=this.transmux(r,k,d,c,s);this.asyncResult=Mn(T);const E=this.currentTransmuxState;return E.contiguous=!0,E.discontinuity=!1,E.trackSwitch=!1,n.executeEnd=gn(),T}flush(t){const i=t.transmuxing;i.executeStart=gn();const{decrypter:s,currentTransmuxState:e,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then((()=>this.flush(t)));const r=[],{timeOffset:h}=e;if(s){const i=s.flush();i&&r.push(this.push(i.buffer,null,t))}const{demuxer:o,remuxer:a}=this;if(!o||!a){i.executeEnd=gn();const s=[Ln(t)];return this.asyncResult?Promise.resolve(s):s}const l=o.flush(h);return Mn(l)?(this.asyncResult=!0,l.then((i=>(this.flushRemux(r,i,t),r)))):(this.flushRemux(r,l,t),this.asyncResult?Promise.resolve(r):r)}flushRemux(t,i,s){const{audioTrack:e,videoTrack:n,id3Track:r,textTrack:h}=i,{accurateTimeOffset:o,timeOffset:a}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===S?"level":"track"} ${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=gn()}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}=this;let n;for(let i=0,s=En.length;i<s;i++){var r;if(null!=(r=En[i].demux)&&r.probe(t,this.logger)){n=En[i];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const h=this.demuxer,o=this.remuxer,a=n.remux,l=n.demux;o&&o instanceof a||(this.remuxer=new a(s,i,e,this.logger)),h&&h instanceof l||(this.demuxer=new l(s,i,e,this.logger),this.probe=l.probe)}needsProbing(t,i){return!this.demuxer||!this.remuxer||t||i}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Ni(this.config)),t}}const Ln=t=>({remuxResult:{},chunkMeta:t});function Mn(t){return"then"in t&&t.then instanceof Function}class xn{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 In{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}}let Dn=0;class Pn{constructor(t,i,s,e){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Dn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const i=t.data,s=this.hls;if(s&&null!=i&&i.event&&i.instanceNo===this.instanceNo)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":s.logger[i.data.logType]&&s.logger[i.data.logType](i.data.message);break;default:i.data=i.data||{},i.data.frag=this.frag,i.data.part=this.part,i.data.id=this.id,s.trigger(i.event,i.data)}},this.onWorkerError=t=>{if(!this.hls)return;const i=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})};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||void 0,t===y.ERROR&&(i.parent=this.id,i.part=this.part,this.error=i.error),this.hls.trigger(t,i)};this.observer=new oe,this.observer.on(y.FRAG_DECRYPTED,r),this.observer.on(y.ERROR,r);const h=Vt(n.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(n.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{n.workerPath?(s.log(`loading Web Worker ${n.workerPath} for "${i}"`),this.workerContext=function(t){const i=le[t];if(i)return i.clientCount++,i;const s=new self.URL(t,self.location.href).href,e={worker:new self.Worker(s),scriptURL:s,clientCount:1};return le[t]=e,e}(n.workerPath)):(s.log(`injecting Web Worker for "${i}"`),this.workerContext=function(){const t=le[ae];if(t)return t.clientCount++,t;const i=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(i),e={worker:new self.Worker(s),objectURL:s,clientCount:1};return le[ae]=e,e}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:h,id:i,config:ri(n)})}catch(e){s.warn(`Error setting up "${i}" Web Worker, fallback to inline`,e),this.terminateWorker(),this.error=null,this.transmuxer=new An(this.observer,h,n,"",i,t.logger)}return}}this.transmuxer=new An(this.observer,h,n,"",i,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Dn++;const i=this.hls.config,s=Vt(i.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:ri(i)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const i=le[t||ae];if(i&&1==i.clientCount--){const{worker:s,objectURL:e}=i;delete le[t||ae],e&&self.URL.revokeObjectURL(e),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,i,s,e,n,r,h,o,a,l){var u,c;a.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,v=r?r.start:n.start,g=n.decryptdata,p=this.frag,m=!(p&&n.cc===p.cc),y=!(p&&a.level===p.level),b=p?a.sn-p.sn:-1,w=this.part?a.part-this.part.index:-1,$=!y&&(1===b||0===b&&(1===w||0===b&&a.id>1&&a.id===(null==p?void 0:p.stats.chunkCount)&&w<=0)),k=self.performance.now();(y||b||0===n.stats.parsing.start)&&(n.stats.parsing.start=k),!r||!w&&$||(r.stats.parsing.start=k);const T=!(p&&(null==(u=n.initSegment)?void 0:u.url)===(null==(c=p.initSegment)?void 0:c.url)),E=new In(m,$,o,y,v,T);if(!$||m||T){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${a.sn}${a.part>-1?" part: "+a.part:""} ${this.id===S?"level":"track"}: ${a.level} id: ${a.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${$}\n accurateTimeOffset: ${o}\n timeOffset: ${v}\n initSegmentChange: ${T}`);const t=new xn(s,e,i,h,l);this.configureTransmuxer(t)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:t,decryptdata:g,chunkMeta:a,state:E},t instanceof ArrayBuffer?[t]:[]);else if(f){const i=f.push(t,g,a,E);Mn(i)?i.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,a,"transmuxer-interface push error")})):this.handleTransmuxComplete(i)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:i,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:t});else if(s){const i=s.flush(t);Mn(i)?i.then((i=>{this.handleFlushResult(i,t)})).catch((i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")})):this.handleFlushResult(i,t)}}transmuxerError(t,i,s){this.hls&&(this.error=t,this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,chunkMeta:i,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,i){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(i)}configureTransmuxer(t){const{instanceNo:i,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:i,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class Cn extends P{constructor(t,i){super(i,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,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.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){this.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&&ii(s);return new si(r,h>=0?h:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,i){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,i){if(i)try{return i.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return 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;e.advancedDateTime=Date.now()-h;const o=this.hls.config.timelineOffset;if(o!==e.appliedTimelineOffset){const t=Math.max(o||0,0);e.appliedTimelineOffset=t,e.fragments.forEach((i=>{i.start=i.playlistOffset+t}))}if(e.live||null!=s&&s.live){const o="levelInfo"in i?i.levelInfo:i.track;if(e.reloaded(s),s&&e.fragments.length>0){!function(t,i){if(t===i)return;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 l=n;l<=r;l++){const n=a[h+l];let r=o[l];if(e&&!r&&n&&(r=i.fragments[l]=n),n&&r){if(s(n,r,l,o),n.url&&n.url!==r.url)return void(i.playlistParsingError=js(`media sequence mismatch ${r.sn}:`,t,i,0,r));if(n.cc!==r.cc)return void(i.playlistParsingError=js(`discontinuity sequence mismatch (${n.cc}!=${r.cc})`,t,i,0,r))}}}(t,i,((t,e,r,h)=>{if((!i.startCC||i.skippedSegments)&&e.cc!==t.cc){const s=t.cc-e.cc;for(let t=r;t<h.length;t++)h[t].cc+=s;i.endCC=h[h.length-1].cc}f(t.startPTS)&&f(t.endPTS)&&(e.setStart(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.setDuration(t.endPTS-t.startPTS),e.duration&&(n=e),i.PTSKnown=i.alignedSliding=!0),t.hasStreams&&(e.elementaryStreams=t.elementaryStreams),e.loader=t.loader,t.hasStats&&(e.stats=t.stats),t.initSegment&&(e.initSegment=t.initSegment,s=t.initSegment)}));const r=i.fragments,h=i.fragmentHint?r.concat(i.fragmentHint):r;if(s&&h.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){F.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){const{dateRanges:s,recentlyRemovedDateranges:e}=i,n=x({},t);e&&e.forEach((t=>{delete n[t]}));const r=Object.keys(n).length;return r&&Object.keys(s).forEach((t=>{const i=n[t],e=new is(s[t].attr,i);e.isValid?(n[t]=e,i||(e.tagOrder+=r)):F.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ri(s[t].attr)}"`)})),n}(t.dateRanges,i));const s=t.fragments.filter((t=>t.rawProgramDateTime));if(t.hasProgramDateTime&&!i.hasProgramDateTime)for(let t=1;t<h.length;t++)null===h[t].programDateTime&&Rs(h[t],h[t-1],s);Ms(s,i)}i.endCC=r[r.length-1].cc}if(!i.startCC){var o;const s=Vs(t,i.startSN-1);i.startCC=null!=(o=null==s?void 0:s.cc)?o:r[0].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?_s(i,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Gs(t,i),r.length&&(i.totalduration=i.edge-r[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const a=i.advancedDateTime;if(i.advanced&&a){const t=i.edge;i.driftStart||(i.driftStartTime=a,i.driftStart=t),i.driftEndTime=a,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}(s,e);const t=e.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var a;const{networkDetails:r}=i;return void s.trigger(y.ERROR,{type:p.NETWORK_ERROR,details:m.LEVEL_PARSING_ERROR,fatal:!1,url:e.url,error:t,reason:t.message,level:i.level||void 0,parent:null==(a=e.fragments[0])?void 0:a.type,networkDetails:r,stats:n})}e.playlistParsingError=null}}-1===e.requestScheduled&&(e.requestScheduled=n.loading.start);const l=this.hls.mainForwardBufferInfo,u=Ks(e,1e3*(e.edge-(l?l.end-l.len:0)));if(e.requestScheduled+u<r?e.requestScheduled=r:e.requestScheduled+=u,this.log(`live playlist ${t} ${e.advanced?"REFRESHED "+e.lastPartSn+"-"+e.lastPartIndex:e.updated?"UPDATED":"MISSED"}`),!this.canLoad||!e.live)return;let c,d,v;if(e.canBlockReload&&e.endSN&&e.advanced){const t=this.hls.config.lowLatencyMode,n=e.lastPartSn,h=e.endSN,a=e.lastPartIndex,l=n===h;-1!==a?l?(d=h+1,v=t?0:a):(d=n,v=t?a+1:e.maxPartIndex):d=h+1;const u=e.age,f=u+e.ageHeader;let g=Math.min(f-e.partTarget,1.5*e.targetduration);if(g>0){if(f>3*e.targetduration)this.log(`Playlist last advanced ${u.toFixed(2)}s ago. Omitting segment and part directives.`),d=void 0,v=void 0;else if(null!=s&&s.tuneInGoal&&f-e.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${g} with playlist age: ${e.age}`),g=0;else{const t=Math.floor(g/e.targetduration);d+=t,void 0!==v&&(v+=Math.round(g%e.targetduration/e.partTarget)),this.log(`CDN Tune-in age: ${e.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${g} skip sn ${t} to part ${v}`)}e.tuneInGoal=g}if(c=this.getDeliveryDirectives(e,i.deliveryDirectives,d,v),t||!l)return e.requestScheduled=r,void this.loadingPlaylist(o,c)}else(e.canBlockReload||e.canSkipUntil)&&(c=this.getDeliveryDirectives(e,i.deliveryDirectives,d,v));c&&void 0!==d&&e.canBlockReload&&(e.requestScheduled=n.loading.first+Math.max(u-2*h,u/2)),this.scheduleLoading(o,c,e)}else this.clearTimer()}scheduleLoading(t,i,s){const e=s||t.details;if(!e)return void this.loadingPlaylist(t,i);const n=self.performance.now(),r=e.requestScheduled;if(n>=r)return void this.loadingPlaylist(t,i);const h=r-n;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(h)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(t,i)),h)}getDeliveryDirectives(t,i,s,e){let n=ii(t);return null!=i&&i.skip&&t.deltaUpdateFailed&&(s=i.msn,e=i.part,n=""),new si(s,e,n)}checkRetry(t){const i=t.details,s=bi(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(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=$i(h,r);this.clearTimer(),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}}function Rn(t,i){if(t.length!==i.length)return!1;for(let s=0;s<t.length;s++)if(!On(t[s].attrs,i[s].attrs))return!1;return!0}function On(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 Nn(t,i){return i.label.toLowerCase()===t.name.toLowerCase()&&(!i.language||i.language.toLowerCase()===(t.lang||"").toLowerCase())}class Un{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,i,s){if(null===this.queues||null===this.tracks)return;const e=this.queues[i];e.push(t),1!==e.length||s||this.executeNext(i)}appendBlocker(t){return new Promise((i=>{this.append({label:"async-blocker",execute:i,onStart:()=>{},onComplete:()=>{},onError:()=>{}},t)}))}prependBlocker(t){return new Promise((i=>{this.queues&&this.queues[t].unshift({label:"async-blocker-prepend",execute:i,onStart:()=>{},onComplete:()=>{},onError:()=>{}})}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t=>{var i;const s=null==(i=t[0])?void 0:i.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(t[0].execute(),t.splice(0,1))}))}unblockAudio(t){null!==this.queues&&this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];if(i.length){const e=i[0];try{e.execute()}catch(i){var s;if(e.onError(i),null===this.queues||null===this.tracks)return;const n=null==(s=this.tracks[t])?void 0:s.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var i;return(null==(i=this.queues)?void 0:i[t][0])||null}toString(){const{queues:t,tracks:i}=this;return null===t||null===i?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var i,s;return null!=(i=this.queues)&&i[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var i;const s=null==(i=this.tracks)?void 0:i[t],e=null==s?void 0:s.buffer;return e?`SourceBuffer${e.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var i;return(null==(i=this.queues)?void 0:i[t].map((t=>t.label)).join(", "))||""}}const Fn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Bn="HlsJsTrackRemovedError";class _n extends Error{constructor(t){super(t),this.name=Bn}}function jn(t){const i=t.querySelectorAll("source");[].slice.call(i).forEach((i=>{t.removeChild(i)}))}function Gn(t){return"audio"===t?1:0}class Hn{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(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.BUFFER_CODECS,this.onBufferCodecs,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.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&&f(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,i){this.hls.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}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.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),i.autoLevelCapping=s,i.autoLevelEnabled&&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,Hn.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 Math.min(t,this.hls.config.maxDevicePixelRatio)}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 Kn="m",Vn="a",Xn="v",Wn="av",zn="i",qn="tt",Yn="h",Qn="CMCD-Object",Jn="CMCD-Request",Zn="CMCD-Session",tr="CMCD-Status",ir={[Qn]:["br","d","ot","tb"],[Jn]:["bl","dl","mtp","nor","nrr","su"],[Zn]:["cid","pr","sf","sid","st","v"],[tr]:["bs","rtp"]};class sr{constructor(t,i){Array.isArray(t)&&(t=t.map((t=>t instanceof sr?t:new sr(t)))),this.value=t,this.params=i}}const er="Dict";function nr(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)}class rr{constructor(t){this.description=t}}const hr="Bare Item",or="Boolean",ar="Byte Sequence";const lr="Integer";function ur(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw nr(t,lr);return t.toString()}function cr(t,i){if(t<0)return-cr(-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}const dr="Decimal";function fr(t){const i=cr(t,3);if(Math.floor(Math.abs(i)).toString().length>12)throw nr(t,dr);const s=i.toString();return s.includes(".")?s:`${s}.0`}const vr="String",gr=/[\x00-\x1f\x7f]+/,pr="Token";function mr(t){const i=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw nr(i,pr);return i}function yr(t){switch(typeof t){case"number":if(!f(t))throw nr(t,hr);return Number.isInteger(t)?ur(t):fr(t);case"string":return function(t){if(gr.test(t))throw nr(t,vr);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return mr(t);case"boolean":return function(t){if("boolean"!=typeof t)throw nr(t,or);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${ur(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return function(t){if(!1===ArrayBuffer.isView(t))throw nr(t,ar);return`:${i=t,btoa(String.fromCharCode(...i))}:`;var i}(t);if(t instanceof rr)return mr(t);default:throw nr(t,hr)}}const br="Key";function wr(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw nr(t,br);return t}function $r(t){return null==t?"":Object.entries(t).map((([t,i])=>!0===i?`;${wr(t)}`:`;${wr(t)}=${yr(i)}`)).join("")}function kr(t){return t instanceof sr?`${yr(t.value)}${$r(t.params)}`:yr(t)}const Sr=t=>Math.round(t),Tr=t=>100*Sr(t/100),Er={br:Sr,d:Sr,bl:Tr,dl:Tr,mtp:Tr,nor:(t,i)=>((null==i?void 0: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:Tr,tb:Sr};function Ar(t,i={}){return t?function(t,i){return function(t,i={whitespace:!0}){if("object"!=typeof t)throw nr(t,er);const s=t instanceof Map?t.entries():Object.entries(t),e=(null==i?void 0:i.whitespace)?" ":"";return Array.from(s).map((([t,i])=>{i instanceof sr==0&&(i=new sr(i));let s=wr(t);var e;return!0===i.value?s+=$r(i.params):(s+="=",Array.isArray(i.value)?s+=`(${(e=i).value.map(kr).join(" ")})${$r(e.params)}`:s+=kr(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=x({},Er,null==i?void 0:i.formatters),r=null==i?void 0:i.filter;return e.forEach((e=>{if(null==r?void 0:r(e))return;let h=t[e];const o=n[e];o&&(h=o(h,i)),"v"===e&&1===h||"pr"==e&&1===h||function(t){return"number"==typeof t?f(t):null!=t&&""!==t&&!1!==t}(h)&&(function(t){return"ot"===t||"sf"===t||"st"===t}(e)&&"string"==typeof h&&(h=new rr(h)),s[e]=h)})),s}(t,i),x({whitespace:!1},i)):""}const Lr=/CMCD=[^&#]+/;function Mr(t,i,s,e){t&&Object.keys(i).forEach((n=>{const r=t.filter((t=>t.groupId===n)).map((t=>{const r=x({},t);return r.details=void 0,r.attrs=new Zi(r.attrs),r.url=r.attrs.URI=xr(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 xr(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}function Ir(t,i,s){Dr(t,i,s),t.addEventListener(i,s)}function Dr(t,i,s){t.removeEventListener(i,s)}class Pr extends P{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Pr.CDMCleanupPromise?[Pr.CDMCleanupPromise]:[],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=ps(this.config));const i=t.map(gs).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(i)}this.keyFormatPromise.then((n=>{const r=fs(n);let h,o;if("sinf"===i){if(r!==as.FAIRPLAY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${r}`);const n=ut(new Uint8Array(s));try{const t=St(rs(JSON.parse(n).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=new Uint8Array(t.subarray(8,24)),o=as.FAIRPLAY}catch(t){return void this.warn(`${e} Failed to parse sinf: ${t}`)}}else{if(r!==as.WIDEVINE&&r!==as.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=It(new DataView(t,e));i.push(s),e+=s.size}}return i}(s),a=n.filter((t=>!!t.systemId&&vs(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=>vs(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=vs(l.systemId),0===l.version&&l.data)if(o===as.WIDEVINE){const t=l.data.length-22;h=new Uint8Array(l.data.subarray(t,t+16))}else o===as.PLAYREADY&&(h=bs(l.data))}if(!o||!h)return;const a=G(h),{keyIdToKeySessionPromise:l,mediaKeySessions:u}=this;let c=l[a];for(let t=0;t<u.length;t++){const e=u[t],n=e.decryptdata;if(!n.keyId)continue;const r=G(n.keyId);if(a===r||-1!==n.uri.replace(/-/g,"").indexOf(a)){if(c=l[r],n.pssh)break;delete l[r],n.pssh=new Uint8Array(s),n.keyId=h,c=l[a]=c.then((()=>this.generateRequestWithPreferredKeySession(e,i,s,"encrypted-event-key-match"))),c.catch((t=>this.handleError(t)));break}}if(!c){if(o!==r)return void this.log(`Ignoring "${t.type}" event with ${o} init data for selected key-system ${r}`);c=l[a]=this.getKeySystemSelectionPromise([o]).then((({keySystem:t,mediaKeys:e})=>{var n;this.throwIfDestroyed();const r=new $s("ISO-23001-7",a,null!=(n=gs(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")}))})),c.catch((t=>this.handleError(t)))}}))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),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(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(y.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(y.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:i,widevineLicenseUrl:s}=this.config,e=i[t];return e?e.licenseUrl:t===as.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 Cr?i:new Cr({type:p.KEY_SYSTEM_ERROR,details:m.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===ms&&"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 as.FAIRPLAY:n=["cenc","sinf"];break;case as.WIDEVINE:case as.PLAYREADY:n=["cenc"];break;case as.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: ${ri(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((s=>(this.log(`Media-keys created for "${t}"`),i.hasMediaKeys=!0,e.then((i=>i?this.setMediaKeysServerCertificate(s,t,i):s))))),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: ${G(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.buffer,"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 G(t.keyId)}updateKeySession(t,i){var s;const e=t.mediaKeysSession;return this.log(`Updating key-session "${e.sessionId}" for keyID ${G((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${i?i.byteLength:i})`),e.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map((t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys}))).filter((({hasMediaKeys:t})=>!!t)).map((({keySystem:t})=>gs(t))).filter((t=>!!t))}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then((({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i)))}selectKeySystem(t){return new Promise(((i,s)=>this.getKeySystemSelectionPromise(t).then((({keySystem:t})=>{const e=gs(t);e?i(e):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)))}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){const i=ps(this.config),s=t.map(fs).filter((t=>!!t&&-1!==i.indexOf(t)));return this.selectKeySystem(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.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(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:n,decryptdata:i}))))))),(this.keyIdToKeySessionPromise[s]=n.then((t=>this.generateRequestWithPreferredKeySession(t,"cenc",i.pssh?i.pssh.buffer:null,"playlist-key")))).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(y.ERROR,t instanceof Cr?t.data:{type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const i=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[i];if(!s){const i=fs(t.keyFormat),s=i?[i]:ps(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=ps(this.config)),0===t.length)throw new Cr({type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ri({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,i){if(this.mediaKeys===i)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const e=Promise.all(s).then((()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(i)}));return this.mediaKeys=i,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,t.decryptdata.pssh=(s=e.initData?e.initData:null)?new Uint8Array(s):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 oe,u=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=>{l.eventNames().length?l.emit("error",t):this.handleError(t)})):"license-release"===e?t.keySystem===as.FAIRPLAY&&(this.updateKeySession(t,hs("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${e}"`)},c=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))};Ir(t.mediaKeysSession,"message",u),Ir(t.mediaKeysSession,"keystatuseschange",c);const d=new Promise(((t,i)=>{l.on("error",i),l.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?i(new Cr({type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?i(new Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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)=>{if("string"==typeof s&&"object"==typeof i){const t=s;s=i,i=t}this.log(`key status change "${i}" for keyStatuses keyId: ${G("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${G(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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:D({url:h.url,data:void 0},i)},`"${t}" certificate request failed (${e}). Status: ${i.code} (${i.text})`))},onTimeout:(i,s,n)=>{r(new Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 hs(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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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==as.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(i,s)),i.send(s)}))}))}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,i){if(!this.config.emeEnabled)return;const s=i.media;this.media=s,Ir(s,"encrypted",this.onMediaEncrypted),Ir(s,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media;t&&(Dr(t,"encrypted",this.onMediaEncrypted),Dr(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,$s.clearKeyUriToKeyIdMap();const e=s.length;Pr.CDMCleanupPromise=Promise.all(s.map((t=>this.removeSession(t))).concat(null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch((t=>{var i;this.log(`Could not clear media keys: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})})))).catch((t=>{var i;this.log(`Could not close sessions and clear media keys: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})})).then((()=>{e&&this.log("finished closing key sessions and clearing media keys")}))}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);e>-1&&this.mediaKeySessions.splice(e,1);const{drmSystemOptions:n}=this.config,r=function(t){var i;return"persistent-license"===t.sessionType||!(null==(i=t.sessionTypes)||!i.some((t=>"persistent-license"===t)))}(n)?new Promise(((t,s)=>{self.setTimeout((()=>s(new Error("MediaKeySession.remove() timeout"))),8e3),i.remove().then(t)})):Promise.resolve();return r.catch((t=>{var i;this.log(`Could not remove session: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})})).then((()=>i.close())).catch((t=>{var i;this.log(`Could not close session: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})}))}}}Pr.CDMCleanupPromise=void 0;class Cr 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}}function Rr(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 Or(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){F.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){F.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function Nr(t,i){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues)for(let s=t.cues.length;s--;)i&&t.cues[s].removeEventListener("enter",i),t.removeCue(t.cues[s]);"disabled"===s&&(t.mode=s)}function Ur(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,n=0,r=s;for(;n<=r;)if(e=Math.floor((r+n)/2),i<t[e].startTime)r=e-1;else{if(!(i>t[e].startTime&&n<s))return e;n=e+1}return t[n].startTime-i<i-t[r].startTime?n:r}(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 Fr(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}function Br(t){let i=5381,s=t.length;for(;s;)i=33*i^t.charCodeAt(--s);return(i>>>0).toString()}const _r=.025;let jr=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Gr(t,i,s){return`${t.identifier}-${s+1}-${Br(i)}`}class Hr{constructor(t,i){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=i,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var i;if(t>0&&t>=this.assetList.length)return!0;const s=this.playoutLimit;return!(t<=0||isNaN(s))&&(0===s||((null==(i=this.assetList[t])?void 0:i.startOffset)||0)>s)}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const i=this.dateRange.tagAnchor;if(i)return Kr(t,i)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const i=this.dateRange.startTime;return i-Kr(i,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,i=f(t)?t:this.duration;return this.cumulativeDuration+i}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const i=this.resumeAnchor;if(i)return Kr(t,i)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<_r))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let i;return i=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<i&&(i=t),i}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?jr.Range:jr.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Kr(t,i){return t-i.start<i.duration/2&&!(Math.abs(t-(i.start+i.duration))<_r)?i.start:i.start+i.duration}function Vr(t,i,s){const e=new self.URL(t,s);return"data:"!==e.protocol&&e.searchParams.set("_HLS_primary_id",i),e}function Xr(t,i){for(;null!=(s=t.assetList[++i])&&s.error;)var s;return i}function Wr(t){const i=t.timelineStart,s=t.duration||0;return`["${t.identifier}" ${i.toFixed(2)}-${(i+s).toFixed(2)}]`}class zr{constructor(t,i,s,e){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new t(i);this.interstitial=s,this.assetItem=e;let r=e.uri;try{r=Vr(r,i.primarySessionId).href}catch(t){}n.loadSource(r);const h=()=>{this.hasDetails=!0};n.once(y.LEVEL_LOADED,h),n.once(y.AUDIO_TRACK_LOADED,h),n.once(y.SUBTITLE_TRACK_LOADED,h),n.on(y.MEDIA_ATTACHING,((t,{media:i})=>{this.removeMediaListeners(),this.mediaAttached=i,this.interstitial.playoutLimit&&(i.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(y.BUFFER_APPENDED,(()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,n.trigger(y.BUFFERED_TO_END,void 0))})))}))}get appendInPlace(){var t;return(null==(t=this.interstitial)?void 0:t.appendInPlace)||!1}bufferedInPlaceToEnd(t){var i;if(!this.appendInPlace)return!1;if(null!=(i=this.hls)&&i.bufferedToEnd)return!0;if(!t||!this._bufferedEosTime)return!1;const s=Vi.bufferInfo(t,this.timelineOffset,0);return this.getAssetTime(s.end)>=this._bufferedEosTime-.02}reachedPlayout(t){return this.startOffset+t>=this.interstitial.playoutLimit}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const i=Vi.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(i.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){return this.assetItem.duration||0}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const i=this.timelineOffset;if(t!==i&&Math.abs(t-i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}getAssetTime(t){const i=this.duration;return Math.min(Math.max(0,t-this.timelineOffset),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){this.hls.attachMedia(t)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}resetDetails(){const t=this.hls;if(this.hasDetails){t.stopLoad();const i=t=>delete t.details;t.levels.forEach(i),t.allAudioTracks.forEach(i),t.allSubtitleTracks.forEach(i),this.hasDetails=!1}}on(t,i,s){this.hls.on(t,i)}once(t,i,s){this.hls.once(t,i)}off(t,i,s){this.hls.off(t,i)}toString(){var t;return`HlsAssetPlayer: ${Wr(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class qr extends P{constructor(t,i){super("interstitials-sched",i),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((t=>t.reset())),this.events=this.items=null}resetErrorsInRange(t,i){return this.events?this.events.reduce(((s,e)=>t<=e.startOffset&&i>e.startOffset?(delete e.error,s+1):s),0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,i){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const e=this.items;if(e)for(e[s]||(void 0===i&&(i=t.start),s=this.findItemIndexAtTime(i));s>=0&&null!=(n=e[s])&&n.event;){var n;s--}return s}findItemIndexAtTime(t,i){const s=this.items;if(s)for(let e=0;e<s.length;e++){let n=s[e];if(i&&"primary"!==i&&(n=n[i]),t===n.start||t>n.start&&t<n.end)return e}return-1}findJumpRestrictedIndex(t,i){const s=this.items;if(s)for(let e=t;e<=i&&s[e];e++){const t=s[e].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return e}return-1}findEventIndex(t){const i=this.items;if(i)for(let e=i.length;e--;){var s;if((null==(s=i[e].event)?void 0:s.identifier)===t)return e}return-1}findAssetIndex(t,i){const s=t.assetList,e=s.length;if(e>1)for(let t=0;t<e;t++){const e=s[t];if(!e.error){const s=e.timelineStart;if(i===s||i>s&&i<s+(e.duration||0))return t}}return 0}get assetIdAtEnd(){var t,i;const s=null==(t=this.items)||null==(i=t[this.length-1])?void 0:i.event;if(s){const t=s.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,i){const s=t.main.details,{dateRanges:e}=s,n=this.events,r=this.parseDateRanges(e,{url:s.url},i),h=Object.keys(e),o=n?n.filter((t=>!h.includes(t.identifier))):[];r.length&&r.sort(((t,i)=>{const s=t.cue.pre,e=t.cue.post,n=i.cue.pre,r=i.cue.post;if(s&&!n)return-1;if(n&&!s)return 1;if(e&&!r)return 1;if(r&&!e)return-1;if(!(s||n||e||r)){const s=t.startTime,e=i.startTime;if(s!==e)return s-e}return t.dateRange.tagOrder-i.dateRange.tagOrder})),this.events=r,o.forEach((t=>{this.removeEvent(t)})),this.updateSchedule(t,o)}updateSchedule(t,i=[]){const s=this.events||[];if(s.length||i.length||this.length<2){const e=this.items,n=this.parseSchedule(s,t);(i.length||(null==e?void 0:e.length)!==n.length||n.some(((t,i)=>Math.abs(t.playout.start-e[i].playout.start)>.005||Math.abs(t.playout.end-e[i].playout.end)>.005)))&&(this.items=n,this.onScheduleUpdate(i,e))}}parseDateRanges(t,i,s){const e=[],n=Object.keys(t);for(let r=0;r<n.length;r++){const h=n[r],o=t[h];if(o.isInterstitial){let t=this.eventMap[h];t?t.setDateRange(o):(t=new Hr(o,i),this.eventMap[h]=t,!1===s&&(t.appendInPlace=s)),e.push(t)}}return e}parseSchedule(t,i){const s=[],e=i.main.details,n=e.live?1/0:e.edge;let r=0;if((t=t.filter((t=>!(t.error||t.cue.once&&t.hasPlayed)))).length){this.resolveOffsets(t,i);let e=0,o=0;if(t.forEach(((i,h)=>{const a=i.cue.post,l=t[h-1]||null,u=a?n:i.startOffset,c=i.duration,d=i.timelineOccupancy===jr.Range?c:0,f=(null==l?void 0:l.startTime)===u,v=u+i.cumulativeDuration;let g=i.appendInPlace?v+c:u+i.resumptionOffset;if(i.cue.pre||!a&&u<=0){const t=o;o+=d,i.timelineStart=v;const e=r;r+=c,s.push({event:i,start:v,end:g,playout:{start:e,end:r},integrated:{start:t,end:o}})}else{if(!(u<=n))return;{if(!f){const n=u-e;if(n>.033){const a=o;o+=n;const l=r;r+=n,s.push({previousEvent:t[h-1]||null,nextEvent:i,start:e,end:e+n,playout:{start:l,end:r},integrated:{start:a,end:o}})}else n>0&&l&&(l.cumulativeDuration+=n,s[s.length-1].end=u)}a&&(g=v),i.timelineStart=v;const n=o;o+=d;const p=r;r+=c,s.push({event:i,start:v,end:g,playout:{start:p,end:r},integrated:{start:n,end:o}})}}const p=i.resumeTime;e=a||p>n?n:p})),e<n){var h;const t=o,i=n-e;o+=i;const a=r;r+=i,s.push({previousEvent:(null==(h=s[s.length-1])?void 0:h.event)||null,nextEvent:null,start:e,end:e+i,playout:{start:a,end:r},integrated:{start:t,end:o}})}this.setDurations(n,r,o)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:n,playout:{start:t,end:n},integrated:{start:t,end:n}}),this.setDurations(n,n,n)}return s}setDurations(t,i,s){this.durations={primary:t,playout:i,integrated:s}}resolveOffsets(t,i){const s=i.main.details,e=s.live?1/0:s.edge;let n=0,r=-1;t.forEach(((h,o)=>{const a=h.cue.post,l=h.cue.pre?0:a?e:h.startTime;this.updateAssetDurations(h),r===l?h.cumulativeDuration=n:(n=0,r=l),!a&&h.snapOptions.in&&(h.resumeAnchor=gi(null,s.fragments,h.startOffset+h.resumptionOffset,0,0)||void 0),h.appendInPlace&&!h.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(h,i)||(h.appendInPlace=!1)),!h.appendInPlace&&o+1<t.length&&t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${h}`));const u=f(h.resumeOffset)?h.resumeOffset:h.duration;n+=u}))}primaryCanResumeInPlaceAt(t,i){const s=t.resumeTime,e=t.startTime+t.resumptionOffset;return Math.abs(s-e)>_r?(this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${e}`),!1):i?!Object.keys(i).some((e=>{const n=i[e].details,r=n.edge;if(s>=r)return this.log(`"${t.identifier}" resumption ${s} past ${e} playlist end ${r}`),!1;const h=gi(null,n.fragments,s);if(!h)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${e} playlist (${n.fragStart}-${n.fragmentEnd})`),!0;const o="audio"===e?.175:0;return!(Math.abs(h.start-s)<_r+o||Math.abs(h.end-s)<_r+o||(this.log(`"${t.identifier}" resumption ${s} not aligned with ${e} fragment bounds (${h.start}-${h.end} sn: ${h.sn} cc: ${h.cc})`),0))})):(this.log(`"${t.identifier}" resumption ${s} can not be aligned with media (none selected)`),!1)}updateAssetDurations(t){if(!t.assetListLoaded)return;const i=t.timelineStart;let s=0,e=!1,n=!1;t.assetList.forEach((t=>{const r=i+s;t.startOffset=s,t.timelineStart=r,e||(e=null===t.duration),n||(n=!!t.error),s+=t.error?0:t.duration||0})),t.duration=e&&!n?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function Yr(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Qr{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,i){const s=t.assetListUrl;let e;try{e=Vr(s,this.hls.sessionId,t.baseUrl)}catch(i){const e=this.assignAssetListError(t,m.ASSET_LIST_LOAD_ERROR,i,s);return void this.hls.trigger(y.ERROR,e)}i&&"data:"!==e.protocol&&e.searchParams.set("_HLS_start_offset",""+i);const n=this.hls.config,r=new(0,n.loader)(n),h=n.interstitialAssetListLoadPolicy.default;return r.load({responseType:"json",url:e.href},{loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},{onSuccess:(i,s,e,n)=>{const r=i.data;if(Array.isArray(null==r?void 0:r.ASSETS))t.assetListResponse=r,this.hls.trigger(y.ASSET_LIST_LOADED,{event:t,assetListResponse:r,networkDetails:n});else{const i=this.assignAssetListError(t,m.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),e.url,s,n);this.hls.trigger(y.ERROR,i)}},onError:(i,s,e,n)=>{const r=this.assignAssetListError(t,m.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${i.code} ${i.text} (${s.url})`),s.url,n,e);this.hls.trigger(y.ERROR,r)},onTimeout:(i,s,e)=>{const n=this.assignAssetListError(t,m.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,i,e);this.hls.trigger(y.ERROR,n)}}),this.hls.trigger(y.ASSET_LIST_LOADING,{event:t}),r}assignAssetListError(t,i,s,e,n,r){return t.error=s,{type:p.NETWORK_ERROR,details:i,fatal:!1,interstitial:t,url:e,error:s,networkDetails:r,stats:n}}}function Jr(t){null==t||t.play().catch((()=>{}))}class Zr{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)}}}const th={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},ih=t=>String.fromCharCode(th[t]||t),sh=15,eh=100,nh={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rh={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hh={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},oh={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ah=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class lh{constructor(){this.time=null,this.verboseLevel=0}log(t,i){if(this.verboseLevel>=t){const s="function"==typeof i?i():i;F.log(`${this.time} [${t}] ${s}`)}}}const uh=function(t){const i=[];for(let s=0;s<t.length;s++)i.push(t[s].toString(16));return i};class ch{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 dh{constructor(){this.uchar=" ",this.penState=new ch}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 fh{constructor(t){this.chars=[],this.pos=0,this.currPenState=new ch,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<eh;t++)this.chars.push(new dh);this.logger=t}equals(t){for(let i=0;i<eh;i++)if(!this.chars[i].equals(t.chars[i]))return!1;return!0}copy(t){for(let i=0;i<eh;i++)this.chars[i].copy(t.chars[i])}isEmpty(){let t=!0;for(let i=0;i<eh;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>eh&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=eh)}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=ih(t);this.pos>=eh?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<eh;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<eh;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 vh{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let i=0;i<sh;i++)this.rows.push(new fh(t));this.logger=t}reset(){for(let t=0;t<sh;t++)this.rows[t].clear();this.currRow=14}equals(t){let i=!0;for(let s=0;s<sh;s++)if(!this.rows[s].equals(t.rows[s])){i=!1;break}return i}copy(t){for(let i=0;i<sh;i++)this.rows[i].copy(t.rows[i])}isEmpty(){let t=!0;for(let i=0;i<sh;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 = "+ri(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<sh;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 = "+ri(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<sh;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 gh{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 vh(s),this.nonDisplayedMemory=new vh(s),this.lastOutputScreen=new vh(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: "+ri(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 ph{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 lh;this.channels=[null,new gh(t,i,e),new gh(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,(()=>"["+uh([i[t],i[t+1]])+"] -> ("+uh([s,e])+")"));const h=this.cmdHistory;if(s>=16&&s<=31){if(yh(s,e,h)){mh(null,null,h),this.logger.log(3,(()=>"Repeated command ("+uh([s,e])+") is dropped"));continue}mh(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 mh(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 "+uh([s,e])+" orig: "+uh([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 ("+uh([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?nh[t]:hh[t]:1===e?rh[t]:oh[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 '"+ih(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 = "+uh(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=ah[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()}mh(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 mh(t,i,s){s.a=t,s.b=i}function yh(t,i,s){return s.a===t&&s.b===i}var bh=function(){if(null!=os&&os.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="",u=!1,c=i,d=r,f=h,v=null,g="",p=!0,m="auto",y="start",b=50,w="middle",$=50,k="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 u},set:function(t){u=!!t}})),Object.defineProperty(o,"startTime",n({},a,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=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 g},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.");g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},a,{get:function(){return p},set:function(t){p=!!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 b},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");b=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},a,{get:function(){return w},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");w=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},a,{get:function(){return $},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");$=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},a,{get:function(){return k},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");k=i,this.hasBeenReset=!0}})),o.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class wh{decode(t,i){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function $h(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 kh{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 Sh(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 Th=new bh(0,0,""),Eh="middle"===Th.align?"middle":"center";function Ah(t,i,s){const e=t;function n(){const i=$h(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 kh;Sh(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",Eh,"end"]);break;case"position":n=i.split(","),e.percent(t,n[0]),2===n.length&&e.alt("positionAlign",n[1],["start",Eh,"end","line-left","line-right","auto"]);break;case"size":e.percent(t,i);break;case"align":e.alt(t,i,["start",Eh,"end","left","right"])}}),/:/,/\s/),i.region=e.get("region",null),i.vertical=e.get("vertical","");let n=e.get("line","auto");"auto"===n&&-1===Th.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",Eh);let r=e.get("position","auto");"auto"===r&&50===Th.position&&(r="start"===i.align||"left"===i.align?0:"end"===i.align||"right"===i.align?100:50),i.position=r}(t,i)}function Lh(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class Mh{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new wh,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=Lh(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)?Sh(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 bh(0,0,""),i.state="CUE",-1===t.indexOf("--\x3e")){i.cue.id=t;continue}case"CUE":if(!i.cue){i.state="BADCUE";continue}try{Ah(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 xh=/\r\n|\n\r|\n|\r/g,Ih=function(t,i,s=0){return t.slice(s,s+i.length)===i};function Dh(t,i,s){return Br(t.toString())+Br(i.toString())+Br(s)}const Ph="stpp.ttml.im1t",Ch=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rh=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oh={left:"start",center:"center",right:"end",start:"start",end:"end"};function Nh(t,i,s,e){const n=gt(new Uint8Array(t),["mdat"]);if(0===n.length)return void e(new Error("Could not parse IMSC1 mdat"));const r=n.map((t=>j(t))),h=function(t,i,s=1,e=!1){return fn(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=Fh(Uh(s,"styling","style")),o=Fh(Uh(s,"layout","region")),a=Uh(s,"body","[begin]");return[].map.call(a,(t=>{const s=Bh(t,r);if(!s||!t.hasAttribute("begin"))return null;const e=Gh(t.getAttribute("begin"),n),a=Gh(t.getAttribute("dur"),n);let l=Gh(t.getAttribute("end"),n);if(null===e)throw jh(t);if(null===l){if(null===a)throw jh(t);l=e+a}const u=new bh(e-i,l-i,s);u.id=Dh(u.startTime,u.endTime,u.text);const c=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=_h(i,e,r)||_h(t,e,r)||_h(n,e,r);return h&&(s[r]=h),s}),{})}(o[t.getAttribute("region")],h[t.getAttribute("style")],h),{textAlign:d}=c;if(d){const t=Oh[d];t&&(u.lineAlign=t),u.align=d}return x(u,c),u})).filter((t=>null!==t))}(t,h))))}catch(t){e(t)}}function Uh(t,i,s){const e=t.getElementsByTagName(i)[0];return e?[].slice.call(e.querySelectorAll(s)):[]}function Fh(t){return t.reduce(((t,i)=>{const s=i.getAttribute("xml:id");return s&&(t[s]=i),t}),{})}function Bh(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?Bh(s,i):i?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function _h(t,i,s){return t&&t.hasAttributeNS(i,s)?t.getAttributeNS(i,s):null}function jh(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Gh(t,i){if(!t)return null;let s=$h(t);return null===s&&(Ch.test(t)?s=function(t,i){const s=Ch.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):Rh.test(t)&&(s=function(t,i){const s=Rh.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}class Hh{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}}function Kh(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Vh(t,i){return!!t&&t.kind===Kh(i)&&Nn(i,t)}const Xh=/\s/,Wh={newCue(t,i,s,e){const n=[];let r,h,o,a,l;const u=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 c;for(let t=0;t<r.chars.length;t++)Xh.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=Lh(l.trim()),f=Dh(i,s,e);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(h=new u(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=>Or(t,i)))),n}},zh=/(\d+)-(\d+)\/(\d+)/;class qh{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||Yh,this.controller=new self.AbortController,this.stats=new J}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(x({},t.headers))};return t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),s}(t,this.controller.signal),r="arraybuffer"===t.responseType,h=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:a}=i.loadPolicy;this.context=t,this.config=i,this.callbacks=s,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),i.timeout=o&&f(o)?o:a,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(e,t,this.response))}),i.timeout),(Mn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var n;this.response=this.loader=s;const h=Math.max(self.performance.now(),e.loading.start);if(self.clearTimeout(this.requestTimeout),i.timeout=a,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(e,t,this.response))}),a-(h-e.loading.start)),!s.ok){const{status:t,statusText:i}=s;throw new Qh(i||"fetch, bad network response",t,s)}e.loading.first=h,e.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const i=zh.exec(t);if(i)return parseInt(i[2])-parseInt(i[1])+1}(i);if(f(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(s.headers)||e.total;const o=null==(n=this.callbacks)?void 0:n.onProgress;return o&&f(i.highWaterMark)?this.loadProgressively(s,e,t,i.highWaterMark,o):r?s.arrayBuffer():"json"===t.responseType?s.json():s.text()})).then((s=>{var n,r;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),e.loading.end=Math.max(self.performance.now(),e.loading.first);const a=s[h];a&&(e.loaded=e.total=a);const l={url:o.url,data:s,code:o.status},u=null==(n=this.callbacks)?void 0:n.onProgress;u&&!f(i.highWaterMark)&&u(e,t,s,o),null==(r=this.callbacks)||r.onSuccess(l,e,t,o)})).catch((i=>{var s;self.clearTimeout(this.requestTimeout),e.aborted||null==(s=this.callbacks)||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 ee,h=t.body.getReader(),o=()=>h.read().then((h=>{if(h.done)return r.dataLength&&n(i,s,r.flush().buffer,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().buffer,t)):n(i,s,a.buffer,t),o()})).catch((()=>Promise.reject()));return o()}}function Yh(t,i){return new self.Request(t.url,i)}class Qh extends Error{constructor(t,i,s){super(t),this.code=void 0,this.details=void 0,this.code=i,this.details=s}}const Jh=/^age:\s*[\d.]+\s*$/im;class Zh{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 J,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=>{var n;null==(n=this.callbacks)||n.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&&f(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,a="text"===i.responseType?i.responseText:null;if(e>=200&&e<300){const n=null!=a?a:i.response;if(null!=n){var r,h;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);const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&o(s,t,n,i),void(null==(h=this.callbacks)||h.onSuccess({url:i.responseURL,data:n,code:e},s,t,i))}}const l=n.loadPolicy.errorRetry;var o;Si(l,s.retry,!1,{url:t.url,data:void 0,code:e})?this.retry(l):(F.error(`${e} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:e,text:i.statusText},t,i,s))}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Si(t,this.stats.retry,!0))this.retry(t);else{var i;F.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=$i(t,s.retry),s.retry++,F.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&&Jh.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 to=D(D({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:Zh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends P{constructor(t){super("abr",t.logger),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.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:e,hls:n}=this,{autoLevelEnabled:r,media:h}=n;if(!s||!h)return;const o=performance.now(),a=e?e.stats:s.stats,l=e?e.duration:s.duration,u=o-a.loading.start,c=n.minAutoLevel,d=s.level,v=this._nextAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||d<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r)return;const g=v>-1&&v!==d,p=!!t||g;if(!p&&(h.paused||!h.playbackRate||!h.readyState))return;const m=n.mainForwardBufferInfo;if(!p&&null===m)return;const b=this.bwEstimator.getEstimateTTFB(),w=Math.abs(h.playbackRate);if(u<=Math.max(b,l/(2*w)*1e3))return;const $=m?m.len/w:0,k=a.loading.first?a.loading.first-a.loading.start:-1,S=a.loaded&&k>-1,T=this.getBwEstimate(),E=n.levels,A=Math.max(a.loaded,Math.round(l*(s.bitrate||E[d].averageBitrate)/8));let L=S?u-k:u;L<1&&S&&(L=Math.min(u,8*a.loaded/T));const M=S?1e3*a.loaded/L:0,x=b/1e3,I=M?(A-a.loaded)/M:8*A/T+x;if(I<=$)return;const D=M?8*M:T,P=!0===(null==(i=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:i.live),C=this.hls.config.abrBandWidthUpFactor;let R,O=Number.POSITIVE_INFINITY;for(R=d-1;R>c&&(O=this.getTimeToLoadFrag(x,D,l*E[R].maxBitrate,!E[R].details||P),!(O<Math.min($,l+x)));R--);if(O>=I)return;if(O>10*l)return;S?this.bwEstimator.sample(u-Math.min(b,k),a.loaded):this.bwEstimator.sampleTTFB(u);const N=E[R].maxBitrate;this.getBwEstimate()*C>N&&this.resetEstimator(N);const U=this.findBestLevel(N,c,R,0,$,1,1);U>-1&&(R=U),this.warn(`Fragment ${s.sn}${e?" part "+e.index:""} of level ${d} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${$.toFixed(3)} s\n Estimated load time for current fragment: ${I.toFixed(3)} s\n Estimated load time for down switch fragment: ${O.toFixed(3)} s\n TTFB estimate: ${0|k} ms\n Current BW estimate: ${f(T)?0|T:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${R} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=R,this.clearTimer();const F=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===R&&R>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${R>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,R>c){let i=this.findBestLevel(this.hls.levels[c].bitrate,c,R,0,t,1,1);-1===i&&(i=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=i,this.resetEstimator(this.hls.levels[i].bitrate)}}};g||I>2*O?F():this.timer=self.setInterval(F,1e3*O),n.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.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 L(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.FRAG_LOADING,this.onFragLoading,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.FRAG_LOADING,this.onFragLoading,this),t.off(y.FRAG_LOADED,this.onFragLoaded,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,i){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},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 m.BUFFER_ADD_CODEC_ERROR:case m.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case m.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?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:e}=i.stats,n=e.end-e.first;f(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(i.levelInfo)}onFragLoaded(t,{frag:i,part:s}){const e=s?s.stats:i.stats;if(i.type===S&&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(y.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!==S||"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 this.warn(`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;if(s.levels.length<=1)return s.loadLevel;const{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,u=n.abrBandWidthUpFactor;if(a){const t=this.findBestLevel(o,r,e,a,0,l,u);if(t>=0)return this.rebufferNotice=-1,t}let c=h?Math.min(h,n.maxStarvationDelay):n.maxStarvationDelay;if(!a){const t=this.bitrateTestDelay;t&&(c=(h?Math.min(h,n.maxLoadingDelay):n.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),l=u=1)}const d=this.findBestLevel(o,r,e,a,c,l,u);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${a?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=s.levels[r],v=s.loadLevelObj;return v&&(null==f?void 0:f.bitrate)<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,u=-1===l?this.hls.firstLevel:l,{fragCurrent:c,partCurrent:d}=this,{levels:v,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===v.length)return 0;const y=v[u],b=!(null==(o=this.hls.latestLevelDetails)||!o.live),w=-1===p||-1===l;let $,k="SDR",S=(null==y?void 0:y.frameRate)||0;const{audioPreference:T,videoPreference:E}=m,A=this.audioTracksByGroup||(this.audioTracksByGroup=oi(g));let L=-1;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,e)=>{if(!s.codecSet)return t;const n=s.audioGroups;let r=t[s.codecSet];r||(t[s.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:e,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,s.bitrate);const h=Math.min(s.height,s.width);return r.minHeight=Math.min(r.minHeight,h),r.minFramerate=Math.min(r.minFramerate,s.frameRate),r.minIndex=Math.min(r.minIndex,e),r.maxScore=Math.max(r.maxScore,s.score),r.fragmentError+=s.fragmentError,r.videoRanges[s.videoRange]=(r.videoRanges[s.videoRange]||0)+1,n&&n.forEach((t=>{if(!t)return;const s=i.groups[t];s&&(r.hasDefaultAudio=r.hasDefaultAudio||i.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!i.hasDefaultAudio&&!i.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{r.channels[t]=(r.channels[t]||0)+s.channels[t]})))})),t}),{})}(v,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=null==n?void 0:n.videoCodec,l=h&&2===parseInt(h);let u=!1,c=!1,d=1/0,v=1/0,g=1/0,p=1/0,m=0,y=[];const{preferHDR:b,allowedVideoRanges:w}=function(t,i){let s=!1,e=[];if(t&&(s="SDR"!==t,e=[t]),i){e=i.allowedVideoRanges||ti.slice(0);const t="SDR"!==e.join("")&&!i.videoCodec;s=void 0!==i.preferHDR?i.preferHDR:t&&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}(),s||(e=["SDR"])}return{preferHDR:s,allowedVideoRanges:e}}(i,n);for(let i=r.length;i--;){const s=t[r[i]];u||(u=s.channels[2]>0),d=Math.min(d,s.minHeight),v=Math.min(v,s.minFramerate),g=Math.min(g,s.minBitrate),w.filter((t=>s.videoRanges[t]>0)).length>0&&(c=!0)}d=f(d)?d:0,v=f(v)?v:0;const $=Math.max(1080,d),k=Math.max(30,v);g=f(g)?g:s,s=Math.max(g,s),c||(i=void 0);const S=r.length>1;return{codecSet:r.reduce(((i,e)=>{const n=t[e];if(e===i)return i;if(y=c?w.filter((t=>n.videoRanges[t]>0)):[],S){if(n.minBitrate>s)return hi(e,`min bitrate of ${n.minBitrate} > current estimate of ${s}`),i;if(!n.hasDefaultAudio)return hi(e,"no renditions with default or auto-select sound found"),i;if(o&&e.indexOf(o.substring(0,4))%5!=0)return hi(e,`audio codec preference "${o}" not found`),i;if(h&&!l){if(!n.channels[h])return hi(e,`no renditions with ${h} channel sound found (channels options: ${Object.keys(n.channels)})`),i}else if((!o||l)&&u&&0===n.channels[2])return hi(e,"no renditions with stereo sound found"),i;if(n.minHeight>$)return hi(e,`min resolution of ${n.minHeight} > maximum of ${$}`),i;if(n.minFramerate>k)return hi(e,`min framerate of ${n.minFramerate} > maximum of ${k}`),i;if(!y.some((t=>n.videoRanges[t]>0)))return hi(e,`no variants with VIDEO-RANGE of ${ri(y)} found`),i;if(a&&e.indexOf(a.substring(0,4))%5!=0)return hi(e,`video codec preference "${a}" not found`),i;if(n.maxScore<m)return hi(e,`max score of ${n.maxScore} < selected max of ${m}`),i}return i&&(Ft(e)>=Ft(i)||n.fragmentError>t[i].fragmentError)?i:(p=n.minIndex,m=n.maxScore,e)}),void 0),videoRanges:y,preferHDR:b,minFramerate:v,minBitrate:g,minIndex:p}}(e,k,t,T,E),{codecSet:r,videoRanges:h,minFramerate:o,minBitrate:a,minIndex:l,preferHDR:u}=n;L=l,$=r,k=u?h[h.length-1]:h[0],S=o,t=Math.max(t,a),this.log(`picked start tier ${ri(n)}`)}else $=null==y?void 0:y.codecSet,k=null==y?void 0:y.videoRange;const M=d?d.duration:c?c.duration:0,x=this.bwEstimator.getEstimateTTFB()/1e3,I=[];for(let o=s;o>=i;o--){var D,P;const i=v[o],c=o>u;if(!i)continue;if(m.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&qt(i,A,k,S,t,T)?(i.supportedPromise=Yt(i,A,s,this.supportedCache),i.supportedPromise.then((t=>{if(!this.hls)return;i.supportedResult=t;const s=this.hls.levels,e=s.indexOf(i);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${e} ${ri(t)}`):t.supported?t.decodingInfoResults.some((t=>!1===t.smooth||!1===t.powerEfficient))&&this.log(`MediaCapabilities decodingInfo for level ${e} not smooth or powerEfficient: ${ri(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${e} ${ri(t)}`),e>-1&&s.length>1&&(this.log(`Removing unsupported level ${e}`),this.hls.removeLevel(e),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):i.supportedResult=Wt}if(($&&i.codecSet!==$||k&&i.videoRange!==k||c&&S>i.frameRate||!c&&S>0&&S<i.frameRate||null!=(D=i.supportedResult)&&null!=(P=D.decodingInfoResults)&&P.some((t=>!1===t.smooth)))&&(!w||o!==L)){I.push(o);continue}const g=i.details,y=(d?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||M;let E;E=c?h*t:r*t;const C=M&&e>=2*M&&0===n?i.averageBitrate:i.maxBitrate,R=this.getTimeToLoadFrag(x,E,C*y,void 0===g);if(E>=C&&(o===l||0===i.loadError&&0===i.fragmentError)&&(R<=x||!f(R)||b&&!this.bitrateTestDelay||R<a)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(I.length&&this.trace(`Skipped level(s) ${I.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${v[I[0]].codecs}" ${v[I[0]].videoRange}; not compatible with "${$}" ${k}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(E)})-bitrate=${Math.round(E-C)} ttfb:${x.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${a.toFixed(1)} fetchDuration:${R.toFixed(1)} firstSelection:${w} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${p}`)),w&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const i=this.deriveNextAutoLevel(t);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}deriveNextAutoLevel(t){const{maxAutoLevel:i,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),i)}},bufferController:class extends P{constructor(t,i){var s;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=()=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=()=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:i,mediaSource:s}=this;t&&this.log("Media source opened"),i&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:i,mediaSource:s}),null!==this.mediaSource&&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&&this.error(`Media element src was set while attaching MediaSource (${i} > ${t})`)},this.hls=t,this.fragmentTracker=i,this.appendSource=(s=B(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.BUFFER_RESET,this.onBufferReset,this),t.on(y.BUFFER_APPENDING,this.onBufferAppending,this),t.on(y.BUFFER_CODECS,this.onBufferCodecs,this),t.on(y.BUFFER_EOS,this.onBufferEos,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.FRAG_PARSED,this.onFragParsed,this),t.on(y.FRAG_CHANGED,this.onFragChanged,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.BUFFER_RESET,this.onBufferReset,this),t.off(y.BUFFER_APPENDING,this.onBufferAppending,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.BUFFER_EOS,this.onBufferEos,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.FRAG_PARSED,this.onFragParsed,this),t.off(y.FRAG_CHANGED,this.onFragChanged,this),t.off(y.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:i}=this;if(!t)return null;const s={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const i=this.isQueued();(t||i)&&this.warn(`Transfering MediaSource with${i?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const e=this.transferData;return!this.sourceBufferCount&&e&&e.mediaSource===i?x(s,e.tracks):this.sourceBuffers.forEach((t=>{const[i]=t;i&&(s[i]=x({},this.tracks[i]),this.removeBuffer(i)),t[0]=t[1]=null})),{media:t,mediaSource:i,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,i){var s;let e=2;(i.audio&&!i.video||!i.altAudio)&&(e=1),this.bufferCodecEventsTotal=e,this.log(`${e} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&e&&this.bufferCreated()}onMediaAttaching(t,i){const s=this.media=i.media,e=B(this.appendSource);if(this.transferData=this.overrides=void 0,s&&e){const t=!!i.mediaSource;(t||i.overrides)&&(this.transferData=i,this.overrides=i.overrides);const n=this.mediaSource=i.mediaSource||new e;if(this.assignMediaSource(n),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const i=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||i&&n instanceof i,jn(s),function(t,i){const s=self.document.createElement("source");s.type="video/mp4",s.src=i,t.appendChild(s)}(s,t),s.load()}catch(i){s.src=t}else s.src=t}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var i,s;this.log(`${(null==(i=this.transferData)?void 0:i.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.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))}attachTransferred(){const t=this.media,i=this.transferData;if(!i||!t)return;const s=this.tracks,e=i.tracks,n=e?Object.keys(e):null,r=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(e&&n&&n&&n.length){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${ri(s,((t,i)=>"initSegment"===t?void 0:i))};\ntransfer tracks: ${ri(e,((t,i)=>"initSegment"===t?void 0:i))}}`),!_(e,s)){i.mediaSource=null,i.tracks=void 0;const n=t.currentTime,r=this.details,h=Math.max(n,(null==r?void 0:r.fragments[0].start)||0);return h-n>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${n} -> ${h}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(e)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${n}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,i),void(t.currentTime=h))}this.transferData=void 0,n.forEach((t=>{const i=t,s=e[i];if(s){const t=s.buffer;if(t){const e=this.fragmentTracker,n=s.id;if(e.hasFragments(n)||e.hasParts(n)){const s=Vi.getBuffered(t);e.detectEvictedFragments(i,s,n,null,!0)}const r=Gn(i);this.sourceBuffers[r]=[i,t],t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(i),this.trackSourceBuffer(i,s)}}})),r(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),r()}get mediaSourceOpenOrEnded(){var t;const i=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===i||"ended"===i}onMediaDetaching(t,i){const s=!!i.transferMedia;this.transferData=this.overrides=void 0;const{media:e,mediaSource:n,_objectUrl:r}=this;if(n){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach((([t])=>{t&&this.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===n.readyState;try{const i=n.sourceBuffers;for(let s=i.length;s--;)t&&i[s].abort(),n.removeSourceBuffer(i[s]);t&&n.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}e&&(e.removeEventListener("emptied",this._onMediaEmptied),s||(r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(e.removeAttribute("src"),this.appendSource&&jn(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(y.MEDIA_DETACHED,i)}onBufferReset(){this.sourceBuffers.forEach((([t])=>{t&&this.resetBuffer(t)})),this.initTracks()}resetBuffer(t){var i;const s=null==(i=this.tracks[t])?void 0:i.buffer;if(this.removeBuffer(t),s)try{var e;null!=(e=this.mediaSource)&&e.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Gn(t)]=[null,null];const i=this.tracks[t];i&&(i.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Un(this.tracks)}onBufferCodecs(t,i){const s=this.tracks,e=Object.keys(i);this.log(`BUFFER_CODECS: "${e}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in i&&(s.audio||s.video)||s.audiovideo&&("audio"in i||"video"in i),r=!n&&this.sourceBufferCount&&this.media&&e.some((t=>!s[t]));n||r?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${e}" SourceBuffers`):(e.forEach((t=>{var e,n,r;const h=i[t],{id:o,codec:a,levelCodec:l,container:u,metadata:c,supplemental:d}=h;let f=s[t];const v=null==(e=this.transferData)||null==(n=e.tracks)?void 0:n[t],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;f||(f=s[t]={buffer:void 0,listeners:[],codec:a,supplemental:d,container:u,levelCodec:l,metadata:c,id:o});const y=Gt(p,m),b=null==y?void 0:y.replace(Fn,"$1");let w=Gt(a,l);const $=null==(r=w)?void 0:r.replace(Fn,"$1");w&&y&&b!==$&&("audio"===t.slice(0,5)&&(w=jt(w,this.appendSource)),this.log(`switching codec ${p} to ${w}`),w!==(f.pendingCodec||f.codec)&&(f.pendingCodec=w),f.container=u,this.appendChangeType(t,u,w))})),(this.tracksReady||this.sourceBufferCount)&&(i.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((t,i)=>{const s=this.tracks[i];return t[i]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t}),{})}appendChangeType(t,i,s){const e=`${i};codecs=${s}`;this.append({label:`change-type=${e}`,execute:()=>{const n=this.tracks[t];if(n){const r=n.buffer;null!=r&&r.changeType&&(this.log(`changing ${t} sourceBuffer type to ${e}`),r.changeType(e),n.codec=s,n.container=i)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:i=>{this.warn(`Failed to change ${t} SourceBuffer type`,i)}},t,this.isPending(this.tracks[t]))}blockAudio(t){var i;const s=t.start,e=s+.05*t.duration;if(!0===(null==(i=this.fragmentTracker.getAppendedFrag(s,S))?void 0:i.gap))return;const n={label:"block-audio",execute:()=>{var t;const i=this.tracks.video;(this.lastVideoAppendEnd>e||null!=i&&i.buffer&&Vi.isBuffered(i.buffer,e)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(e,S))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:n,frag:t},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:i}=this;t&&i&&(this.blockedAudioAppend=null,i.unblockAudio(t.op))}onBufferAppending(t,i){const{tracks:s}=this,{data:e,type:n,parent:r,frag:h,part:o,chunkMeta:a,offset:l}=i,u=a.buffering[n],{sn:c,cc:d}=h,v=self.performance.now();u.start=v;const g=h.stats.buffering,b=o?o.stats.buffering:null;0===g.start&&(g.start=v),b&&0===b.start&&(b.start=v);const w=s.audio;let $=!1;"audio"===n&&"audio/mpeg"===(null==w?void 0:w.container)&&($=!this.lastMpegAudioChunk||1===a.id||this.lastMpegAudioChunk.sn!==a.sn,this.lastMpegAudioChunk=a);const k=s.video,S=null==k?void 0:k.buffer;if(S&&"initSegment"!==c){const t=o||h,i=this.blockedAudioAppend;if("audio"!==n||"main"===r||this.blockedAudioAppend){if("video"===n){const s=t.end;if(i){const t=i.frag.start;(s>t||s<this.lastVideoAppendEnd||Vi.isBuffered(S,t))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const i=t.start+.05*t.duration,s=S.buffered,e=this.currentOp("video");s.length||e?!e&&!Vi.isBuffered(S,i)&&this.lastVideoAppendEnd<i&&this.blockAudio(t):this.blockAudio(t)}}const T=(o||h).start,E={label:`append-${n}`,execute:()=>{var t;u.executeStart=self.performance.now();const i=null==(t=this.tracks[n])?void 0:t.buffer;i&&($?this.updateTimestampOffset(i,T,.1,n,c,d):void 0!==l&&f(l)&&this.updateTimestampOffset(i,l,1e-6,n,c,d)),this.appendExecutor(e,n)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();u.executeEnd=u.end=t,0===g.first&&(g.first=t),b&&0===b.first&&(b.first=t);const i={};this.sourceBuffers.forEach((([t,s])=>{t&&(i[t]=Vi.getBuffered(s))})),this.appendErrors[n]=0,"audio"===n||"video"===n?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:h,part:o,chunkMeta:a,parent:h.type,timeRanges:i})},onError:t=>{var i;const s={type:p.MEDIA_ERROR,parent:h.type,details:m.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:h,part:o,chunkMeta:a,error:t,err:t,fatal:!1},e=null==(i=this.media)?void 0:i.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)s.details=m.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!e)s.errorAction=Ti(!0);else if(t.name===Bn&&0===this.sourceBufferCount)s.errorAction=Ti(!0);else{const t=++this.appendErrors[n];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${e||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||e)&&(s.fatal=!0)}this.hls.trigger(y.ERROR,s)}};this.append(E,n,this.isPending(this.tracks[n]))}getFlushOp(t,i,s){return this.log(`queuing "${t}" remove ${i}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,i,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove ${i}-${s} from "${t}" SourceBuffer`,e)}}}onBufferFlushing(t,i){const{type:s,startOffset:e,endOffset:n}=i;s?this.append(this.getFlushOp(s,e,n),s):this.sourceBuffers.forEach((([t])=>{t&&this.append(this.getFlushOp(t,e,n),t)}))}onFragParsed(t,i){const{frag:s,part:e}=i,n=[],r=e?e.elementaryStreams:s.elementaryStreams;r[it]?n.push("audiovideo"):(r[Z]&&n.push("audio"),r[tt]&&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(y.FRAG_BUFFERED,{frag:s,part:e,stats:e?e.stats:s.stats,id:s.type})}),n).catch((t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(t,i){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var i,s;return t&&(!(null!=(i=this.tracks[t])&&i.ended)||(null==(s=this.tracks[t])?void 0:s.ending))}))}onBufferEos(t,i){var s;this.sourceBuffers.forEach((([t])=>{if(t){const s=this.tracks[t];i.type&&i.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}}));const e=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var i;return t&&!(null!=(i=this.tracks[t])&&i.ended)}))&&(e?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(y.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach((([t])=>{if(null!==t){const i=this.tracks[t];i&&(i.ending=!1)}}))}onLevelUpdated(t,{details:i}){i.fragments.length&&(this.details=i,this.updateDuration())}updateDuration(){this.blockUntilOpen((()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)}))}onError(t,i){if(i.details===m.BUFFER_APPEND_ERROR&&i.frag){var s;const t=null==(s=i.errorAction)?void 0:s.nextAutoLevel;f(t)&&t!==i.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:i,media:s}=this;if(!s||null===i)return;if(!this.sourceBufferCount)return;const e=t.config,n=s.currentTime,r=i.levelTargetDuration,h=i.live&&null!==e.liveBackBufferLength?e.liveBackBufferLength:e.backBufferLength;if(f(h)&&h>=0){const t=Math.max(h,r),i=Math.floor(n/r)*r-t;this.flushBackBuffer(n,r,i)}if(f(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){this.sourceBuffers.forEach((([t,i])=>{if(i){const n=Vi.getBuffered(i);if(n.length>0&&s>n.start(0)){var e;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:s});const i=this.tracks[t];if(null!=(e=this.details)&&e.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=i&&i.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}}))}flushFrontBuffer(t,i,s){this.sourceBuffers.forEach((([i,e])=>{if(e){const n=Vi.getBuffered(e),r=n.length;if(r<2)return;const h=n.start(r-1),o=n.end(r-1);if(s>h||t>=h&&t<=o)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:i})}}))}getDurationAndRange(){var t;const{details:i,mediaSource:s}=this;if(!i||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const e=i.edge;if(i.live&&this.hls.config.liveDurationInfinity){if(i.fragments.length&&i.live&&s.setLiveSeekableRange){const t=Math.max(0,i.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,e)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return f(n)?{duration:n}:null;const r=this.media.duration;return e>(f(s.duration)?s.duration:0)&&e>r||!f(r)?{duration:e}:null}updateMediaSource({duration:t,start:i,end:s}){const e=this.mediaSource;this.media&&e&&"open"===e.readyState&&(e.duration!==t&&(f(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),e.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${e.duration}. Setting seekable range to ${i}-${s}.`),e.setLiveSeekableRange(i,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:i,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${i} codec events expected: ${t}) ${ri(s)}`),this.tracksReady){var e;const t=null==(e=this.transferData)?void 0:e.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach((([i,s])=>{if(i){const e=this.tracks[i];t[i]={buffer:s,container:e.container,codec:e.codec,supplemental:e.supplemental,levelCodec:e.levelCodec,id:e.id,metadata:e.metadata}}})),this.hls.trigger(y.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([t])=>{this.executeNext(t)}))}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:i,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in t){const r=n,h=t[r];if(this.isPending(h)){const t=this.getTrackCodec(h,r),n=`${h.container};codecs=${t}`;h.codec=t,this.log(`creating sourceBuffer(${n})${this.currentOp(r)?" Queued":""} ${ri(h)}`);try{const t=s.addSourceBuffer(n);i[Gn(r)]=[r,t],h.buffer=t}catch(t){var e;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(r),null==(e=this.operationQueue)||e.removeBlockers(),delete this.tracks[r],void this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:r,mimeType:n,parent:h.id})}this.trackSourceBuffer(r,h)}}this.bufferCreated()}getTrackCodec(t,i){const s=t.supplemental;let e=t.codec;s&&("video"===i||"audiovideo"===i)&&Rt(s,"video")&&(e=function(t,i){const s=[];if(t){const i=t.split(",");for(let t=0;t<i.length;t++)Ct(i[t],"video")||s.push(i[t])}return i&&s.push(i),s.join(",")}(e,s));const n=Gt(e,t.levelCodec);return n?"audio"===i.slice(0,5)?jt(n,this.appendSource):n:""}trackSourceBuffer(t,i){const s=i.buffer;if(!s)return;const e=this.getTrackCodec(i,t);this.tracks[t]={buffer:s,codec:e,container:i.container,levelCodec:i.levelCodec,supplemental:i.supplemental,metadata:i.metadata,id:i.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",((t,i)=>{const s=i.removedRanges;null!=s&&s.length&&this.hls.trigger(y.BUFFER_FLUSHED,{type:t})}))}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 i=this.currentOp(t);i&&i.onStart()}onSBUpdateEnd(t){var i;if("closed"===(null==(i=this.mediaSource)?void 0:i.readyState))return void this.resetBuffer(t);const s=this.currentOp(t);s&&(s.onComplete(),this.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(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:e,fatal:!1});const n=this.currentOp(t);n&&n.onError(e)}updateTimestampOffset(t,i,s,e,n,r){Math.abs(i-t.timestampOffset)>=s&&(this.log(`Updating ${e} SourceBuffer timestampOffset to ${i} (sn: ${n} cc: ${r})`),t.timestampOffset=i)}removeExecutor(t,i,s){const{media:e,mediaSource:n}=this,r=this.tracks[t],h=null==r?void 0:r.buffer;if(!e||!n||!h)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=f(e.duration)?e.duration:1/0,a=f(n.duration)?n.duration:1/0,l=Math.max(0,i),u=Math.min(s,o,a);u>l&&(!r.ending||r.ended)?(r.ended=!1,this.log(`Removing [${l},${u}] from the ${t} SourceBuffer`),h.remove(l,u)):this.shiftAndExecuteNext(t)}appendExecutor(t,i){const s=this.tracks[i],e=null==s?void 0:s.buffer;if(!e)throw new _n(`Attempting to append to the ${i} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,e.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch((t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some((([t,i])=>t&&i.updating))}isQueued(){return this.sourceBuffers.some((([t])=>t&&!!this.currentOp(t)))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,i=this.sourceBufferTypes){if(!i.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:s}=this,e=i.map((t=>this.appendBlocker(t)));return i.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(e).then((()=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(t){t.forEach((t=>{var i;const s=null==(i=this.tracks[t])?void 0:i.buffer;s&&!s.updating&&this.shiftAndExecuteNext(t)}))}append(t,i,s){this.operationQueue&&this.operationQueue.append(t,i,s)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((t,i)=>t+(this.isPending(this.tracks[i])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((t,[i])=>t+(i?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([t])=>t)).filter((t=>!!t))}addBufferListener(t,i,s){const e=this.tracks[t];if(!e)return;const n=e.buffer;if(!n)return;const r=s.bind(this,t);e.listeners.push({event:i,listener:r}),n.addEventListener(i,r)}removeBufferListeners(t){const i=this.tracks[t];if(!i)return;const s=i.buffer;s&&(i.listeners.forEach((t=>{s.removeEventListener(t.event,t.listener)})),i.listeners.length=0)}},capLevelController:Hn,errorController:class extends P{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(y.ERROR,this.onError,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.ERROR,this.onError,this),t.off(y.ERROR,this.onErrorOut,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.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)===S?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,i){var s;if(i.fatal)return;const e=this.hls,n=i.context;switch(i.details){case m.FRAG_LOAD_ERROR:case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_ERROR:case m.KEY_LOAD_TIMEOUT:return void(i.errorAction=this.getFragRetryOrSwitchAction(i));case m.FRAG_PARSING_ERROR:if(null!=(s=i.frag)&&s.gap)return void(i.errorAction=Ti());case m.FRAG_GAP:case m.FRAG_DECRYPT_ERROR:return i.errorAction=this.getFragRetryOrSwitchAction(i),void(i.errorAction.action=2);case m.LEVEL_EMPTY_ERROR:case m.LEVEL_PARSING_ERROR:{var r,h;const t=i.parent===S?i.level:e.loadLevel;i.details===m.LEVEL_EMPTY_ERROR&&null!=(r=i.context)&&null!=(h=r.levelDetails)&&h.live?i.errorAction=this.getPlaylistRetryOrSwitchAction(i,t):(i.levelRetry=!1,i.errorAction=this.getLevelSwitchAction(i,t))}return;case m.LEVEL_LOAD_ERROR:case m.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(i.errorAction=this.getPlaylistRetryOrSwitchAction(i,n.level)));case m.AUDIO_TRACK_LOAD_ERROR:case m.AUDIO_TRACK_LOAD_TIMEOUT:case m.SUBTITLE_LOAD_ERROR:case m.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=e.loadLevelObj;if(t&&(n.type===$&&t.hasAudioGroup(n.groupId)||n.type===k&&t.hasSubtitleGroup(n.groupId)))return i.errorAction=this.getPlaylistRetryOrSwitchAction(i,e.loadLevel),i.errorAction.action=2,void(i.errorAction.flags=1)}return;case m.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=e.loadLevelObj,s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?i.errorAction={action:2,flags:2,hdcpLevel:s}:this.keySystemError(i)}return;case m.BUFFER_ADD_CODEC_ERROR:case m.REMUX_ALLOC_ERROR:case m.BUFFER_APPEND_ERROR:var o;return void(i.errorAction||(i.errorAction=this.getLevelSwitchAction(i,null!=(o=i.level)?o:e.loadLevel)));case m.INTERNAL_EXCEPTION:case m.BUFFER_APPENDING_ERROR:case m.BUFFER_FULL_ERROR:case m.LEVEL_SWITCH_ERROR:case m.BUFFER_STALLED_ERROR:case m.BUFFER_SEEK_OVER_HOLE:case m.BUFFER_NUDGE_ON_STALL:return void(i.errorAction=Ti())}i.type===p.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=wi(this.hls.config.playlistLoadPolicy,t),e=this.playlistError++;if(Si(s,e,bi(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=wi(t.details.startsWith("key")?r:n,t),o=i.levels.reduce(((t,i)=>t+i.fragmentError),0);if(e&&(t.details!==m.FRAG_GAP&&e.fragmentError++,Si(h,o,bi(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===m.BUFFER_APPEND_ERROR&&e.fragmentError++;let a=-1;const{levels:l,loadLevel:u,minAutoLevel:c,maxAutoLevel:d}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(n=t.frag)?void 0:n.type,v=(f===T&&i===m.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(i===m.BUFFER_ADD_CODEC_ERROR||i===m.BUFFER_APPEND_ERROR))&&l.some((({audioCodec:t})=>e.audioCodec!==t)),g="video"===t.sourceBufferName&&(i===m.BUFFER_ADD_CODEC_ERROR||i===m.BUFFER_APPEND_ERROR)&&l.some((({codecSet:t,audioCodec:i})=>e.codecSet!==t&&e.audioCodec===i)),{type:p,groupId:y}=null!=(r=t.context)?r:{};for(let s=l.length;s--;){const n=(s+u)%l.length;if(n!==u&&n>=c&&n<=d&&0===l[n].loadError){var h,o;const s=l[n];if(i===m.FRAG_GAP&&f===S&&t.frag){const i=l[n].details;if(i){const s=gi(t.frag,i.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===$&&s.hasAudioGroup(y)||p===k&&s.hasSubtitleGroup(y))continue;if(f===T&&null!=(h=e.audioGroups)&&h.some((t=>s.hasAudioGroup(t)))||f===E&&null!=(o=e.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||v&&e.audioCodec===s.audioCodec||!v&&e.audioCodec!==s.audioCodec||g&&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===m.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=Zt[Zt.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){if(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,t.details===m.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const i=Xt(t.mimeType),s=this.hls.levels;for(let e=s.length;e--;)s[e][`${t.sourceBufferName}Codec`]===i&&this.hls.removeLevel(e)}}},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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}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(y.FPS_DROP,{currentDropped:t,currentDecoded:n,totalDroppedFrames:s}),r>0&&t>h.config.fpsDroppedMonitoringThreshold*n){let t=h.currentLevel;h.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=t)&&(t-=1,h.trigger(y.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:ms,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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:Wh,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 ie{constructor(t,i,s){super(t,i,s,"subtitle-stream-controller",E),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,i){this.stopLoad(),this.state=te.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=i?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,i){this.tracksBuffered=[],super.onMediaDetaching(t,i)}onLevelLoaded(t,i){this.mainDetails=i.details}onSubtitleFragProcessed(t,i){const{frag:s,success:e}=i;if(this.fragContextChanged(s)||(et(s)&&(this.fragPrevious=s),this.state=te.IDLE),!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),this.media&&this.tick()}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,E)}}onError(t,i){const s=i.frag;(null==s?void 0:s.type)===E&&(i.details===m.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==te.STOPPED&&(this.state=te.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:i}){this.levels&&Rn(this.levels,i)?this.levels=i.map((t=>new ei(t))):(this.tracksBuffered=[],this.levels=i.map((t=>{const i=new ei(t);return this.tracksBuffered[i.id]=[],i})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,E),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.state!==te.STOPPED&&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){if(r.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);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?(Zs(r,t),a=r.fragmentStart):i&&(a=i.start,Hs(r,a)),t&&!this.startFragRequested&&this.setStartPosition(t,a)}o.details=r,this.levelLastLoaded=o,h===e&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:r,id:h,groupId:i.groupId}),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===te.IDLE)&&(gi(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&&es(e.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),e.key.buffer,e.iv.buffer,ns(e.method)).catch((t=>{throw n.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((s=>{const e=performance.now();n.trigger(y.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:t,tdecrypt:e}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=te.IDLE}))}}doTick(){if(this.media){if(this.state===te.IDLE){const{currentTrackId:t,levels:i}=this,s=null==i?void 0:i[t];if(!s||!i.length||!s.details)return;if(this.waitForLive(s))return;const{config:e}=this,n=this.getLoadPosition(),r=Vi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,e.maxBufferHole),{end:h,len:o}=r,a=s.details;if(o>this.hls.maxBufferLength+a.levelTargetDuration)return;const l=a.fragments,u=l.length,c=a.edge;let d=null;const f=this.fragPrevious;if(h<c){const t=e.maxFragLookUpTolerance,i=h>c-t?0:t;d=gi(f,l,Math.max(l[0].start,h),i),!d&&f&&f.start<l[0].start&&(d=l[0])}else d=l[u-1];if(d=this.filterReplacedPrimary(d,s.details),!d)return;const v=l[d.sn-a.startSN-1];if(v&&v.cc===d.cc&&this.fragmentTracker.getState(v)===Ei&&(d=v),this.fragmentTracker.getState(d)===Ei){const t=this.mapToInitFragWhenRequired(d);t&&this.loadFragment(t,s,h)}}}else this.state=te.IDLE}loadFragment(t,i,s){et(t)?super.loadFragment(t,i,s):this._loadInitSegment(t,i)}get mediaBufferTimeRanges(){return new Zr(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Cn{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.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Fr(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(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVEL_LOADING,this.onLevelLoading,this),t.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(y.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(t,i){const s=this.media;if(!s)return;const e=!!i.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,e||Fr(s.textTracks).forEach((t=>{Nr(t)}))}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=li(i,t);if(s>-1)n=t[s];else{const t=li(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(y.SUBTITLE_TRACKS_UPDATED,r),-1!==e&&-1===this.trackId&&this.setSubtitleTrack(e)}}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||ui(n,t)))return e}if(t){for(let s=0;s<i.length;s++)if(On(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(On(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(Nn(i[s],t))return s}return-1}onError(t,i){!i.fatal&&i.context&&(i.context.type!==k||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){if(-1===t.id)return this.setSubtitleTrack(-1),null;const i=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&ui(t,s))return s;const e=li(t,this.tracksInGroup);if(e>-1){const t=this.tracksInGroup[e];return this.setSubtitleTrack(e),t}if(s)return null;{const s=li(t,i);if(s>-1)return i[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,i){super.loadingPlaylist(t,i);const s=t.id,e=t.groupId,n=this.getUrlWithDirectives(t.url,i),r=t.details,h=null==r?void 0:r.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${e}${void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:""}${h&&r.live?" age "+h.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:i||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const i=Fr(t.textTracks),s=this.currentTrack;let e;if(s&&(e=i.filter((t=>Nn(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||!f(t))return void this.warn(`Invalid subtitle track id: ${t}`);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(y.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(y.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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(y.FRAG_LOADING,this.onFragLoading,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this),t.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(y.FRAG_LOADING,this.onFragLoading,this),t.off(y.FRAG_LOADED,this.onFragLoaded,this),t.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Hh(this,"textTrack1"),i=new Hh(this,"textTrack2"),s=new Hh(this,"textTrack3"),e=new Hh(this,"textTrack4");this.cea608Parser1=new ph(1,t,i),this.cea608Parser2=new ph(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(y.CUES_PARSED,{type:"captions",cues:n,track:t})}}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){const{unparsedVttFrags:r}=this;s===S&&(this.initPTS[i.cc]={baseTime:e,timescale:n}),r.length&&(this.unparsedVttFrags=[],r.forEach((t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,t):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))}getExistingTrack(t,i){const{media:s}=this;if(s)for(let e=0;e<s.textTracks.length;e++){const n=s.textTracks[e];if(Vh(n,{name:t,lang:i,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))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,Nr(s[t]),Rr(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(y.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,i.mediaSource||this._cleanTracks()}onMediaDetaching(t,i){const s=!!i.transferMedia;if(this.media=null,s)return;const{captionsTracks:e}=this;Object.keys(e).forEach((t=>{Nr(e[t]),delete e[t]})),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++)Nr(i[t])}onSubtitleTracksUpdated(t,i){const s=i.subtitleTracks||[],e=s.some((t=>t.textCodec===Ph));if(this.config.enableWebVTT||e&&this.config.enableIMSC1){if(Rn(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,i=t?Fr(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]&&Vh(i[s],t)){e=i[s],i[s]=null;break}e&&(s=e)}if(s)Nr(s);else{const i=Kh(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&&this.hls.logger.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(y.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===S){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===E)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===Ph?this._parseIMSC1(s,e):this._parseVTTs(i)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,i){const s=this.hls;Nh(i,this.initPTS[t.cc],(i=>{this._appendCues(i,t.level),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(y.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 Mh,a=j(new Uint8Array(t)).trim().replace(xh,"\n").split("\n"),l=[],u=i?function(t,i=1){return fn(t,9e4,1/i)}(i.baseTime,i.timescale):0;let c,d="00:00.000",v=0,g=0,p=!0;o.oncue=function(t){const r=s[e];let h=s.ccOffset;const o=(v-u)/9e4;if(null!=r&&r.new&&(void 0!==g?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(c=new Error("Missing initPTS for VTT MPEGTS"));h=o-s.presentationOffset}const a=t.endTime-t.startTime,d=wn(9e4*(t.startTime+h-g),9e4*n)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+a,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=Dh(t.startTime,t.endTime,f)),t.endTime>0&&l.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?h(c):r(l)},a.forEach((t=>{if(p){if(Ih(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{Ih(t,"LOCAL:")?d=t.slice(6):Ih(t,"MPEGTS:")&&(v=parseInt(t.slice(7)))}));try{g=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(!(f(i)&&f(s)&&f(e)&&f(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*e,i+=36e5*n,i}(d)/1e3}catch(t){c=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}(null!=(i=s.initSegment)&&i.data?Tt(s.initSegment.data,new Uint8Array(e)).buffer:e,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(y.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),o.logger.log(`Failed to parse VTT cue: ${i}`),n&&h>s.cc||o.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:i})}))}_fallbackToIMSC1(t,i){const s=this.tracks[t.level];s.textCodec||Nh(i,this.initPTS[t.cc],(()=>{s.textCodec=Ph,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=>Or(s,t)))}else{const e=this.tracks[i];if(!e)return;s.trigger(y.CUES_PARSED,{type:"subtitles",cues:t,track:e.default?"default":"subtitles"+i})}}onFragDecrypted(t,i){const{frag:s}=i;s.type===E&&this.onFragLoaded(y.FRAG_LOADED,i)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,i){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:e}=i;if(s.type!==S||"NONE"!==this.closedCaptionsForLevel(s))for(let t=0;t<e.length;t++){const i=e[t].bytes;if(i){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(i);this.cea608Parser1.addData(e[t].pts,s[0]),this.cea608Parser2.addData(e[t].pts,s[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=>Ur(t[e],i,s)))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==e){const{textTracks:t}=this;Object.keys(t).forEach((s=>Ur(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 ie{constructor(t,i,s){super(t,i,s,"audio-stream-controller",T),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!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.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(y.BUFFER_RESET,this.onBufferReset,this),t.on(y.BUFFER_CREATED,this.onBufferCreated,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(y.FRAG_LOADING,this.onFragLoading,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(y.BUFFER_RESET,this.onBufferReset,this),t.off(y.BUFFER_CREATED,this.onBufferCreated,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(y.FRAG_LOADING,this.onFragLoading,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){if(s===S){const t=i.cc,s=this.fragCurrent;if(this.initPTS[t]={baseTime:e,timescale:n},this.log(`InitPTS for cc: ${t} found from main: ${e}/${n}`),this.mainAnchor=i,this.state===te.WAITING_INIT_PTS){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==t)&&this.syncWithAnchor(i,null==s?void 0:s.frag)}else!this.hls.hasEnoughToStart&&s&&s.cc!==t?(s.abortRequests(),this.syncWithAnchor(i,s)):this.state===te.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,i){var s;const e=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(i&&(null==e?void 0:e.cc)===i.cc)return;const n=(e||t).cc,r=yi(this.getLevelDetails(),n,this.getLoadPosition());r&&(this.log(`Waiting fragment cc (${null==i?void 0:i.cc}) cancelled because video is at cc ${t.cc}`),this.startFragRequested=!1,this.nextLoadPosition=r.start,this.resetLoadingState(),this.state===te.IDLE&&this.doTickIdle())}startLoad(t,i){if(!this.levels)return this.startPosition=t,void(this.state=te.STOPPED);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s,this.state=te.IDLE):this.state=te.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=i?-1:t,this.tick()}doTick(){switch(this.state){case te.IDLE:this.doTickIdle();break;case te.WAITING_TRACK:{const{levels:t,trackId:i}=this,s=null==t?void 0:t[i],e=null==s?void 0:s.details;if(e&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(e))break;this.state=te.WAITING_INIT_PTS}break}case te.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),s=this.retryDate;if(!s||i>=s||null!=(t=this.media)&&t.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=te.IDLE}break}case te.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:i,part:s,cache:e,complete:n}=t,r=this.mainAnchor;if(void 0!==this.initPTS[i.cc]){this.waitingData=null,this.state=te.FRAG_LOADING;const t={frag:i,part:s,payload:e.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),n&&super._handleFragmentLoadComplete(t)}else r&&r.cc!==t.frag.cc&&this.syncWithAnchor(r,t.frag)}else this.state=te.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:i,levels:s,media:e,trackId:n}=this;if(!this.buffering||!e&&!this.primaryPrefetch&&(this.startFragRequested||!i.config.startFragPrefetch)||null==s||!s[n])return;const r=s[n],h=r.details;if(!h||this.waitForLive(r)||this.waitForCdnTuneIn(h))return this.state=te.WAITING_TRACK,void(this.startFragRequested=!1);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,Z,T));const a=this.getFwdBufferInfo(o,T);if(null===a)return;if(!this.switchingTrack&&this._streamEnded(a,h))return i.trigger(y.BUFFER_EOS,{type:"audio"}),void(this.state=te.ENDED);const l=a.len,u=i.maxBufferLength,c=h.fragments,d=c[0].start,f=this.getLoadPosition(),v=this.flushing?f:a.end;if(this.switchingTrack&&e&&h.PTSKnown&&f<d&&(a.end>d||a.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),e.currentTime=d+.05),l>=u&&!this.switchingTrack&&v<c[c.length-1].start)return;let g=this.getNextFragment(v,h);if(g&&this.isLoopLoading(g,v)&&(g=this.getNextFragmentLoopLoading(g,h,a,S,u)),!g)return void(this.bufferFlushed=!0);let p=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&p&&et(g)&&!g.endList&&(!h.live||!this.loadingParts&&v<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(p)===Mi&&(this.mainFragLoading=p=null),p&&et(p))){if(g.start>p.end){const t=this.fragmentTracker.getFragAtPos(v,S);t&&t.end>p.end&&(p=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(g.start>p.end)return}this.loadFragment(g,r,v)}onMediaDetaching(t,i){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,i)}onAudioTracksUpdated(t,{audioTracks:i}){this.resetTransmuxer(),this.levels=i.map((t=>new ei(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.switchingTrack=i,this.flushAudioIfNeeded(i),this.state!==te.STOPPED&&(this.setInterval(100),this.state=te.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=i,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,i){this.mainDetails=i.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,i){var s;const{levels:e}=this,{details:n,id:r,groupId:h,track:o}=i;if(!e)return void this.warn(`Audio tracks reset while loading track ${r} "${o.name}" of "${h}"`);const a=this.mainDetails;if(!a||n.endCC>a.endCC||a.expired)return this.cachedTrackLoadedData=i,void(this.state!==te.STOPPED&&(this.state=te.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${o.name}" of "${h}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const l=e[r];let u=0;if(n.live||null!=(s=l.details)&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var c;l.details&&(u=this.alignPlaylists(n,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)),n.alignedSliding||(Js(n,a),n.alignedSliding||Zs(n,a),u=n.fragmentStart)}l.details=n,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(a,u),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:i.groupId}),this.state!==te.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=te.IDLE),this.tick()}_handleFragmentLoadProgress(t){var i;const s=t.frag,{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 u=r.defaultAudioCodec||a.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Pn(this.hls,T,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 Hi(s.level,s.sn,s.stats.chunkCount,n.byteLength,i,-1!==i);c.push(n,f,u,"",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 ee,complete:!1};t.push(new Uint8Array(n)),this.state!==te.STOPPED&&(this.state=te.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,i){this.bufferFlushed=this.flushing=!1;const s=i.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,i){!this.audioOnly&&i.frag.type===S&&et(i.frag)&&(this.mainFragLoading=i,this.state===te.IDLE&&this.tick())}onFragBuffered(t,i){const{frag:s,part:e}=i;if(s.type===T)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(et(s)){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,D({},t)))}this.fragBufferedComplete(s,e),this.media&&this.tick()}else this.audioOnly||s.type!==S||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,i){var s;if(i.fatal)this.state=te.ERROR;else switch(i.details){case m.FRAG_GAP:case m.FRAG_PARSING_ERROR:case m.FRAG_DECRYPT_ERROR:case m.FRAG_LOAD_ERROR:case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_ERROR:case m.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(T,i);break;case m.AUDIO_TRACK_LOAD_ERROR:case m.AUDIO_TRACK_LOAD_TIMEOUT:case m.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==te.WAITING_TRACK||(null==(s=i.context)?void 0:s.type)!==$||(this.state=te.IDLE);break;case m.BUFFER_ADD_CODEC_ERROR:case m.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)||this.resetLoadingState();break;case m.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case m.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}onBufferFlushing(t,{type:i}){i!==tt&&(this.flushing=!0)}onBufferFlushed(t,{type:i}){if(i!==tt){this.flushing=!1,this.bufferFlushed=!0,this.state===te.ENDED&&(this.state=te.IDLE);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,i,T),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:u}=l,{audio:c,text:d,id3:f,initSegment:v}=n;if(!this.fragContextChanged(o)&&u){if(this.state=te.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,v.tracks,t,r),e.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:v.tracks})}if(c){const{startPTS:t,endPTS:i,startDTS:s,endDTS:e}=c;a&&(a.elementaryStreams[Z]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(Z,t,i,s,e),this.bufferFragmentData(c,o,a,r)}if(null!=f&&null!=(i=f.samples)&&i.length){const t=x({id:s,frag:o,details:u},f);e.trigger(y.FRAG_PARSING_METADATA,t)}if(d){const t=x({id:s,frag:o,details:u},d);e.trigger(y.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,i,s,e){if(this.state!==te.PARSING)return;if(i.video&&delete i.video,i.audiovideo&&delete i.audiovideo,!i.audio)return;const n=i.audio;n.id=T;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(y.BUFFER_CODECS,i);const h=n.initSegment;null!=h&&h.byteLength&&this.hls.trigger(y.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.switchingTrack||e===Ei||e===Li)if(et(t))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=te.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==i.details.fragmentStart&&Zs(i.details,s)}else super.loadFragment(t,i,s);else this._loadInitSegment(t,i);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;ui({name:i,lang:s,assocLang:e,characteristics:n,audioCodec:r,channels:h},t,ci)||(fi(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:i}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,i.trigger(y.AUDIO_TRACK_SWITCHED,D({},t))}},audioTrackController:class extends Cn{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVEL_LOADING,this.onLevelLoading,this),t.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(y.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=li(i,t,ci);if(s>-1)n=t[s];else{const t=li(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(y.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(y.ERROR,{type:p.MEDIA_ERROR,details:m.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}}onError(t,i){!i.fatal&&i.context&&(i.context.type!==$||i.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(i.context.groupId)||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&&ui(t,e,ci))return e;const n=li(t,this.tracksInGroup,ci);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),u=di(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 li(t,r,n)>-1}));return u>-1?u:di(i,e,(i=>{const e=i.audioGroups,r=s.filter((t=>!e||-1!==e.indexOf(t.groupId)));return li(t,r,n)>-1}))}(t,i.levels,s,e,ci);if(-1===n)return null;i.nextLoadLevel=n}if(t.channels||t.audioCodec){const i=li(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.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(y.AUDIO_TRACK_SWITCHING,D({},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||ui(t,e,ci)))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(ui({name:s,lang:e,assocLang:n,characteristics:r,audioCodec:h,channels:o},i[t],ci))return t;for(let s=0;s<i.length;s++)if(On(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(On(t.attrs,i[s].attrs,["LANGUAGE"]))return s}return-1}loadPlaylist(t){super.loadPlaylist();const i=this.currentTrack;this.shouldLoadPlaylist(i)&&fi(i.url,this.hls)&&this.scheduleLoading(i,t)}loadingPlaylist(t,i){super.loadingPlaylist(t,i);const s=t.id,e=t.groupId,n=this.getUrlWithDirectives(t.url,i),r=t.details,h=null==r?void 0:r.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${e}${void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:""}${h&&r.live?" age "+h.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:i||null,track:t})}},emeController:Pr,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:Kn,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:i,part:s}=t,e=this.hls.levels[i.level],n=this.getObjectType(i),r={d:1e3*(s||i).duration,ot:n};n!==Xn&&n!==Vn&&n!=Wn||(r.br=e.bitrate/1e3,r.tb=this.getTopBandwidth(n)/1e3,r.bl=this.getBufferLength(n));const h=s?this.getNextPart(s):this.getNextFrag(i);null!=h&&h.url&&h.url!==i.url&&(r.nor=h.url),this.apply(t,r)}catch(t){this.hls.logger.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||t.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHED,this.onMediaDetached,this),t.on(y.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHED,this.onMediaDetached,this),t.off(y.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=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:Yn,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,i={}){x(i,this.createData()),this.starved&&(i.ot===zn||i.ot===Xn||i.ot===Wn)&&(i.bs=!0,i.su=!0,this.starved=!1),null==i.su&&(i.su=this.buffering);const{includeKeys:s}=this;s&&(i=Object.keys(i).reduce(((t,e)=>(s.includes(e)&&(t[e]=i[e]),t)),{}));const e={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),function(t,i,s){x(t,function(t,i={}){const s={};if(!t)return s;const e=Object.entries(t),n=Object.entries(ir).concat(Object.entries((null==i?void 0:i.customHeaderMap)||{})),r=e.reduce(((t,i)=>{var s,e;const[r,h]=i,o=(null===(s=n.find((t=>t[1].includes(r))))||void 0===s?void 0:s[0])||Jn;return null!==(e=t[o])&&void 0!==e||(t[o]={}),t[o][r]=h,t}),{});return Object.entries(r).reduce(((t,[s,e])=>(t[s]=Ar(e,i),t)),s)}(i,s))}(t.headers,i,e)):t.url=function(t,i,s){const e=function(t,i={}){if(!t)return"";const s=Ar(t,i);return`CMCD=${encodeURIComponent(s)}`}(i,s);if(!e)return t;if(Lr.test(t))return t.replace(Lr,e);const n=t.includes("?")?"&":"?";return`${t}${n}${e}`}(t.url,i,e)}getNextFrag(t){var i;const s=null==(i=this.hls.levels[t.level])?void 0:i.details;if(s)return s.fragments[t.sn-s.startSN+1]}getNextPart(t){var i,s;const{index:e,fragment:n}=t,r=null==(i=this.hls.levels[n.level])||null==(s=i.details)?void 0:s.partList;if(r){const{sn:t}=n;for(let i=r.length-1;i>=0;i--){const s=r[i];if(s.index===e&&s.fragment.sn===t)return r[i+1]}}}getObjectType(t){const{type:i}=t;return"subtitle"===i?qn:"initSegment"===t.sn?zn:"audio"===i?Vn:"main"===i?this.hls.audioTracks.length?Xn:Wn:void 0}getTopBandwidth(t){let i,s=0;const e=this.hls;if(t===Vn)i=e.audioTracks;else{const t=e.maxAutoLevel;i=e.levels.slice(0,t>-1?t+1:e.levels.length)}return i.forEach((t=>{t.bitrate>s&&(s=t.bitrate)})),s>0?s:NaN}getBufferLength(t){const i=this.media,s=t===Vn?this.audioBuffer:this.videoBuffer;return s&&i?1e3*Vi.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 extends P{constructor(t){super("content-steering",t.logger),this.hls=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.registerListeners()}registerListeners(){const t=this.hls;t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((t,i)=>(-1===t.indexOf(i.pathwayId)&&t.push(i.pathwayId),t)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}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=this.pathways()),e&&e.length>1&&(this.updatePathwayPriority(e),s.resolved=this.pathwayId!==n),i.details!==m.BUFFER_APPEND_ERROR||i.fatal?s.resolved||this.warn(`Could not resolve ${i.details} ("${i.error.message}") with content-steering for Pathway: ${n} levels: ${t?t.length:t} priorities: ${ri(e)} penalized: ${ri(this.penalizedPathways)}`):s.resolved=!0}}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,zs(i),this.hls.trigger(y.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===$&&e[s].hasAudioGroup(t)||i===k&&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 Zi(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=xr(t.uri,i["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",h),l=new ei({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),Mr(this.audioTracks,s,h,n),Mr(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!==(null==n?void 0: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(y.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)}},interstitialsController:class extends P{constructor(t,i){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;const i=t-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const s=i<=-.01;this.timelinePos=t,this.bufferedPos=t;const e=this.playingItem;if(!e)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(t,t-i)&&this.updateSchedule(),this.checkBuffer(),s&&t<e.start||t>=e.end){var n;const t=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(e)&&null!=(n=this.media)&&n.paused&&(this.shouldPlay=!1),!s){const i=this.findItemIndex(e);if(t>i){const s=this.schedule.findJumpRestrictedIndex(i+1,t);if(s>i)return void this.setSchedulePosition(s)}}return void this.setSchedulePosition(t)}const r=this.playingAsset;if(!r){if(this.playingLastItem&&this.isInterstitial(e)){const i=e.event.assetList[0];i&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,i))}return}const h=r.timelineStart;(s&&t<h||t>=h+(r.duration||0))&&this.setScheduleToAssetAtTime(t,r)},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const i=this.playingItem;if(!i||this.playingLastItem)return;if(t>=i.end){this.timelinePos=i.end;const t=this.findItemIndex(i);this.setSchedulePosition(t+1)}const s=this.playingAsset;s&&t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,i)=>{const s=this.schedule,e=this.playingItem,n=s.events||[],r=s.items||[],h=s.durations,o=t.map((t=>t.identifier)),a=!(!n.length&&!o.length);(a||i)&&this.log(`INTERSTITIALS_UPDATED (${n.length}): ${n}\nSchedule: ${r.map((t=>Yr(t)))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`),this.playerQueue.forEach((t=>{if(t.interstitial.appendInPlace){const i=t.assetItem.timelineStart,s=t.timelineOffset-i;if(s)try{t.timelineOffset=i}catch(e){Math.abs(s)>_r&&this.warn(`${e} ("${t.assetId}" ${t.timelineOffset}->${i})`)}}}));let l=null;if(e){const t=this.updateItem(e,this.timelinePos);this.itemsMatch(e,t)&&(this.playingItem=t,this.waitingItem=this.endedItem=null,l=()=>this.trimInPlace(t,e))}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u){const t=this.updateItem(u,this.bufferedPos);this.itemsMatch(u,t)?(this.bufferingItem=t,l||(l=()=>this.trimInPlace(t,u))):u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))}if(t.forEach((t=>{t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,null)}))})),a||i){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:r.slice(0),durations:h,removedIds:o}),this.isInterstitial(e)&&o.includes(e.event.identifier))return this.warn(`Interstitial "${e.event.identifier}" removed while playing`),void this.primaryFallback(e.event);l&&l(),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=i,this.assetListLoader=new Qr(t),this.schedule=new qr(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this),t.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(y.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(y.MEDIA_ENDED,this.onMediaEnded,this),t.on(y.ERROR,this.onError,this),t.on(y.DESTROYING,this.onDestroying,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.BUFFER_APPENDED,this.onBufferAppended,this),t.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(y.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(y.MEDIA_ENDED,this.onMediaEnded,this),t.off(y.ERROR,this.onError,this),t.off(y.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Dr(t,"play",this.onPlay),Dr(t,"pause",this.onPause),Dr(t,"seeking",this.onSeeking),Dr(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,i){const s=this.media=i.media;Ir(s,"seeking",this.onSeeking),Ir(s,"timeupdate",this.onTimeupdate),Ir(s,"play",this.onPlay),Ir(s,"pause",this.onPause)}onMediaAttached(t,i){const s=this.effectivePlayingItem,e=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!e){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,i){const s=!!i.transferMedia,e=this.media;if(this.media=null,!s&&(e&&this.removeMediaListeners(e),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const t=this,i=()=>t.bufferingItem||t.waitingItem,s=i=>i?t.getAssetPlayer(i.identifier):i,e=(i,e,n,h,o)=>{if(i){let a=i[e].start;const l=i.event;if(l){if("playout"===e||l.timelineOccupancy!==jr.Point){const t=s(n);(null==t?void 0:t.interstitial)===l&&(a+=t.assetItem.startOffset+t[o])}}else a+=("bufferedPos"===h?r():t[h])-i.start;return a}return 0},n=(i,s)=>{if(0!==i&&"primary"!==s&&t.schedule.length){var e;const n=t.schedule.findItemIndexAtTime(i),r=null==(e=t.schedule.items)?void 0:e[n];if(r)return i+(r[s].start-r.start)}return i},r=()=>{const i=t.bufferedPos;return i===Number.MAX_VALUE?h("primary"):Math.max(i,0)},h=i=>{var s;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:t.schedule.durations[i]},o=(i,n)=>{var r,h;const o=t.effectivePlayingItem;if(null!=o&&null!=(r=o.event)&&r.restrictions.skip)return;t.log(`seek to ${i} "${n}"`);const a=t.effectivePlayingItem,l=t.schedule.findItemIndexAtTime(i,n),u=null==(h=t.schedule.items)?void 0:h[l],c=t.getBufferingPlayer(),d=null==c?void 0:c.interstitial,f=null==d?void 0:d.appendInPlace,v=a&&t.itemsMatch(a,u);if(a&&(f||v)){const r=s(t.playingAsset),h=(null==r?void 0:r.media)||t.primaryMedia;if(h){const s="primary"===n?h.currentTime:e(a,n,t.playingAsset,"timelinePos","currentTime"),o=(f?s:h.currentTime)+(i-s);if(o>=0&&(!r||f||o<=r.duration))return void(h.currentTime=o)}}if(u){let s=i;"primary"!==n&&(s=u.start+(i-u[n].start));const e=!t.isInterstitial(u);if(t.isInterstitial(a)&&!a.event.appendInPlace||!e&&!u.event.appendInPlace){if(a){const r=t.findItemIndex(a);if(l>r){const i=t.schedule.findJumpRestrictedIndex(r+1,l);if(i>r)return void t.setSchedulePosition(i)}let h=0;if(e)t.timelinePos=s,t.checkBuffer();else{var g;const t=null==u||null==(g=u.event)?void 0:g.assetList;if(t){const s=i-(u[n]||u).start;for(let i=t.length;i--;){const e=t[i];if(e.duration&&s>=e.startOffset&&s<e.startOffset+e.duration){h=i;break}}}}t.setSchedulePosition(l,h)}}else{const i=t.media||(f?null==c?void 0:c.media:null);i&&(i.currentTime=s)}}},a=()=>{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const e=i();return t.isInterstitial(e)?e:null},l={get currentTime(){const i=a(),s=t.effectivePlayingItem;return s&&s===i?e(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(i){const s=a(),e=t.effectivePlayingItem;e&&e===s&&o(i+e.playout.start,"playout")},get duration(){const t=a();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var i;const s=null==(i=a())?void 0:i.event.assetList;return s?s.map((i=>t.getAssetPlayer(i.identifier))):[]},get playingIndex(){var i;const s=null==(i=a())?void 0:i.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return a()}};this.manager={get events(){var i,s;return(null==(i=t.schedule)||null==(s=i.events)?void 0:s.slice(0))||[]},get schedule(){var i,s;return(null==(i=t.schedule)||null==(s=i.items)?void 0:s.slice(0))||[]},get interstitialPlayer(){return a()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return i()},get bufferingIndex(){const s=i();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){return t.findItemIndex(t.effectivePlayingItem)},primary:{get bufferedEnd(){return r()},get currentTime(){const i=t.timelinePos;return i>0?i:0},set currentTime(t){o(t,"primary")},get duration(){return h("primary")},get seekableStart(){var i;return(null==(i=t.primaryDetails)?void 0:i.fragmentStart)||0}},integrated:{get bufferedEnd(){return e(i(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return e(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){o(t,"integrated")},get duration(){return h("integrated")},get seekableStart(){var i;return n((null==(i=t.primaryDetails)?void 0:i.fragmentStart)||0,"integrated")}},skip:()=>{const i=t.effectivePlayingItem,s=null==i?void 0:i.event;if(s&&!s.restrictions.skip){const e=t.findItemIndex(i);s.appendInPlace?o(i.playout.start+i.event.duration+.001,"playout"):t.advanceAfterAssetEnded(s,e,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const i=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&i&&s)&&this.findItemIndex(i)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,i,s;if(null===this.mediaSelection)return;const e=this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&!e.event.appendInPlace)return;let n=this.media;!n&&null!=(t=this.bufferingItem)&&null!=(i=t.event)&&i.appendInPlace&&(n=this.primaryMedia);const r=null==(s=n)?void 0:s.currentTime;return void 0!==r&&f(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,i){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,i)}transferMediaFromPlayer(t,i){const s=t.media;if(t.interstitial.appendInPlace&&s===this.primaryMedia){if(this.bufferingAsset=null,(!i||this.isInterstitial(i)&&!i.event.appendInPlace)&&i&&s)return void(this.detachedData={media:s});const e=t.transferMedia();this.log(`transfer MediaSource from ${t} ${ri(e)}`),this.detachedData=e}else i&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,i){var s,e;if(t.media===i)return;let n=null;const r=this.hls,h=t!==r,o=h&&t.interstitial.appendInPlace,a=null==(s=this.detachedData)?void 0:s.mediaSource;let l;if(r.media)o&&(n=r.transferMedia(),this.detachedData=n),l="Primary";else if(a){const t=this.getBufferingPlayer();t?(n=t.transferMedia(),l=`${t}`):l="detached MediaSource"}else l="detached media";if(!n)if(a)n=this.detachedData,this.log(`using detachedData: MediaSource ${ri(n)}`);else if(!this.detachedData||r.media===i){const t=this.playerQueue;t.length>1&&t.forEach((t=>{if(h&&t.interstitial.appendInPlace!==o){const i=t.interstitial;this.clearInterstitial(t.interstitial,null),i.appendInPlace=!1,i.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${i}`)}})),this.hls.detachMedia(),this.detachedData={media:i}}const u=n&&"mediaSource"in n&&"closed"!==(null==(e=n.mediaSource)?void 0:e.readyState),c=u&&n?n:i;this.log(`${u?"transfering MediaSource":"attaching media"} to ${h?t:"Primary"} from ${l}`),c===n&&(c.overrides={duration:this.schedule.duration,endOfStream:!h||h&&t.assetId===this.schedule.assetIdAtEnd,cueRemoval:!h}),t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,i=t.events;if(!i||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.effectivePlayingItem;if(-1===this.timelinePos){const s=this.hls.startPosition;if(this.timelinePos=s,i.length&&i[0].cue.pre){const s=t.findEventIndex(i[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const i=this.timelinePos=s>0?s:0,e=t.findItemIndexAtTime(i);this.setSchedulePosition(e)}}else if(s&&!this.playingItem){const i=t.findItemIndex(s);this.setSchedulePosition(i)}}advanceAfterAssetEnded(t,i,s){const e=Xr(t,s);if(t.isAssetPastPlayoutLimit(e)){const s=this.schedule.items;if(s){const e=i+1;if(e>=s.length)return void this.setSchedulePosition(-1);const n=t.resumeTime;this.timelinePos<n&&(this.timelinePos=n,this.checkBuffer()),this.setSchedulePosition(e)}}else this.setSchedulePosition(i,e)}setScheduleToAssetAtTime(t,i){const s=this.schedule,e=i.parentIdentifier,n=s.getEvent(e);if(n){const i=s.findEventIndex(e),r=s.findAssetIndex(n,t);this.advanceAfterAssetEnded(n,i,r-1)}}setSchedulePosition(t,i){const s=this.schedule.items;if(!s||this.playbackDisabled)return;this.log(`setSchedulePosition ${t}, ${i}`);const e=t>=0?s[t]:null,n=this.playingItem,r=this.playingLastItem;if(this.isInterstitial(n)){var h;const a=n.event,l=this.playingAsset,u=null==l?void 0:l.identifier,c=u?this.getAssetPlayer(u):null;if(c&&u&&(!this.eventItemsMatch(n,e)||void 0!==i&&u!==(null==(h=a.assetList)?void 0:h[i].identifier))){var o;const i=a.findAssetIndex(l);if(this.log(`INTERSTITIAL_ASSET_ENDED ${i+1}/${a.assetList.length} ${Wr(l)}`),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:i,event:a,schedule:s.slice(0),scheduleIndex:t,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(a,this.findItemIndex(this.playingItem),i));this.retreiveMediaSource(u,e),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,e)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${a} ${Yr(n)}`),a.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:a,schedule:s.slice(0),scheduleIndex:t}),a.cue.once)){this.updateSchedule();const t=this.schedule.items;if(e&&t){const s=this.findItemIndex(e);this.advanceSchedule(s,t,i,n,r)}return}}this.advanceSchedule(t,s,i,n,r)}advanceSchedule(t,i,s,e,n){const r=t>=0?i[t]:null,h=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach((i=>{const s=i.interstitial,e=this.schedule.findEventIndex(s.identifier);(e<t||e>t+1)&&this.clearInterstitial(s,r)})),this.isInterstitial(r)){this.timelinePos=Math.min(Math.max(this.timelinePos,r.start),r.end);const n=r.event;if(void 0===s){const i=Xr(n,(s=this.schedule.findAssetIndex(n,this.timelinePos))-1);if(n.isAssetPastPlayoutLimit(i))return void this.advanceAfterAssetEnded(n,t,s);s=i}const o=this.waitingItem;this.assetsBuffered(r,h)||this.setBufferingItem(r);let a=this.preloadAssets(n,s);if(this.eventItemsMatch(r,o||e)||(this.waitingItem=r,this.log(`INTERSTITIAL_STARTED ${Yr(r)} ${n.appendInPlace?"append in place":""}`),this.hls.trigger(y.INTERSTITIAL_STARTED,{event:n,schedule:i.slice(0),scheduleIndex:t})),!n.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${n}`);if(n.assetListLoader&&(n.assetListLoader.destroy(),n.assetListLoader=void 0),!h)return void this.log(`Waiting for attachMedia to start Interstitial ${n}`);this.waitingItem=this.endedItem=null,this.playingItem=r;const l=n.assetList[s];if(!l){const e=i[t+1],r=this.media;return e&&r&&!this.isInterstitial(e)&&r.currentTime<e.start&&(r.currentTime=this.timelinePos=e.start),void this.advanceAfterAssetEnded(n,t,s||0)}if(a||(a=this.getAssetPlayer(l.identifier)),(null===a||a.destroyed)&&(this.warn(`asset ${s+1}/${n.assetList.length} player destroyed ${n}`),a=this.createAssetPlayer(n,l,s)),!this.eventItemsMatch(r,this.bufferingItem)&&n.appendInPlace&&this.isAssetBuffered(l))return;this.startAssetPlayer(a,s,i,t,h),this.shouldPlay&&Jr(a.media)}else null!==r?(this.resumePrimary(r,t,e),this.shouldPlay&&Jr(this.hls.media)):n&&this.isInterstitial(e)&&(this.endedItem=null,this.playingItem=e,e.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t,i;return null==(t=this.mediaSelection)||null==(i=t.main)?void 0:i.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,i,s){var e;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${Yr(t)}`),null==(e=this.detachedData)||!e.mediaSource){let s=this.timelinePos;(s<t.start||s>=t.end)&&(s=this.getPrimaryResumption(t,i),this.timelinePos=s),this.attachPrimary(s,t)}if(!s)return;const n=this.schedule.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Yr(t)}`),this.hls.trigger(y.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:i}),this.checkBuffer())}getPrimaryResumption(t,i){const s=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===i)return this.hls.startPosition;if(t&&(s<t.fragmentStart||s>t.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(t){const i=this.getAssetPlayer(t.identifier);return null!=i&&i.hls?i.hls.bufferedToEnd:Vi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,i,s){i?this.setBufferingItem(i):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const e=this.primaryMedia;if(!e)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,e),s&&this.startLoadingPrimaryAt(t,s)),s||(this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,i){var s;const e=this.hls;!e.loadingEnabled||!e.media||Math.abs(((null==(s=e.mainForwardBufferInfo)?void 0:s.start)||e.media.currentTime)-t)>.5?e.startLoad(t,i):e.bufferingEnabled||e.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(y.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(y.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,i){if(-1===i.level)return;const s=this.hls.levels[i.level],e=D(D({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=e,this.schedule.parseInterstitialDateRanges(e,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,i){const s=this.hls.audioTracks[i.id],e=this.mediaSelection;if(!e)return void(this.altSelection=D(D({},this.altSelection),{},{audio:s}));const n=D(D({},e),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(t,i){const s=this.hls.subtitleTracks[i.id],e=this.mediaSelection;if(!e)return void(this.altSelection=D(D({},this.altSelection),{},{subtitles:s}));const n=D(D({},e),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(t,i){const s=ai(i);this.playerQueue.forEach((t=>t.hls.setAudioOption(i)||t.hls.setAudioOption(s)))}onSubtitleTrackSwitch(t,i){const s=ai(i);this.playerQueue.forEach((t=>t.hls.setSubtitleOption(i)||-1!==i.id&&t.hls.setSubtitleOption(s)))}onBufferCodecs(t,i){const s=i.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,i){this.checkBuffer()}onBufferFlushed(t,i){const s=this.playingItem;!s||this.itemsMatch(s,this.bufferingItem)||this.isInterstitial(s)||(this.bufferedPos=this.timelinePos,this.checkBuffer())}onBufferedToEnd(t){const i=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&i){for(let t=0;t<i.length;t++){const e=i[t];if(e.cue.post){var s;const t=this.schedule.findEventIndex(e.identifier),i=null==(s=this.schedule.items)?void 0:s[t];this.isInterstitial(i)&&this.eventItemsMatch(i,this.bufferingItem)&&this.bufferedToItem(i,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const i=this.playingItem;if(!this.playingLastItem&&i){const t=this.findItemIndex(i);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,i){const s=this.schedule.items;return t&&s&&s[this.findItemIndex(t,i)]||null}trimInPlace(t,i){if(this.isInterstitial(t)&&t.event.appendInPlace&&i.end-t.end>.25){t.event.assetList.forEach(((i,s)=>{t.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(i.identifier,null)}));const i=t.end+.25,s=Vi.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.attachPrimary(i,null),this.flushFrontBuffer(i))}}itemsMatch(t,i){return!!i&&(t===i||t.event&&i.event&&this.eventItemsMatch(t,i)||!t.event&&!i.event&&this.findItemIndex(t)===this.findItemIndex(i))}eventItemsMatch(t,i){var s;return!!i&&(t===i||t.event.identifier===(null==(s=i.event)?void 0:s.identifier))}findItemIndex(t,i){return t?this.schedule.findItemIndex(t,i):-1}updateSchedule(){const t=this.mediaSelection;t&&this.schedule.updateSchedule(t,[])}checkBuffer(t){const i=this.schedule.items;if(!i)return;const s=Vi.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,i,t)}updateBufferedPos(t,i,s){const e=this.schedule,n=this.bufferingItem;if(this.bufferedPos>t)return;if(1===i.length&&this.itemsMatch(i[0],n))return void(this.bufferedPos=t);const r=this.playingItem,h=this.findItemIndex(r);let o=e.findItemIndexAtTime(t);if(this.bufferedPos<t){var a,l;const s=this.findItemIndex(n),e=Math.min(s+1,i.length-1),r=i[e];if((-1===o&&n&&t>=n.end||null!=(a=r.event)&&a.appendInPlace&&t+.01>=r.start)&&(o=e),e-h>1&&!1===(null==n||null==(l=n.event)?void 0:l.appendInPlace))return;if(this.bufferedPos=t,o>s&&o>h)this.bufferedToItem(r);else{const i=this.primaryDetails;this.primaryLive&&i&&t>i.edge-i.targetduration&&r.start<i.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(r)&&this.preloadAssets(r.event,0)}}else s&&r&&!this.itemsMatch(r,n)&&(o===h?this.bufferedToItem(r):o===h+1&&this.bufferedToItem(i[o]))}assetsBuffered(t,i){return 0!==t.event.assetList.length&&!t.event.assetList.some((t=>{const s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(i))}))}setBufferingItem(t){const i=this.bufferingItem,s=this.schedule;if(this.itemsMatch(t,i))this.bufferingItem!==t&&(this.bufferingItem=t);else{const{items:e,events:n}=s;if(!e||!n)return i;const r=this.isInterstitial(t),h=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=h?h.remaining:i?i.end-this.timelinePos:0;this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Yr(t)}`+(i?` (${o.toFixed(2)} remaining)`:"")),this.playbackDisabled||(r?t.event.assetList.forEach((t=>{const i=this.getAssetPlayer(t.identifier);i&&i.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((t=>t.pauseBuffering())))),this.hls.trigger(y.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:e.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}return i}bufferedToItem(t,i=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,i);else if(null!==s){this.bufferingAsset=null;const i=this.detachedData;i&&i.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t)}}preloadPrimary(t){const i=this.findItemIndex(t),s=this.getPrimaryResumption(t,i);this.startLoadingPrimaryAt(s)}bufferedToEvent(t,i){const s=t.event;if(0===s.assetList.length&&!s.assetListLoader||!s.cue.once){const t=this.preloadAssets(s,i);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;s.assetList[i]&&e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,i){const s=t.assetUrl,e=t.assetList.length;if(0!==e||t.assetListLoader){if(!t.cue.once&&e){for(let s=i;s<e;s++){const i=t.assetList[s],e=this.getAssetPlayerQueueIndex(i.identifier);-1!==e&&!this.playerQueue[e].destroyed||i.error||this.createAssetPlayer(t,i,s)}return this.getAssetPlayer(t.assetList[i].identifier)}}else{const r=t.timelineStart;if(t.appendInPlace){var n;const i=this.playingItem;this.isInterstitial(i)||(null==i||null==(n=i.nextEvent)?void 0:n.identifier)!==t.identifier||this.flushFrontBuffer(r+.25)}let h,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(h=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${i+1}/${s?1:e} ${t}${h?` live-start: ${o} start-offset: ${h}`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const a=this.assetListLoader.loadAssetList(t,h);a&&(t.assetListLoader=a)}return null}flushFrontBuffer(t){const i=this.requiredTracks;i&&(this.log(`Removing front buffer starting at ${t}`),Object.keys(i).forEach((i=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:i})})))}getAssetPlayerQueueIndex(t){const i=this.playerQueue;for(let s=0;s<i.length;s++)if(t===i[s].assetId)return s;return-1}getAssetPlayer(t){const i=this.getAssetPlayerQueueIndex(t);return this.playerQueue[i]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:i}=this;if(i)for(let s=0;s<t.length;s++)if(t[s].media===i)return t[s];return null}createAsset(t,i,s,e,n,r){const h={parentIdentifier:t.identifier,identifier:Gr(t,r,i),duration:n,startOffset:s,timelineStart:e,uri:r};return this.createAssetPlayer(t,h,i)}createAssetPlayer(t,i,s){const e=this.hls,n=e.userConfig;let r=n.videoPreference;const h=e.loadLevelObj||e.levels[e.currentLevel];(r||h)&&(r=x({},r),h.videoCodec&&(r.videoCodec=h.videoCodec),h.videoRange&&(r.allowedVideoRanges=[h.videoRange]));const o=e.audioTracks[e.audioTrack],a=e.subtitleTracks[e.subtitleTrack];let l=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-i.timelineStart;if(t>1){const s=i.duration;s&&t<s&&(l=t)}}const u=i.identifier,c=D(D({},n),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:e.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:e.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:r,audioPreference:o||n.audioPreference,subtitlePreference:a||n.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,i.timelineStart&&(c.timelineOffset=i.timelineStart));const d=c.cmcd;null!=d&&d.sessionId&&d.contentId&&(c.cmcd=x({},d,{contentId:Br(i.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${t} and asset ${u}`);const f=new zr(this.HlsPlayerClass,c,t,i);this.playerQueue.push(f),t.assetList[s]=i;const v=e=>{if(e.live){const i=new Error(`Interstitials MUST be VOD assets ${t}`);return void this.handleAssetItemError({fatal:!0,type:p.OTHER_ERROR,details:m.INTERSTITIAL_ASSET_ITEM_ERROR,error:i},t,this.schedule.findEventIndex(t.identifier),s,i.message)}const n=e.edge-e.fragmentStart,r=i.duration;(null===r||n>r)&&(this.log(`Interstitial asset "${u}" duration change ${r} > ${n}`),i.duration=n,this.updateSchedule())};f.on(y.LEVEL_UPDATED,((t,{details:i})=>v(i))),f.on(y.LEVEL_PTS_UPDATED,((t,{details:i})=>v(i)));const g=(t,i)=>{const s=this.getAssetPlayer(u);if(s&&i.tracks){s.off(y.BUFFER_CODECS,g),s.tracks=i.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};f.on(y.BUFFER_CODECS,g);const b=()=>{var s;const e=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${e}`),!e)return;const n=this.schedule.findEventIndex(t.identifier),r=null==(s=this.schedule.items)?void 0:s[n];if(this.isInterstitial(r)){const s=t.findAssetIndex(i),e=Xr(t,s);if(t.isAssetPastPlayoutLimit(e)){var h;const t=null==(h=this.schedule.items)?void 0:h[n+1];t&&this.bufferedToItem(t)}else this.bufferedToItem(r,e)}};f.on(y.BUFFERED_TO_END,b);const w=i=>()=>{if(!this.getAssetPlayer(u))return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,i)};return f.once(y.MEDIA_ENDED,w(s)),f.once(y.PLAYOUT_LIMIT_REACHED,w(1/0)),f.on(y.ERROR,((i,e)=>{const n=this.getAssetPlayer(u);if(e.details!==m.BUFFER_STALLED_ERROR)this.handleAssetItemError(e,t,this.schedule.findEventIndex(t.identifier),s,`Asset player error ${e.error} ${t}`);else if(null!=n&&n.media){const i=n.currentTime,s=n.duration-i;i&&t.appendInPlace&&s/n.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${u} ${t} at ${n.media.currentTime}`),b()):(this.warn(`Stalled at ${i} of ${i+s} in asset ${u} ${t}`),this.onTimeupdate(),this.checkBuffer(!0))}})),f.on(y.DESTROYING,(()=>{if(!this.getAssetPlayer(u))return;const i=new Error(`Asset player destroyed unexpectedly ${u}`);this.handleAssetItemError({fatal:!0,type:p.OTHER_ERROR,details:m.INTERSTITIAL_ASSET_ITEM_ERROR,error:i},t,this.schedule.findEventIndex(t.identifier),s,i.message)})),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Wr(i)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:i,assetListIndex:s,event:t,player:f}),f}clearInterstitial(t,i){t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,i)})),t.reset()}resetAssetPlayer(t){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){this.log(`reset asset player "${t}" after error`);const s=this.playerQueue[i];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(t,i){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){this.log(`clear asset player "${t}" toSegment: ${i?Yr(i):i}`);const e=this.playerQueue[s];this.transferMediaFromPlayer(e,i),this.playerQueue.splice(s,1),e.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,i,s,e,n){const{interstitial:r,assetItem:h,assetId:o}=t,a=r.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=h,l&&l.identifier===o||(l&&(this.clearAssetPlayer(l.identifier,s[e]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${i+1}/${a} ${Wr(h)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:h,assetListIndex:i,event:r,schedule:s.slice(0),scheduleIndex:e,player:t})),this.bufferAssetPlayer(t,n)}bufferAssetPlayer(t,i){var s,e;const{interstitial:n,assetItem:r}=t,h=this.schedule.findEventIndex(n.identifier),o=null==(s=this.schedule.items)?void 0:s[h];if(!o)return;this.setBufferingItem(o),this.bufferingAsset=r;const a=this.getBufferingPlayer();if(a===t)return;const l=n.appendInPlace;if(l&&!1===(null==a?void 0:a.interstitial.appendInPlace))return;const u=(null==a?void 0:a.tracks)||(null==(e=this.detachedData)?void 0:e.tracks)||this.requiredTracks;if(l&&r!==this.playingAsset){if(!t.tracks)return;if(u&&!_(u,t.tracks)){const i=new Error(`Asset ${Wr(r)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),s={fatal:!0,type:p.OTHER_ERROR,details:m.INTERSTITIAL_ASSET_ITEM_ERROR,error:i},e=n.findAssetIndex(r);return void this.handleAssetItemError(s,n,h,e,i.message)}}this.transferMediaTo(t,i)}handleAssetItemError(t,i,s,e,n){if(t.details===m.BUFFER_STALLED_ERROR)return;const r=i.assetList[e];this.warn(`INTERSTITIAL_ASSET_ERROR ${r?Wr(r):r} ${t.error}`);const h=null==r?void 0:r.identifier,o=this.getAssetPlayerQueueIndex(h),a=this.playerQueue[o]||null,l=this.schedule.items,u=x({},t,{fatal:!1,errorAction:Ti(!0),asset:r,assetListIndex:e,event:i,schedule:l,scheduleIndex:s,player:a});if(this.hls.trigger(y.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const c=this.playingAsset,d=new Error(n);if(r&&(this.clearAssetPlayer(h,null),r.error=d),i.assetList.some((t=>!t.error))){for(let t=e;t<i.assetList.length;t++)this.resetAssetPlayer(i.assetList[t].identifier);this.updateSchedule()}else i.error=d;i.error?this.primaryFallback(i):c&&c.identifier===h&&this.advanceAfterAssetEnded(i,s,e)}primaryFallback(t){const i=t.timelineStart,s=this.effectivePlayingItem;if(this.updateSchedule(),s){this.log(`Fallback to primary from event "${t.identifier}" start: ${i} pos: ${this.timelinePos} playing: ${s?Yr(s):"<none>"} error: ${t.error}`);let e=this.timelinePos;-1===e&&(e=this.hls.startPosition);const n=this.updateItem(s,e);this.itemsMatch(s,n)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(i,null),this.flushFrontBuffer(i));const r=this.schedule.findItemIndexAtTime(e);this.setSchedulePosition(r)}else this.checkStart()}onAssetListLoaded(t,i){var s;const e=i.event,n=e.identifier,r=i.assetListResponse.ASSETS;if(!this.schedule.hasEvent(n))return;const h=e.timelineStart,o=e.duration;let a=0;r.forEach(((t,i)=>{const s=parseFloat(t.DURATION);this.createAsset(e,i,a,h+a,s,t.URI),a+=s})),e.duration=a,this.log(`Loaded asset-list with duration: ${a} (was: ${o}) ${e}`);const l=this.waitingItem,u=(null==l?void 0:l.event.identifier)===n;this.updateSchedule();const c=null==(s=this.bufferingItem)?void 0:s.event;if(u){var d;const t=this.schedule.findEventIndex(n),i=null==(d=this.schedule.items)?void 0:d[t];if(i){if(!this.playingItem&&this.timelinePos>i.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return e.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${e}`),void this.primaryFallback(e);this.setBufferingItem(i)}this.setSchedulePosition(t)}else if((null==c?void 0:c.identifier)===n&&c.appendInPlace){const t=e.assetList[0],i=this.getAssetPlayer(t.identifier),s=this.primaryMedia;t&&i&&s&&this.bufferAssetPlayer(i,s)}}onError(t,i){switch(i.details){case m.ASSET_LIST_PARSING_ERROR:case m.ASSET_LIST_LOAD_ERROR:case m.ASSET_LIST_LOAD_TIMEOUT:{const t=i.interstitial;t&&this.primaryFallback(t);break}case m.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}}}});function io(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(io):Object.keys(t).reduce(((i,s)=>(i[s]=io(t[s]),i)),{}):t}class so extends Gi{constructor(t,i){super("gap-controller",t.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=i,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,i){this.setInterval(100),this.mediaSource=i.mediaSource;const s=this.media=i.media;Ir(s,"playing",this.onMediaPlaying),Ir(s,"waiting",this.onMediaWaiting),Ir(s,"ended",this.onMediaEnded)}onMediaDetaching(t,i){this.clearInterval();const{media:s}=this;s&&(Dr(s,"playing",this.onMediaPlaying),Dr(s,"waiting",this.onMediaWaiting),Dr(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,i){this.buffered=i.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const i=this.media.currentTime;this.poll(i,this.lastCurrentTime),this.lastCurrentTime=i}poll(t,i){var s,e;const n=null==(s=this.hls)?void 0:s.config;if(!n)return;const r=this.media;if(!r)return;const{seeking:h}=r,o=this.seeking&&!h,a=!this.seeking&&h,l=r.paused&&!h||r.ended||0===r.playbackRate;if(this.seeking=h,t!==i)return i&&(this.ended=0),this.moved=!0,h||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!l&&t>i&&this.nudgeOnVideoHole(t,i)),void(0===this.waiting&&this.stallResolved(t));if(a||o)return void(o&&this.stallResolved(t));if(l)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&r.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})));if(!Vi.getBuffered(r).length)return void(this.nudgeRetry=0);const u=Vi.bufferInfo(r,t,0),c=u.nextStart||0,d=this.fragmentTracker;if(h&&d&&this.hls){const i=eo(this.hls.inFlightFragments,t),s=u.len>2,e=!c||i||c-t>2&&!d.getPartialFragment(t);if(s||e)return;this.moved=!1}const f=null==(e=this.hls)?void 0:e.latestLevelDetails;if(!this.moved&&null!==this.stalled&&d){if(!(u.len>0||c))return;const i=Math.max(c,u.start||0)-t,s=null!=f&&f.live?2*f.targetduration:2,e=d.getPartialFragment(t);if(i>0&&(i<=s||e))return void(r.paused||this._trySkipBufferHole(e))}const v=n.detectStallWithCurrentTimeMs,g=self.performance.now(),p=this.waiting;let m=this.stalled;if(null===m){if(!(p>0&&g-p<v))return void(this.stalled=g);m=this.stalled=p}const b=g-m;if(!h&&(b>=v||p)&&this.hls){var w;if("ended"===(null==(w=this.mediaSource)?void 0:w.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(y.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}const $=Vi.bufferInfo(r,t,n.maxBufferHole);this._tryFixBufferStall($,b,t)}stallResolved(t){const i=this.stalled;if(i&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-i;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,i){var s;const e=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&e&&e.length>1&&t>e.end(0)){const s=Vi.bufferedInfo(Vi.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&i>=s.start){const s=Vi.timeRangesToArray(e),n=Vi.bufferedInfo(s,i,0).bufferedIndex;if(n>-1&&n<s.length-1){const i=Vi.bufferedInfo(s,t,0).bufferedIndex,e=s[n].end,r=s[n+1].start;if((-1===i||i>n)&&r-e<1&&t-e<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${e} -> ${r} buffered index: ${i}`);this.warn(s.message),this.media.currentTime+=1e-6;const n=this.fragmentTracker.getPartialFragment(t)||void 0,h=Vi.bufferInfo(this.media,t,0);this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:n,buffer:h.len,bufferInfo:h})}}}}}_tryFixBufferStall(t,i,s){var e,n;const{fragmentTracker:r,media:h}=this,o=null==(e=this.hls)?void 0:e.config;if(!h||!r||!o)return;const a=null==(n=this.hls)?void 0:n.latestLevelDetails,l=r.getPartialFragment(s);if((l||null!=a&&a.live&&s<a.fragmentStart)&&(this._trySkipBufferHole(l)||!this.media))return;const u=t.buffered,c=this.adjacentTraversal(t,s);(u&&u.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-s<o.maxBufferHole||c))&&(i>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,i){const s=this.fragmentTracker,e=t.nextStart;if(s&&e){const t=s.getFragAtPos(i,S),n=s.getFragAtPos(e,S);if(t&&n)return n.sn-t.sn<2}return!1}_reportStall(t){const{hls:i,media:s,stallReported:e,stalled:n}=this;if(!e&&null!==n&&s&&i){this.stallReported=!0;const e=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ri(t)})`);this.warn(e.message),i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_STALLED_ERROR,fatal:!1,error:e,buffer:t.len,bufferInfo:t,stalled:{start:n}})}}_trySkipBufferHole(t){var i;const{fragmentTracker:s,media:e}=this,n=null==(i=this.hls)?void 0:i.config;if(!e||!s||!n)return 0;const r=e.currentTime,h=Vi.bufferInfo(e,r,0),o=r<h.start?h.start:h.nextStart;if(o&&this.hls){const i=o-r;if(i>0&&(h.len<=n.maxBufferHole||h.len>0&&h.len<1&&e.readyState<3)){if(i>n.maxBufferHole){let i=!1;if(0===r){const t=s.getAppendedFrag(0,S);t&&o<t.end&&(i=!0)}if(!i){const i=t||s.getAppendedFrag(r,S);if(i){var a;if(null==(a=this.hls.loadLevelObj)||!a.details)return 0;if(eo(this.hls.inFlightFragments,o))return 0;let t=!1,e=i.end;for(;e<o;){const i=s.getAppendedFrag(e,S)||s.getPartialFragment(e);if(!i){t=!0;break}e+=i.duration}if(t)return 0}}}const l=Math.max(o+.05,r+.1);if(this.warn(`skipping hole, adjusting currentTime from ${r} to ${l}`),this.moved=!0,e.currentTime=l,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${l}`);this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:t||void 0,buffer:h.len,bufferInfo:h})}return l}}return 0}_tryNudgeBuffer(t){const{hls:i,media:s,nudgeRetry:e}=this,n=null==i?void 0:i.config;if(!s||!n)return 0;const r=s.currentTime;if(this.nudgeRetry++,e<n.nudgeMaxRetry){const h=r+(e+1)*n.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${h}`);this.warn(o.message),s.currentTime=h,i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const s=new Error(`Playhead still not moving while enough data buffered @${r} after ${n.nudgeMaxRetry} nudges`);this.error(s.message),i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:t.len,bufferInfo:t})}}}function eo(t,i){const s=no(t.main);if(s&&s.start<=i)return s;const e=no(t.audio);return e&&e.start<=i?e:null}function no(t){if(!t)return null;switch(t.state){case te.IDLE:case te.STOPPED:case te.ENDED:case te.ERROR:return null}return t.frag}function ro(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ho(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,ri(n?D({type:n},e):e))}return r}const oo=(()=>{const t=ro();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ao{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(t,i){var s;this.media=i.media,!1===(null==(s=i.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const t=this.hls.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(t,i){this.media=null,i.transferMedia||(this.id3Track&&(this.removeCues&&Nr(this.id3Track,this.onEventCueEnter),this.id3Track=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 Rr(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=ro();if(r)for(let t=0;t<n.length;t++){const i=n[t].type;if(i===Pe.emsg&&!s||!e)continue;const h=Me(n[t].data);if(h){const s=n[t].pts;let e=s+n[t].duration;e>oo&&(e=oo),e-s<=0&&(e=s+.25);for(let t=0;t<h.length;t++){const n=h[t];if(!xe(n)){this.updateId3CueEnds(s,i);const t=ho(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===oo&&(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===Pe.audioId3&&o:"video"===e?t=>t.type===Pe.emsg&&h:t=>t.type===Pe.audioId3&&o||t.type===Pe.emsg&&h,Ur(n,i,s,t)}}onLevelUpdated(t,{details:i}){this.updateDateRangeCues(i,!0)}onLevelPtsUpdated(t,i){Math.abs(i.drift)>.01&&this.updateDateRangeCues(i.details)}updateDateRangeCues(t,i){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:e}=t,n=Object.keys(e);let r=this.dateRangeCuesAppended;var h;if(s&&i)if(null!=(h=s.cues)&&h.length){const t=Object.keys(r).filter((t=>!n.includes(t)));for(let i=t.length;i--;){const e=t[i],n=r[e].cues;delete r[e],Object.keys(n).forEach((t=>{try{const i=n[t];i.removeEventListener("enter",this.onEventCueEnter),s.removeCue(i)}catch(t){}}))}}else r=this.dateRangeCuesAppended={};const o=t.fragments[t.fragments.length-1];if(0===n.length||!f(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ro();for(let t=0;t<n.length;t++){const i=n[t],s=e[i],h=s.startTime,o=r[i],u=(null==o?void 0:o.cues)||{};let c=(null==o?void 0:o.durationKnown)||!1,d=oo;const{duration:f,endDate:v}=s;if(v&&null!==f)d=h+f,c=!0;else if(s.endOnNext&&!c){const t=n.reduce(((t,i)=>{if(i!==s.id){const n=e[i];if(n.class===s.class&&n.startDate>s.startDate&&(!t||s.startDate<t.startDate))return n}return t}),null);t&&(d=t.startTime,c=!0)}const g=Object.keys(s.attr);for(let t=0;t<g.length;t++){const e=g[t];if("ID"===(l=e)||"CLASS"===l||"CUE"===l||"START-DATE"===l||"DURATION"===l||"END-DATE"===l||"END-ON-NEXT"===l)continue;const n=u[e];if(n)c&&!o.durationKnown?n.endTime=d:Math.abs(n.startTime-h)>.01&&(n.startTime=h,n.endTime=d);else if(a){let t=s.attr[e];ts(e)&&(t=Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const n=ho(a,h,d,{key:e,data:t},Pe.dateRange);n&&(n.id=i,this.id3Track.addCue(n),u[e]=n,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==e&&"X-ASSET-URL"!==e||n.addEventListener("enter",this.onEventCueEnter)))}}r[i]={cues:u,dateRange:s,durationKnown:c}}var l}}class lo{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;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,e=Math.min(i,Math.max(1,s));this.changeMediaPlaybackRate(t,e)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)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(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===a)&&(a=void 0!==n?n:r*e),a+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,e)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),i=this.targetLatency;if(null===t||null===i)return null;const s=this.levelDetails;if(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 t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;return null===t?0:Math.max(t.age-3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration),0)}get forwardBufferLength(){const{media:t}=this,i=this.levelDetails;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.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.ERROR,this.onError,this))}onMediaAttached(t,i){this.media=i.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:i}){i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,i){var s;i.details===m.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,i){var s,e;t.playbackRate!==i&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(e=this.targetLatency)?void 0:e.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${i}`),t.playbackRate=i)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class uo extends Cn{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.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=>{const i=t.attrs;let{audioCodec:l,videoCodec:u}=t;l&&(t.audioCodec=l=jt(l,s)||void 0),u&&(u=t.videoCodec=function(t){const i=t.split(",");for(let t=0;t<i.length;t++){const s=i[t].split(".");s.length>2&&"avc1"===s[0]&&(i[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return i.join(",")}(u));const{width:c,height:d,unknownCodecs:f}=t;let v=f?f.length:0;if(f)for(let i=v;i--;){const s=f[i];this.isAudioSupported(s)?(t.audioCodec=l=l?`${l},${s}`:s,v--,Pt.audio[l.substring(0,4)]=2):this.isVideoSupported(s)&&(t.videoCodec=u=u?`${u},${s}`:s,v--,Pt.video[u.substring(0,4)]=2)}if(h||(h=!(!c||!d)),o||(o=!!u),a||(a=!!l),v||l&&!this.isAudioSupported(l)||u&&!this.isVideoSupported(u))return void this.log(`Some or all CODECS not supported "${i.CODECS}"`);const{CODECS:g,"FRAME-RATE":p,"HDCP-LEVEL":m,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":w}=i,$=`${y||"."}-${t.bitrate}-${b}-${p}-${g}-${w}-${m}`;if(n[$])if(n[$].uri===t.url||t.attrs["PATHWAY-ID"])n[$].addGroupId("audio",i.AUDIO),n[$].addGroupId("text",i.SUBTITLES);else{const i=r[$]+=1;t.attrs["PATHWAY-ID"]=new Array(i+1).join(".");const s=this.createLevel(t);n[$]=s,e.push(s)}else{const i=this.createLevel(t);n[$]=i,r[$]=1,e.push(i)}})),this.filterAndSortMediaOptions(e,i,h,o,a)}createLevel(t){const i=new ei(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),i.supportedResult=zt(t,[])}return i}isAudioSupported(t){return Rt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Rt(t,"video",this.hls.config.preferManagedMediaSource)}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)&&ti.indexOf(n)>-1;var n}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;i.levels.length&&(s=`one or more CODECS in variant not supported: ${ri(i.levels.map((t=>t.attrs.CODECS)).filter(((t,i,s)=>s.indexOf(t)===i)))}`,this.warn(s),t+=` (${s})`);const e=new Error(t);this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:i.url,error:e,reason:s})}}));i.audioTracks&&(r=i.audioTracks.filter((t=>!t.audioCodec||this.isAudioSupported(t.audioCodec))),co(r)),i.subtitles&&(h=i.subtitles,co(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 ti.indexOf(t.videoRange)-ti.indexOf(i.videoRange);if(t.videoCodec!==i.videoCodec){const s=Ut(t.videoCodec),e=Ut(i.videoCodec);if(s!==e)return e-s}if(t.uri===i.uri&&t.codecSet!==i.codecSet){const s=Ft(t.codecSet),e=Ft(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 u;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==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const t=Math.min(i,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const c=this.hls.config,d={levels:o,audioTracks:r,subtitleTracks:h,sessionData:i.sessionData,sessionKeys:i.sessionKeys,firstLevel:this._firstLevel,stats:i.stats,audio:n,video:e,altAudio:!(!c.audioStreamController||!c.audioTrackController)&&!(n&&!e)&&r.some((t=>!!t.url))};this.hls.trigger(y.MANIFEST_PARSED,d)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}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(y.ERROR,{type:p.OTHER_ERROR,details:m.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&&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(y.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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const i=this.steering.pathways(),s=t.filter((t=>-1!==i.indexOf(t)));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${i}`);this.steering.pathwayPriority=s}}onError(t,i){!i.fatal&&i.context&&i.context.type===w&&i.context.level===this.level&&this.checkRetry(i)}onFragBuffered(t,{frag:i}){if(void 0!==i&&i.type===S){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=i.levelInfo;var h;if(!r)return this.warn(`Invalid level index ${e}`),void(null!=(h=i.deliveryDirectives)&&h.skip&&(n.deltaUpdateFailed=!0));if(r===this.currentLevel||i.withoutMultiVariant){0===r.fragmentError&&(r.loadError=0);let t=r.details;t===i.details&&t.advanced&&(t=void 0),this.playlistLoaded(e,i,t)}else null!=(s=i.deliveryDirectives)&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,i){super.loadingPlaylist(t,i);const s=this.getUrlWithDirectives(t.uri,i),e=this.currentLevelIndex,n=t.attrs["PATHWAY-ID"],r=t.details,h=null==r?void 0:r.age;this.log(`Loading level index ${e}${void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:""}${n?" Pathway "+n:""}${h&&r.live?" age "+h.toFixed(1)+(r.type&&" "+r.type||""):""} ${s}`),this.hls.trigger(y.LEVEL_LOADING,{url:s,level:e,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||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;if(1===this._levels.length)return;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)));zs(s),this._levels=s,this.currentLevelIndex>-1&&null!=(i=this.currentLevel)&&i.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const e=s.length-1;this._firstLevel=Math.min(this._firstLevel,e),this._startLevel&&(this._startLevel=Math.min(this._startLevel,e)),this.hls.trigger(y.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(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function co(t){const i={};t.forEach((t=>{const s=t.groupId||"";t.id=i[s]=i[s]||0,i[s]++}))}function fo(){return self.SourceBuffer||self.WebKitSourceBuffer}function vo(){if(!B())return!1;const t=fo();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class go extends ie{constructor(t,i,s){super(t,i,s,"stream-controller",S),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,i=t?t.currentTime:null;if(null===i||!f(i))return;if(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i))return;const s=this.getFwdBufferInfoAtPos(t,i,S,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${i} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(y.BUFFER_CREATED,this.onBufferCreated,this),t.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(y.BUFFER_CREATED,this.onBufferCreated,this),t.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,i){if(this.levels){const{lastCurrentTime:s,hls:e}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=e.startLevel;-1===t&&(e.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=e.firstAutoLevel),e.nextLoadLevel=t,this.level=e.loadLevel,this._hasEnoughToStart=!!i}s>0&&-1===t&&!i&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=te.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=i?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=te.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case te.WAITING_LEVEL:{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&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(e))break;this.state=te.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=te.IDLE;break}break}case te.FRAG_LOADING_WAITING_RETRY:{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=te.IDLE}}}this.state===te.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:i,levels:s,media:e}=this;if(null===i||!e&&!this.primaryPrefetch&&(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 2===this.altAudio&&(t.type="video"),this.hls.trigger(y.BUFFER_EOS,t),void(this.state=te.ENDED)}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===te.WAITING_LEVEL||this.waitForLive(r))return this.level=n,this.state=te.WAITING_LEVEL,void(this.startFragRequested=!1);const l=h.len,u=this.getMaxBufferLength(r.maxBitrate);if(l>=u)return;this.backtrackFragment&&this.backtrackFragment.start>h.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:h.end;let d=this.getNextFragment(c,a);if(this.couldBacktrack&&!this.fragPrevious&&d&&et(d)&&this.fragmentTracker.getState(d)!==Mi){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,c)){if(!d.gap){const t=this.audioOnly&&!this.altAudio?Z:tt,i=(t===tt?this.videoBuffer:this.mediaBuffer)||this.media;i&&this.afterBufferFlushed(i,t,S)}d=this.getNextFragmentLoopLoading(d,a,h,S,u)}d&&(!d.initSegment||d.initSegment.data||this.bitrateTest||(d=d.initSegment),this.loadFragment(d,r,c))}loadFragment(t,i,s){const e=this.fragmentTracker.getState(t);e===Ei||e===Li?et(t)?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)):super.loadFragment(t,i,s):this._loadInitSegment(t,i):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,S)}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 te.KEY_LOADING:case te.FRAG_LOADING:case te.FRAG_LOADING_WAITING_RETRY:case te.PARSING:case te.PARSED:this.state=te.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,i){super.flushMainBuffer(t,i,2===this.altAudio?"video":null)}onMediaAttached(t,i){super.onMediaAttached(t,i);const s=i.media;Ir(s,"playing",this.onMediaPlaying),Ir(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,i){const{media:s}=this;s&&(Dr(s,"playing",this.onMediaPlaying),Dr(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,i),i.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!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=fo();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!==te.IDLE)return;const e=i.levelInfo;(!e.details||e.details.live&&(this.levelLastLoaded!==e||e.details.expired)||this.waitForCdnTuneIn(e.details))&&(this.state=te.WAITING_LEVEL)}onLevelLoaded(t,i){var s;const{levels:e,startFragRequested:n}=this,r=i.level,h=i.details,o=h.totalduration;if(!e)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${h.startSN},${h.endSN}]${h.lastPartSn?`[part-${h.lastPartSn}-${h.lastPartIndex}]`:""}, cc [${h.startCC}, ${h.endCC}] duration:${o}`);const a=i.levelInfo,l=this.fragCurrent;!l||this.state!==te.FRAG_LOADING&&this.state!==te.FRAG_LOADING_WAITING_RETRY||l.level!==i.level&&l.loader&&this.abortCurrentFrag();let u=0;if(h.live||null!=(s=a.details)&&s.live){var c;if(this.checkLiveUpdate(h),h.deltaUpdateFailed)return;u=this.alignPlaylists(h,a.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(a.details=h,this.levelLastLoaded=a,n||this.setStartPosition(h,u),this.hls.trigger(y.LEVEL_UPDATED,{details:h,level:r}),this.state===te.WAITING_LEVEL){if(this.waitForCdnTuneIn(h))return;this.state=te.IDLE}n&&h.live&&this.synchronizeToLiveEdge(h),this.tick()}synchronizeToLiveEdge(t){const{config:i,media:s}=this;if(!s)return;const e=this.hls.liveSyncPosition,n=this.getLoadPosition(),r=t.edge,h=n>=t.fragmentStart-i.maxFragLookUpTolerance&&n<=r;if(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._hasEnoughToStart||(this.nextLoadPosition=e),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${r}, reset currentTime to : ${e.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var o;const t=Vi.bufferInfo(s,e,0);if(null==t||null==(o=t.buffered)||!o.length)return void(s.currentTime=e);if(t.start<=n)return void(s.currentTime=e);const{nextStart:i}=Vi.bufferedInfo(t.buffered,n,0);i&&(s.currentTime=i)}else s.currentTime=e}_handleFragmentLoadProgress(t){var i;const s=t.frag,{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];if(!h)return void this.warn(`Level ${s.level} not found on progress`);const 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,u=null==(i=s.initSegment)?void 0:i.data,c=this._getAudioCodec(h),d=this.transmuxer=this.transmuxer||new Pn(this.hls,S,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=e?e.index:-1,v=new Hi(s.level,s.sn,s.stats.chunkCount,n.byteLength,f,-1!==f);d.push(n,u,c,a,s,e,o.totalduration,l,v,this.initPTS[s.cc])}onAudioTrackSwitching(t,i){const s=this.hls,e=2===this.altAudio;if(fi(i.url,s))this.altAudio=1;else{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();if(e)return this.fragmentTracker.removeAllFragments(),s.once(y.BUFFER_FLUSHED,(()=>{var t;null==(t=this.hls)||t.trigger(y.AUDIO_TRACK_SWITCHED,i)})),void s.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(y.AUDIO_TRACK_SWITCHED,i)}}onAudioTrackSwitched(t,i){const s=fi(i.url,this.hls);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?2:0,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,n=s.type===S;if(n){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===te.PARSED&&(this.state=te.IDLE));const t=e?e.stats:s.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),et(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,e)}const r=this.media;r&&(!this._hasEnoughToStart&&Vi.getBuffered(r).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,i){var s;if(i.fatal)this.state=te.ERROR;else switch(i.details){case m.FRAG_GAP:case m.FRAG_PARSING_ERROR:case m.FRAG_DECRYPT_ERROR:case m.FRAG_LOAD_ERROR:case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_ERROR:case m.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(S,i);break;case m.LEVEL_LOAD_ERROR:case m.LEVEL_LOAD_TIMEOUT:case m.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==te.WAITING_LEVEL||(null==(s=i.context)?void 0:s.type)!==w||(this.state=te.IDLE);break;case m.BUFFER_ADD_CODEC_ERROR:case m.BUFFER_APPEND_ERROR:if("main"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&this.resetLoadingState();break;case m.BUFFER_FULL_ERROR:if("main"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case m.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}onFragLoadEmergencyAborted(){this.state=te.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:i}){if(i!==Z||!this.altAudio){const t=(i===tt?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,i,S),this.tick())}}onLevelsUpdated(t,i){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),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=this.timelineOffset;e&&s&&(s+=e);const n=this.getLevelDetails(),r=Vi.getBuffered(t),h=r.length?r.start(0):0,o=h-s,a=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<a||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),i<s&&(this.log(`seek to target start position ${s} from current time ${i} buffer start ${h}`),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((t=>{const{hls:s}=this,e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e))return;i.fragmentError=0,this.state=te.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(y.FRAG_LOADED,t),e.bitrateTest=!1}))}_handleTransmuxComplete(t){var i;const s=this.playlistType,{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:u,text:c,id3:d,initSegment:v}=n,{details:g}=l,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=te.PARSING,v){if(null!=v&&v.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,v.tracks,t,r),e.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:v.tracks})}const t=v.initPTS,i=v.timescale,n=this.initPTS[o.cc];!f(t)||n&&n.baseTime===t&&n.timescale===i||(this.initPTS[o.cc]={baseTime:t,timescale:i},e.trigger(y.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:i}))}if(u&&g){p&&"audiovideo"===u.type&&this.logMuxedErr(o);const t=g.fragments[o.sn-1-g.startSN],i=o.sn===g.startSN,s=!t||o.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:e,startDTS:n,endDTS:h}=u;if(a)a.elementaryStreams[u.type]={startPTS:t,endPTS:e,startDTS:n,endDTS:h};else if(u.firstKeyFrame&&u.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),u.dropped&&u.independent){const n=this.getMainFwdBufferInfo(),r=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole;if(!i&&r<(u.firstKeyFramePTS?u.firstKeyFramePTS:t)-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,e,o.start,h,!0)}else i&&t-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,t,e,n,h),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,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[Z]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(Z,t,i,s,e),this.bufferFragmentData(p,o,a,r)}g&&null!=d&&null!=(i=d.samples)&&i.length&&e.trigger(y.FRAG_PARSING_METADATA,{id:s,frag:o,details:g,samples:d.samples}),g&&c&&e.trigger(y.FRAG_PARSING_USERDATA,{id:s,frag:o,details:g,samples:c.samples})}}logMuxedErr(t){this.warn(`${et(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,i,s,e){if(this.state!==te.PARSING)return;this.audioOnly=!!i.audio&&!i.video,this.altAudio&&!this.audioOnly&&(delete i.audio,i.audiovideo&&this.logMuxedErr(s));const{audio:n,video:r,audiovideo:h}=i;if(n){const s=t.audioCodec;let e=Gt(n.codec,s);"mp4a"===e&&(e="mp4a.40.5");const r=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=n.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===r.indexOf("firefox")&&(e="mp4a.40.5")}e&&-1!==e.indexOf("mp4a.40.5")&&-1!==r.indexOf("android")&&"audio/mpeg"!==n.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),s&&s!==e&&this.log(`Swapping manifest audio codec "${s}" for "${e}"`),n.levelCodec=e,n.id=S,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${e||""}/${s||""}/${n.codec}]`),delete i.audiovideo}if(r){r.levelCodec=t.videoCodec,r.id=S;const s=r.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":r.codec="hvc1.1.6.L120.90";break;case"av01":r.codec="av01.0.04M.08";break;case"avc1":r.codec="avc1.42e01e"}this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s}]${r.codec!==s?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.supplemental:""}`),delete i.audiovideo}h&&(this.log(`Init audiovideo buffer, container:${h.container}, codecs[level/parsed]=[${t.codecs}/${h.codec}]`),delete i.video,delete i.audio);const o=Object.keys(i);if(o.length){if(this.hls.trigger(y.BUFFER_CODECS,i),!this.hls)return;o.forEach((t=>{const n=i[t].initSegment;null!=n&&n.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:t,data:n,frag:s,part:null,chunkMeta:e,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media,S)}get maxBufferLength(){const{levels:t,level:i}=this,s=null==t?void 0:t[i];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}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=te.IDLE}checkFragmentChanged(){const t=this.media;let i=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(Vi.isBuffered(t,s)?i=this.getAppendedFrag(s):Vi.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(y.FRAG_CHANGED,{frag:i}),t&&t.level===s||this.hls.trigger(y.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return f(i)?this.getAppendedFrag(i):null}get currentProgramDateTime(){var t;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(f(i)){const t=this.getLevelDetails(),s=this.currentFrag||(t?gi(null,t.fragments,i):null);if(s){const t=s.programDateTime;if(null!==t)return new Date(t+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 po{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=m.KEY_LOAD_ERROR,s,e,n){return new ji({type:p.NETWORK_ERROR,details:i,fatal:!1,frag:t,response:n,error:s,networkDetails:e})}loadClear(t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length)if(i.length){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))return this.emeController.selectKeySystemFormat(n).then((t=>{if(n.setKeyFormat(t),this.emeController&&this.config.requireKeySystemAccessOnStart){const i=fs(t);if(i)return this.emeController.getKeySystemAccess([i])}}))}}else if(this.config.requireKeySystemAccessOnStart){const t=ps(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}return null}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,m.KEY_LOAD_ERROR,s))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(t,m.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":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(h,t);default:return Promise.reject(this.createKeyLoadError(t,m.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,m.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,m.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),e,D({url:h.url,data:void 0},t)))},onTimeout:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,m.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),e))},onAbort:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,m.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 mo(t){const{type:i}=t;switch(i){case $:return T;case k:return E;default:return S}}function yo(t,i){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=i.url),s}class bo{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_LOADING,this.onLevelLoading,this),t.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,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:b,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,i){const{id:s,level:e,pathwayId:n,url:r,deliveryDirectives:h,levelInfo:o}=i;this.load({id:s,level:e,pathwayId:n,responseType:"text",type:w,url:r,deliveryDirectives:h,levelOrTrack:o})}onAudioTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r,track:h}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:$,url:n,deliveryDirectives:r,levelOrTrack:h})}onSubtitleTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r,track:h}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:k,url:n,deliveryDirectives:r,levelOrTrack:h})}onLevelsUpdated(t,i){const s=this.loaders[w];if(s){const t=s.context;t&&!i.levels.some((i=>i===t.levelOrTrack))&&(s.abort(),delete this.loaders[w])}}load(t){var i;const s=this.hls.config;let e,n=this.getInternalLoader(t);if(n){const i=this.hls.logger,s=n.context;if(s&&s.levelOrTrack===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void i.log(s.url===t.url?`[playlist-loader]: ignore ${t.url} ongoing request`:`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`);i.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(e=t.type===b?s.manifestLoadPolicy.default:x({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),f(null==(i=t.deliveryDirectives)?void 0:i.part)){let i;if(t.type===w&&null!==t.level?i=this.hls.levels[t.level].details:t.type===$&&null!==t.id?i=this.hls.audioTracks[t.id].details:t.type===k&&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=x({},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(),Ls.isMediaPlaylist(r)||s.type!==b?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)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:i},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${i}`),this.hls.startLoad(i))}handleMasterPlaylist(t,i,s,e){const n=this.hls,r=t.data,h=yo(t,s),o=Ls.parseMasterPlaylist(r,h);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,e,i);const{contentSteering:a,levels:l,sessionData:u,sessionKeys:c,startTimeOffset:d,variableList:f}=o;this.variableList=f;const{AUDIO:v=[],SUBTITLES:g,"CLOSED-CAPTIONS":p}=Ls.parseMasterPlaylistMedia(r,h,o);v.length&&(v.some((t=>!t.url))||!l[0].audioCodec||l[0].attrs.AUDIO||(this.hls.logger.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 Zi({}),bitrate:0,url:""}))),n.trigger(y.MANIFEST_LOADED,{levels:l,audioTracks:v,subtitles:g,captions:p,contentSteering:a,url:h,stats:i,networkDetails:e,sessionData:u,sessionKeys:c,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,i,s,e,n){const r=this.hls,{id:h,level:o,type:a}=s,l=yo(t,s),u=f(o)?o:f(h)?h:0,c=mo(s),d=Ls.parseLevelPlaylist(t.data,l,u,c,0,this.variableList);if(a===b){const t={attrs:new Zi({}),bitrate:0,details:d,name:"",url:l};d.requestScheduled=i.loading.start+Ks(d,0),r.trigger(y.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(y.ERROR,{type:p.NETWORK_ERROR,details:m.MANIFEST_PARSING_ERROR,fatal:i.type===b,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===w?r+=`: ${t.level} id: ${t.id}`:t.type!==$&&t.type!==k||(r+=` id: ${t.id} group-id: "${t.groupId}"`);const h=new Error(r);this.hls.logger.warn(`[playlist-loader]: ${r}`);let o=m.UNKNOWN,a=!1;const l=this.getInternalLoader(t);switch(t.type){case b:o=s?m.MANIFEST_LOAD_TIMEOUT:m.MANIFEST_LOAD_ERROR,a=!0;break;case w:o=s?m.LEVEL_LOAD_TIMEOUT:m.LEVEL_LOAD_ERROR,a=!1;break;case $:o=s?m.AUDIO_TRACK_LOAD_TIMEOUT:m.AUDIO_TRACK_LOAD_ERROR,a=!1;break;case k:o=s?m.SUBTITLE_TRACK_LOAD_TIMEOUT:m.SUBTITLE_LOAD_ERROR,a=!1}l&&this.resetInternalLoader(t.type);const u={type:p.NETWORK_ERROR,details:o,fatal:a,url:t.url,loader:l,context:t,error:h,networkDetails:i,stats:n};e&&(u.response=D({url:(null==i?void 0:i.url)||t.url,data:void 0},e)),this.hls.trigger(y.ERROR,u)}handlePlaylistLoaded(t,i,s,e,n,r){const h=this.hls,{type:o,level:a,id:l,groupId:u,deliveryDirectives:c}=e,d=yo(i,e),f=mo(e),v="number"==typeof e.level&&f===S?a:void 0;if(!t.fragments.length){const r=t.playlistParsingError=new Error("No Segments found in Playlist");return void h.trigger(y.ERROR,{type:p.NETWORK_ERROR,details:m.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:r,reason:r.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const g=t.playlistParsingError;if(g){if(this.hls.logger.warn(g),!h.config.ignorePlaylistParsingErrors)return void h.trigger(y.ERROR,{type:p.NETWORK_ERROR,details:m.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:g,reason:g.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s});t.playlistParsingError=null}switch(t.live&&r&&(r.getCacheAge&&(t.ageHeader=r.getCacheAge()||0),r.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case b:case w:h.trigger(y.LEVEL_LOADED,{details:t,levelInfo:e.levelOrTrack||h.levels[0],level:v||0,id:l||0,stats:s,networkDetails:n,deliveryDirectives:c,withoutMultiVariant:o===b});break;case $:h.trigger(y.AUDIO_TRACK_LOADED,{details:t,track:e.levelOrTrack,id:l||0,groupId:u||"",stats:s,networkDetails:n,deliveryDirectives:c});break;case k:h.trigger(y.SUBTITLE_TRACK_LOADED,{details:t,track:e.levelOrTrack,id:l||0,groupId:u||"",stats:s,networkDetails:n,deliveryDirectives:c})}}}class wo{static get version(){return ae}static isMSESupported(){return vo()}static isSupported(){return function(){if(!vo())return!1;const t=B();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(Nt(i,"video"))))||["mp4a.40.2","fLaC"].some((i=>t.isTypeSupported(Nt(i,"audio")))))}()}static getMediaSource(){return B()}static get Events(){return y}static get MetadataSchema(){return Pe}static get ErrorTypes(){return p}static get ErrorDetails(){return m}static get DefaultConfig(){return wo.defaultConfig?wo.defaultConfig:to}static set DefaultConfig(t){wo.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new oe,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const i=this.logger=function(t,i,s){const e=O();if("object"==typeof console&&!0===t||"object"==typeof t){const i=["debug","log","info","warn","error"];i.forEach((i=>{e[i]=N(i,t,s)}));try{e.log('Debug logs enabled for "Hls instance" in hls.js version 1.6.6')}catch(t){return O()}i.forEach((i=>{U[i]=N(i,t)}))}else x(U,e);return e}(t.debug||!1,0,t.assetPlayerId),s=this.config=function(t,i,s){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 e=io(t),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,h=void 0===i[r],o=[];n.forEach((s=>{const n=`${t}Loading${s}`,a=i[n];if(void 0!==a&&h){o.push(n);const t=e[r].default;switch(i[r]={default:t},s){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}}})),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${r}": ${ri(i[r])}`)})),D(D({},e),i)}(wo.DefaultConfig,t,i);this.userConfig=t,s.progressive&&function(t,i){const s=t.loader;s!==qh&&s!==Zh?(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=qh,t.progressive=!0,t.enableSoftwareAES=!0,i.log("[config]: Progressive streaming enabled, using FetchLoader"))}(s,i);const{abrController:e,bufferController:n,capLevelController:r,errorController:h,fpsController:o}=s,a=new h(this),l=this.abrController=new e(this),u=new xi(this),c=s.interstitialsController,d=c?this.interstitialsController=new c(this,wo):null,f=this.bufferController=new n(this,u),v=this.capLevelController=new r(this),g=new o(this),p=new bo(this),m=s.contentSteeringController,b=m?new m(this):null,w=this.levelController=new uo(this,b),$=new ao(this),k=new po(this.config),S=this.streamController=new go(this,u,k),T=this.gapController=new so(this,u);v.setStreamController(S),g.setStreamController(S);const E=[p,w,S];d&&E.splice(1,0,d),b&&E.splice(1,0,b),this.networkControllers=E;const A=[l,f,T,v,g,$,u];this.audioTrackController=this.createController(s.audioTrackController,E);const L=s.audioStreamController;L&&E.push(this.audioStreamController=new L(this,u,k)),this.subtitleTrackController=this.createController(s.subtitleTrackController,E);const M=s.subtitleStreamController;M&&E.push(this.subtititleStreamController=new M(this,u,k)),this.createController(s.timelineController,A),k.emeController=this.emeController=this.createController(s.emeController,A),this.cmcdController=this.createController(s.cmcdController,A),this.latencyController=this.createController(lo,A),this.coreComponents=A,E.push(a);const I=a.onErrorOut;"function"==typeof I&&this.on(y.ERROR,I,a),this.on(y.MANIFEST_LOADED,p.onManifestLoaded,p)}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){this.logger.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(y.ERROR,{type:p.OTHER_ERROR,details:m.INTERNAL_EXCEPTION,fatal:t===y.ERROR,event:t,error:i}),this.triggeringException=!1)}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(y.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){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.ATTACH_MEDIA_ERROR,fatal:!0,error:i})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const i="media"in t,s=i?t.media:t,e=i?t:{media:s};this._media=s,this.trigger(y.MEDIA_ATTACHING,e)}detachMedia(){this.logger.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(y.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const i=this.media,s=this._url,e=this._url=Q.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${e}`),i&&s&&(s!==e||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(y.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,i){this.logger.log(`startLoad(${t+(i?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,i),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((t=>{t.resumeBuffering&&t.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((t=>{t.pauseBuffering&&t.pauseBuffering()})))}get inFlightFragments(){const t={[S]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[T]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[E]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,i=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),i&&this.startLoad(i))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._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)}))}}}()),t}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.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){this.logger.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){this.logger.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 abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Zt.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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var i;return(null==(i=this.audioTrackController)?void 0:i.setAudioOption(t))||null}setSubtitleOption(t){var i;return(null==(i=this.subtitleTrackController)?void 0: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}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,i=this.allAudioTracks){return Yt(t,oi(i),navigator.mediaCapabilities)}}function $o(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")}`}wo.defaultConfig=void 0;var ko=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 So=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.isDragging=!1,this.seekPosition=0,this.isSeeking=!1,this.hideControlsTimeout=null,this.seekingTimeout=null,this.livestreamUpdateListener=t=>{this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=t},this.updateProgress=()=>{this.isSeeking||(this.currentTime=this.videoRef.currentTime)},this.updateHlsStatsPeriodically=()=>{var t,i,s;this.duration=(null===(t=this.videoRef)||void 0===t?void 0:t.seekable)&&this.videoRef.seekable.length>0?this.videoRef.seekable.end(this.videoRef.seekable.length-1):((null===(i=this.videoRef)||void 0===i?void 0:i.currentTime)||0)+((null===(s=this.hls)||void 0===s?void 0:s.latency)||0)},this.fastForwardToLatest=()=>{var t;this.videoRef.currentTime=(null===(t=this.videoRef)||void 0===t?void 0:t.seekable)&&this.videoRef.seekable.length>0?this.videoRef.seekable.end(this.videoRef.seekable.length-1)-1: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.seekToPosition=t=>{if(!this.videoRef)return;const i=Math.max(0,Math.min(t,this.duration));this.isSeeking=!0,this.currentTime=i;try{this.videoRef.currentTime=i,this.seekingTimeout&&clearTimeout(this.seekingTimeout),this.seekingTimeout=setTimeout((()=>{this.isSeeking=!1,this.currentTime=this.videoRef.currentTime}),200)}catch(t){this.isSeeking=!1,this.meeting.__internals__.logger.warn("rtk-livestream-player:: Seek failed",{error:t})}},this.onSeekbarMouseDown=t=>{t.preventDefault(),this.isDragging=!0,this.updateSeekPosition(t),document.addEventListener("mousemove",this.onSeekbarMouseMove),document.addEventListener("mouseup",this.onSeekbarMouseUp)},this.onSeekbarMouseMove=t=>{this.isDragging&&this.updateSeekPosition(t)},this.onSeekbarMouseUp=t=>{this.isDragging&&(this.isDragging=!1,this.updateSeekPosition(t),this.seekToPosition(this.seekPosition),document.removeEventListener("mousemove",this.onSeekbarMouseMove),document.removeEventListener("mouseup",this.onSeekbarMouseUp))},this.onSeekbarClick=t=>{this.isDragging||(this.updateSeekPosition(t),this.seekToPosition(this.seekPosition))},this.updateSeekPosition=t=>{const i=t.currentTarget.getBoundingClientRect(),s=Math.max(0,Math.min(1,(t.clientX-i.left)/i.width));this.seekPosition=s*this.duration},this.getSeekbarProgress=()=>this.isDragging?this.duration>0?this.seekPosition/this.duration:0:this.duration>0?this.currentTime/this.duration:0,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}`),wo.isSupported()?(this.meeting.__internals__.logger.info("rtk-livestream-player:: Initialising HLS. HLS is Supported"),this.hls=new wo({lowLatencyMode:!1}),window.rtk_hls=this.hls,this.meeting.__internals__.logger.info("rtk-livestream-player:: Loading source"),this.hls.loadSource(this.playbackUrl+"?dvrEnabled=true"),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(wo.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+"?dvrEnabled=true"))}),5e3)}else this.meeting.__internals__.logger.warn(`rtk-livestream-player:: non-fatal error: ${i.details}`,{error:i.error})})),this.hls.on(wo.Events.MEDIA_ATTACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media attached")})),this.hls.on(wo.Events.MEDIA_DETACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media detached")})),this.hls.on(wo.Events.DESTROYING,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: hls is getting destroyed")})),this.hls.on(wo.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.seekingTimeout&&clearTimeout(this.seekingTimeout),this.videoRef=null,this.hls&&this.hls.destroy(),window.rtk_hls=null}meetingChanged(t){t&&(this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=this.meeting.livestream.state,this.meeting.livestream.on("livestreamUpdate",this.livestreamUpdateListener))}render(){if(!o(this.meeting))return;const{isError:t,errorMessage:e}=this.getErrorState(),{isLoading:n,loadingMessage:r,showIcon:h}=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"},i("video",{onMouseMove:this.onMouseMovePlayer,ref:async t=>{this.videoRef=t,await this.conditionallyStartLivestreamViewer()},id:"livestream-video",class:"livestream-video",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"},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"},$o(this.currentTime)," /"," ",$o(this.duration))),i("div",{class:"seekbar-container"},i("div",{class:"seekbar",onMouseDown:this.onSeekbarMouseDown,onClick:this.onSeekbarClick},i("div",{class:"seekbar-track"},i("div",{class:"seekbar-progress",style:{width:100*this.getSeekbarProgress()+"%"}}),i("div",{class:"seekbar-handle",style:{left:100*this.getSeekbarProgress()+"%"}})))),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"))),t&&i("div",{class:"loader"},i("rtk-icon",{icon:this.iconPack.warning}),i("p",null,e)),!t&&n&&i("div",{class:"loader"},h&&i("rtk-spinner",{id:"icon",part:"spinner",iconPack:this.iconPack,size:"md"}),i("p",null,r))))}get el(){return n(this)}static get watchers(){return{livestreamState:["updateLivestreamId"],meeting:["meetingChanged"]}}};ko([u()],So.prototype,"meeting",void 0),ko([u()],So.prototype,"t",void 0),ko([u()],So.prototype,"iconPack",void 0),So.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-left:var(--rtk-space-4, 16px);margin-right:var(--rtk-space-4, 16px);margin-top:var(--rtk-space-4, 16px);margin-bottom:var(--rtk-space-0, 0px);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;left:16px;right:16px;display:flex;height:auto;align-items:center;padding:12px 16px;z-index:30;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity));border-radius:6px;border-radius:var(--rtk-border-radius-md, 8px);background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / 0.8);gap:12px}.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;gap:12px;flex-shrink:0}#livestream-video,.livestream-video{position:absolute;top:0;left:0;width:100% !important;height:100% !important;max-width:none !important;max-height:none !important;min-width:100% !important;min-height:100% !important;-o-object-fit:fill !important;object-fit:fill !important;z-index:10;border-radius:var(--rtk-border-radius-md, 8px);border-width:0px}:host:not(:fullscreen) .video-container{padding:16px 16px 0 16px}:host(:fullscreen) .video-container,:host(:-webkit-full-screen) .video-container,:host(:-moz-full-screen) .video-container{padding:0}.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}.seekbar-container{flex:1;min-width:100px;padding:0 12px;display:flex;align-items:center}.seekbar{width:100%;height:20px;cursor:pointer;display:flex;align-items:center}.seekbar-track{position:relative;width:100%;height:4px;border-radius:9999px;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-600, 60 60 60) / var(--tw-bg-opacity))}.seekbar-progress{position:absolute;top:0;left:0;height:100%;border-radius:9999px;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));transition:width 0.1s ease}.seekbar-handle{position:absolute;top:50%;width:12px;height:12px;border-radius:9999px;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));transform:translate(-50%, -50%);transition:left 0.1s ease;opacity:0}.seekbar:hover .seekbar-handle{opacity:1}.seekbar:hover .seekbar-track{height:6px}.seekbar:hover .seekbar-handle{width:14px;height:14px}";var To=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 Eo=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"]}}};To([u()],Eo.prototype,"meeting",void 0),To([u()],Eo.prototype,"iconPack",void 0),To([u()],Eo.prototype,"t",void 0),Eo.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,So as rtk_livestream_player,Eo 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{i as r,e as h,P as o,U as a,V as l}from"./p-25c4d10f.js";import{S as u}from"./p-9b550ec4.js";var c=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;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"]}}};c([u()],d.prototype,"meeting",void 0),c([u()],d.prototype,"t",void 0),c([u()],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}}";const f=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},v=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=g},g=Number.MAX_SAFE_INTEGER||9007199254740991;let p=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}({}),m=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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),y=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var b="manifest",w="level",$="audioTrack",k="subtitleTrack",S="main",T="audio",E="subtitle";class A{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 L{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 A(t),this.fast_=new A(i),this.defaultTTFB_=e,this.ttfb_=new A(t)}update(t,i){const{slow_:s,fast_:e,ttfb_:n}=this;s.halfLife!==t&&(this.slow_=new A(t,s.getEstimate(),s.getTotalWeight())),e.halfLife!==i&&(this.fast_=new A(i,e.getEstimate(),e.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new A(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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function M(t,i,s){return(i=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);if("object"!=typeof e)return e;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof i?i:i+""}(i))in t?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,t}function x(){return x=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var s=arguments[i];for(var e in s)({}).hasOwnProperty.call(s,e)&&(t[e]=s[e])}return t},x.apply(null,arguments)}function I(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 D(t){for(var i=1;i<arguments.length;i++){var s=null!=arguments[i]?arguments[i]:{};i%2?I(Object(s),!0).forEach((function(i){M(t,i,s[i])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):I(Object(s)).forEach((function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(s,i))}))}return t}class P{constructor(t,i){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${t}]:`;this.trace=C,this.debug=i.debug.bind(null,s),this.log=i.log.bind(null,s),this.warn=i.warn.bind(null,s),this.info=i.info.bind(null,s),this.error=i.error.bind(null,s)}}const C=function(){},R={trace:C,debug:C,log:C,warn:C,info:C,error:C};function O(){return x({},R)}function N(t,i,s){return i[t]?i[t].bind(i):function(t,i){const s=self.console[t];return s?s.bind(self.console,`${i?"["+i+"] ":""}[${t}] >`):C}(t,s)}const U=O(),F=U;function B(t=!0){if("undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _(t,i){const s=Object.keys(t),e=Object.keys(i),n=s.length,r=e.length;return!n||!r||n===r&&!s.some((t=>-1===e.indexOf(t)))}function j(t,i=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(t);if(i){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"")}const s=t.length;let e,n,r,h="",o=0;for(;o<s;){if(e=t[o++],0===e&&i)return h;if(0!==e&&3!==e)switch(e>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(e);break;case 12:case 13:n=t[o++],h+=String.fromCharCode((31&e)<<6|63&n);break;case 14:n=t[o++],r=t[o++],h+=String.fromCharCode((15&e)<<12|(63&n)<<6|63&r)}}return h}const G=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};function H(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var K,V,X,W,z,q,Y={exports:{}},Q=K?Y.exports:(K=1,V=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,X=/^(?=([^\/?#]*))\1([^]*)$/,W=/(?:\/|^)\.(?=\/)/g,z=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,Y.exports=q={buildAbsoluteURL:function(t,i,s){if(s=s||{},t=t.trim(),!(i=i.trim())){if(!s.alwaysNormalize)return t;var e=q.parseURL(t);if(!e)throw new Error("Error trying to parse base URL.");return e.path=q.normalizePath(e.path),q.buildURLFromParts(e)}var n=q.parseURL(i);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=q.normalizePath(n.path),q.buildURLFromParts(n)):i;var r=q.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");if(!r.netLoc&&r.path&&"/"!==r.path[0]){var h=X.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=q.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?q.normalizePath(n.path):n.path),q.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(W,"");t.length!==(t=t.replace(z,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}});class J{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 Z="audio",tt="video",it="audiovideo";class st{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,i){const s=ht(t,i);s&&(s.enumerable=!0,Object.defineProperty(t,i,s))}(this,"stats")}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 baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Z]:null,[tt]:null,[it]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new J),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Q.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Z]=null,t[tt]=null,t[it]=null}}function et(t){return"initSegment"!==t.sn}class nt extends st{constructor(t,i){super(i),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=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.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,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 byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange){const t=this.byteRange[0],i=this.byteRange[1];if(f(t)&&f(i))return i-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=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;const t=f(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&this.levelkeys[t[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){this._programDateTime=f(t)?t:this.rawProgramDateTime=null}get ref(){return et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}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}}}class rt extends st{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.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)}}function ht(t,i){const s=Object.getPrototypeOf(t);if(s){return Object.getOwnPropertyDescriptor(s,i)||ht(s,i)}}const ot=Math.pow(2,32)-1,at=[].push,lt={video:1,audio:2,id3:3,text:4};function ut(t){return String.fromCharCode.apply(null,t)}function ct(t,i){const s=t[i]<<8|t[i+1];return s<0?65536+s:s}function dt(t,i){const s=vt(t,i);return s<0?4294967296+s:s}function ft(t,i){let s=dt(t,i);return s*=Math.pow(2,32),s+=dt(t,i+4),s}function vt(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function gt(t,i){const s=[];if(!i.length)return s;const e=t.byteLength;for(let n=0;n<e;){const r=dt(t,n),h=r>1?n+r:e;if(ut(t.subarray(n+4,n+8))===i[0])if(1===i.length)s.push(t.subarray(n+8,h));else{const e=gt(t.subarray(n+8,h),i.slice(1));e.length&&at.apply(s,e)}n=h}return s}function pt(t){const i=[],s=t[0];let e=8;const n=dt(t,e);e+=4;let r=0,h=0;0===s?(r=dt(t,e),h=dt(t,e+4),e+=8):(r=ft(t,e),h=ft(t,e+8),e+=16),e+=2;let o=t.length+h;const a=ct(t,e);e+=2;for(let s=0;s<a;s++){let s=e;const r=dt(t,s);s+=4;const h=2147483647&r;if(1==(2147483648&r)>>>31)return F.warn("SIDX has hierarchical references (not supported)"),null;const a=dt(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 mt(t){const i=[],s=gt(t,["moov","trak"]);for(let t=0;t<s.length;t++){const e=s[t],n=gt(e,["tkhd"])[0];if(n){let t=n[0];const s=dt(n,0===t?12:20),r=gt(e,["mdia","mdhd"])[0];if(r){t=r[0];const n=dt(r,0===t?12:20),h=gt(e,["mdia","hdlr"])[0];if(h){const t=ut(h.subarray(8,12)),r={soun:Z,vide:tt}[t],o=yt(gt(e,["mdia","minf","stbl","stsd"])[0]);r?(i[s]={timescale:n,type:r,stsd:o},i[r]=D({timescale:n,id:s},o)):i[s]={timescale:n,type:t,stsd:o}}}}}return gt(t,["moov","mvex","trex"]).forEach((t=>{const s=dt(t,4),e=i[s];e&&(e.default={duration:dt(t,12),flags:dt(t,20)})})),i}function yt(t){const i=t.subarray(8),s=i.subarray(86),e=ut(i.subarray(4,8));let n,r=e;const h="enca"===e||"encv"===e;if(h){const t=gt(i,[e])[0];gt(t.subarray("enca"===e?28:78),["sinf"]).forEach((t=>{const i=gt(t,["schm"])[0];if(i){const s=ut(i.subarray(4,8));if("cbcs"===s||"cenc"===s){const i=gt(t,["frma"])[0];i&&(r=ut(i))}}}))}const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=gt(s,["avcC"])[0];t&&t.length>3&&(r+="."+$t(t[1])+$t(t[2])+$t(t[3]),n=bt("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const t=gt(i,[e])[0],s=gt(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=wt(s,t),t+=2;const i=s[t++];if(128&i&&(t+=2),64&i&&(t+=s[t++]),4!==s[t++])break;t=wt(s,t);const e=s[t++];if(64!==e)break;if(r+="."+$t(e),t+=12,5!==s[t++])break;t=wt(s,t);const n=s[t++];let h=(248&n)>>3;31===h&&(h+=1+((7&n)<<3)+((224&s[t])>>5)),r+="."+h}break}case"hvc1":case"hev1":{const t=gt(s,["hvcC"])[0];if(t&&t.length>12){const i=t[1],s=["","A","B","C"][i>>6],e=31&i,n=dt(t,2),h=(32&i)>>5?"H":"L",o=t[12],a=t.subarray(6,12);r+="."+s+e,r+="."+function(t){let i=0;for(let s=0;s<32;s++)i|=(t>>s&1)<<31-s;return i>>>0}(n).toString(16).toUpperCase(),r+="."+h+o;let l="";for(let t=a.length;t--;){const i=a[t];(i||l)&&(l="."+i.toString(16).toUpperCase()+l)}r+=l}n=bt("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=bt(r,s)||r;break;case"vp09":{const t=gt(s,["vpcC"])[0];if(t&&t.length>6){const i=t[5],s=t[6]>>4&15;r+="."+kt(t[4])+"."+kt(i)+"."+kt(s)}break}case"av01":{const t=gt(s,["av1C"])[0];if(t&&t.length>2){const i=t[1]>>>5,e=t[2]>>>7?"H":"M",h=(64&t[2])>>6,o=2===i&&h?(32&t[2])>>5?12:10:h?10:8,a=(16&t[2])>>4,l=(8&t[2])>>3,u=(4&t[2])>>2,c=3&t[2],d=1,f=1,v=1,g=0;r+="."+i+"."+kt(31&t[1])+e+"."+kt(o)+"."+a+"."+l+u+c+"."+kt(d)+"."+kt(f)+"."+kt(v)+"."+g,n=bt("dav1",s)}break}}return{codec:r,encrypted:h,supplemental:n}}function bt(t,i){const s=gt(i,["dvvC"]),e=s.length?s[0]:gt(i,["dvcC"])[0];if(e){const i=e[2]<<5&32|e[3]>>3&31;return t+"."+kt(e[2]>>1&127)+"."+kt(i)}}function wt(t,i){const s=i+5;for(;128&t[i++]&&i<s;);return i}function $t(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function kt(t){return(t<10?"0":"")+t}function St(t){const i=gt(t,["schm"])[0];if(i){const s=ut(i.subarray(4,8));if("cbcs"===s||"cenc"===s)return gt(t,["schi","tenc"])[0]}return null}function Tt(t,i){const s=new Uint8Array(t.length+i.length);return s.set(t),s.set(i,t.length),s}function Et(t,i){const s=[],e=i.samples,n=i.timescale,r=i.id;let h=!1;return gt(e,["moof"]).map((o=>{const a=o.byteOffset-8;gt(o,["traf"]).map((o=>{const l=gt(o,["tfdt"]).map((t=>{const i=t[0];let s=dt(t,4);return 1===i&&(s*=Math.pow(2,32),s+=dt(t,8)),s/n}))[0];return void 0!==l&&(t=l),gt(o,["tfhd"]).map((l=>{const u=dt(l,4),c=16777215&dt(l,0);let d=0;const f=!!(16&c);let v=0;const g=!!(32&c);let p=8;u===r&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(d=dt(l,p),p+=4),f&&(v=dt(l,p),p+=4),g&&(p+=4),"video"===i.type&&(h=At(i.codec)),gt(o,["trun"]).map((r=>{const o=r[0],l=16777215&dt(r,0),u=!!(1&l);let c=0;const f=!!(4&l),g=!!(256&l);let p=0;const m=!!(512&l);let y=0;const b=!!(1024&l),w=!!(2048&l);let $=0;const k=dt(r,4);let S=8;u&&(c=dt(r,S),S+=4),f&&(S+=4);let T=c+a;for(let a=0;a<k;a++){if(g?(p=dt(r,S),S+=4):p=d,m?(y=dt(r,S),S+=4):y=v,b&&(S+=4),w&&($=0===o?dt(r,S):vt(r,S),S+=4),i.type===tt){let i=0;for(;i<y;){const r=dt(e,T);T+=4,Lt(h,e[T])&&Mt(e.subarray(T,T+r),h?2:1,t+$/n,s),T+=r,i+=r+4}}t+=p/n}})))}))}))})),s}function At(t){if(!t)return!1;const i=t.substring(0,4);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}function Lt(t,i){if(t){const t=i>>1&63;return 39===t||40===t}return 6==(31&i)}function Mt(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){F.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===h){if(181===n[i++]){const t=ct(n,i);if(i+=2,49===t){const t=dt(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:j(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 It(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=G(new Uint8Array(r,s+12,16));let o=null,a=null,l=0;if(0===n)l=28;else if(1===n){const n=t.getUint32(28);if(!n||e<32+16*n)return{offset:s,size:i};o=[];for(let t=0;t<n;t++)o.push(new Uint8Array(r,s+32+16*t,16));l=32+16*n}if(!l)return{offset:s,size:i};const u=t.getUint32(l);return i-32<u?{offset:s,size:i}:(a=new Uint8Array(r,s+l+4,u),{version:n,systemId:h,kids:o,data:a,offset:s,size:i})}const Dt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Pt={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,dav1:.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 Ct(t,i){const s=Pt[i];return!!s&&!!s[t.slice(0,4)]}function Rt(t,i,s=!0){return!t.split(",").some((t=>!Ot(t,i,s)))}function Ot(t,i,s=!0){var e;const n=B(s);return null!=(e=null==n?void 0:n.isTypeSupported(Nt(t,i)))&&e}function Nt(t,i){return`${i}/mp4;codecs=${t}`}function Ut(t){if(t){const i=t.substring(0,4);return Pt.video[i]}return 2}function Ft(t){const i=Dt();return t.split(",").reduce(((t,s)=>{const e=i&&At(s)?9:Pt.video[s];return e?(2*e+t)/(t?3:2):(Pt.audio[s]+t)/(t?2:1)}),0)}const Bt={},_t=/flac|opus|mp4a\.40\.34/i;function jt(t,i=!0){return t.replace(_t,(t=>function(t,i=!0){if(Bt[t])return Bt[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let n=0;n<s.length;n++){var e;if(Ot(s[n],"audio",i))return Bt[t]=s[n],s[n];if("mp3"===s[n]&&null!=(e=B(i))&&e.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),i)))}function Gt(t,i){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Ht(t,"audio")||Ht(t,"video")))return t;if(i){const s=i.split(",");if(s.length>1){if(t)for(let i=s.length;i--;)if(s[i].substring(0,4)===t.substring(0,4))return s[i];return s[0]}}return i||t}function Ht(t,i){return Ct(t,i)&&Ot(t,i)}function Kt(t){if(t.startsWith("av01.")){const i=t.split("."),s=["0","111","01","01","01","0"];for(let t=i.length;t>4&&t<10;t++)i[t]=s[t-4];return i.join(".")}return t}function Vt(t){const i=B(t)||{isTypeSupported:()=>!1};return{mpeg:i.isTypeSupported("audio/mpeg"),mp3:i.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:i.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Xt(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Wt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function zt(t,i){return{supported:!1,configurations:i,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:t}}function qt(t,i,s,e,n,r){const h=t.videoCodec,o=t.audioCodec?t.audioGroups:null,a=null==r?void 0:r.audioCodec,l=null==r?void 0:r.channels,u=l?parseInt(l):a?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?i.groups[o[0]].channels:o.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!==h&&(h.split(",").some((t=>At(t)))||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&&f(u)&&Object.keys(c).some((t=>parseInt(t)>u))}function Yt(t,i,s,e={}){const n=t.videoCodec;if(!n&&!t.audioCodec||!s)return Promise.resolve(Wt);const r=[],h=function(t){var i;const s=null==(i=t.videoCodec)?void 0:i.split(","),e=Jt(t),n=t.width||640,r=t.height||480,h=t.frameRate||30,o=t.videoRange.toLowerCase();return s?s.map((t=>{const i={contentType:Nt(Kt(t),"video"),width:n,height:r,bitrate:e,framerate:h};return"sdr"!==o&&(i.transferFunction=o),i})):[]}(t),o=h.length,a=function(t,i,s){var e;const n=null==(e=t.audioCodec)?void 0:e.split(","),r=Jt(t);return n&&t.audioGroups?t.audioGroups.reduce(((t,e)=>{var h;const o=e?null==(h=i.groups[e])?void 0:h.tracks:null;return o?o.reduce(((t,i)=>{if(i.groupId===e){const e=parseFloat(i.channels||"");n.forEach((i=>{const n={contentType:Nt(i,"audio"),bitrate:s?Qt(i,r):r};e&&(n.channels=""+e),t.push(n)}))}return t}),t):t}),[]):[]}(t,i,o>0),l=a.length;for(let t=o||1*l||1;t--;){const i={type:"media-source"};if(o&&(i.video=h[t%o]),l){i.audio=a[t%l];const s=i.audio.bitrate;i.video&&s&&(i.video.bitrate-=s)}r.push(i)}if(n){const t=navigator.userAgent;if(n.split(",").some((t=>At(t)))&&Dt())return Promise.resolve(zt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),r))}return Promise.all(r.map((t=>{const i=function(t){let i="";const{audio:s,video:e}=t;return e&&(i+=`${Xt(e.contentType)}_r${e.height}x${e.width}f${Math.ceil(e.framerate)}${e.transferFunction||"sd"}_${Math.ceil(e.bitrate/1e5)}`),s&&(i+=`${e?"_":""}${Xt(s.contentType)}_c${s.channels}`),i}(t);return e[i]||(e[i]=s.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:r,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:r,decodingInfoResults:[],error:t})))}function Qt(t,i){if(i<=1)return 1;let s=128e3;return"ec-3"===t?s=768e3:"ac-3"===t&&(s=64e4),Math.min(i/2,s)}function Jt(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const Zt=["NONE","TYPE-0","TYPE-1",null],ti=["SDR","PQ","HLG"];function ii(t){const{canSkipUntil:i,canSkipDateRanges:s,age:e}=t;return i&&e<i/2?s?"v2":"YES":""}class si{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 ei{constructor(t){if(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.supplemental=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(","),"supplemental"in t){var i;this.supplemental=t.supplemental;const s=null==(i=t.supplemental)?void 0:i.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}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 ni(this._audioGroups,t)}hasSubtitleGroup(t){return ni(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 ni(t,i){return!(!i||!t)&&-1!==t.indexOf(i)}const ri=(t,i)=>JSON.stringify(t,(t=>{const i=new WeakSet;return(s,e)=>{if(t&&(e=t(s,e)),"object"==typeof e&&null!==e){if(i.has(e))return;i.add(e)}return e}})(i));function hi(t,i){F.log(`[abr] start candidates with "${t}" ignored because ${i}`)}function oi(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:{}})}function ai(t){if(!t)return t;const{lang:i,assocLang:s,characteristics:e,channels:n,audioCodec:r}=t;return{lang:i,assocLang:s,characteristics:e,channels:n,audioCodec:r}}function li(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(ui(t,i[e],s))return e;return-1}function ui(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||function(t,i="--"){return t.length===i.length?t===i:t.startsWith(i)||i.startsWith(t)}(r,i.lang))&&(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 ci(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 di(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}function fi(t,i){var s;return!!t&&t!==(null==(s=i.loadLevelObj)?void 0:s.uri)}const vi=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 gi(t,i,s=0,e=0,n=.005){let r=null;if(t){r=i[1+t.sn-i[0].sn]||null;const e=t.endDTS-s;e>0&&e<15e-7&&(s+=15e-7),r&&t.level!==r.level&&r.end<=t.end&&(r=i[2+t.sn-i[0].sn]||null)}else 0===s&&0===i[0].start&&(r=i[0]);if(r&&((!t||t.level===r.level)&&0===pi(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=vi(i,pi.bind(null,s,e));return!h||h===t&&r?r:h}function pi(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 mi(t,i,s){const e=1e3*Math.min(i,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-e>t}function yi(t,i,s){if(t&&t.startCC<=i&&t.endCC>=i){let e=t.fragments;const{fragmentHint:n}=t;let r;return n&&(e=e.concat(n)),vi(e,(t=>t.cc<i?1:t.cc>i?-1:(r=t,t.end<=s?1:t.start>s?-1:0))),r||null}return null}function bi(t){switch(t.details){case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_TIMEOUT:case m.LEVEL_LOAD_TIMEOUT:case m.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function wi(t,i){const s=bi(i);return t.default[(s?"timeout":"error")+"Retry"]}function $i(t,i){const s="linear"===t.backoff?1:Math.pow(2,i);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function ki(t){return D(D({},t),{errorRetry:null,timeoutRetry:null})}function Si(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}function Ti(t){const i={action:0,flags:0};return t&&(i.resolved=!0),i}var Ei="NOT_LOADED",Ai="APPENDING",Li="PARTIAL",Mi="OK";class xi{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.BUFFER_APPENDED,this.onBufferAppended,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.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){return this.getFragAtPos(t,i,!0)}getFragAtPos(t,i,s){const{fragments:e}=this,n=Object.keys(e);for(let r=n.length;r--;){const h=e[n[r]];if((null==h?void 0:h.body.type)===i&&(!s||h.buffered)){const i=h.body;if(i.start<=t&&t<=i.end)return i}}return null}detectEvictedFragments(t,i,s,e,n){this.timeRanges&&(this.timeRanges[t]=i);const r=(null==e?void 0:e.fragment.sn)||-1;Object.keys(this.fragments).forEach((e=>{const h=this.fragments[e];if(!h)return;if(r>=h.body.sn)return;if(!h.buffered&&(!h.loaded||n))return void(h.body.type===s&&this.removeFragment(h.body));const o=h.range[t];o&&(0!==o.time.length?o.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,i);return s&&this.removeFragment(h.body),s})):this.removeFragment(h.body))}))}detectPartialFragments(t){const i=this.timeRanges;if(!i||"initSegment"===t.frag.sn)return;const s=t.frag,e=Di(s),n=this.fragments[e];if(!n||n.buffered&&s.gap)return;const r=!s.relurl;Object.keys(i).forEach((e=>{const h=s.elementaryStreams[e];h&&(n.range[e]=this.getBufferedTimes(s,t.part,r||!0===h.partial,i[e]))})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ii(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}removeParts(t,i){const s=this.activePartLists[i];s&&(this.activePartLists[i]=Pi(s,(i=>i.fragment.sn>=t)))}fragBuffered(t,i){const s=Di(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&&Ii(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||Ii(i))}getState(t){const i=Di(t),s=this.fragments[i];return s?s.buffered?Ii(s)?Li:Mi:Ai:Ei}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}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,i){if("initSegment"===i.frag.sn||i.frag.bitrateTest)return;const s=i.frag,e=i.part?null:i,n=Di(s);this.fragments[n]={body:s,appendedPTS:null,loaded:e,buffered:!1,range:Object.create(null)}}onBufferAppended(t,i){const{frag:s,part:e,timeRanges:n,type:r}=i;if("initSegment"===s.sn)return;const h=s.type;if(e){let t=this.activePartLists[h];t||(this.activePartLists[h]=t=[]),t.push(e)}this.timeRanges=n,this.detectEvictedFragments(r,n[r],h,e)}onFragBuffered(t,i){this.detectPartialFragments(i)}hasFragment(t){const i=Di(t);return!!this.fragments[i]}hasFragments(t){const{fragments:i}=this,s=Object.keys(i);if(!t)return s.length>0;for(let e=s.length;e--;){const n=i[s[e]];if((null==n?void 0:n.body.type)===t)return!0}return!1}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=Di(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const i=t.sn;this.activePartLists[t.type]=Pi(s,(t=>t.fragment.sn!==i))}delete this.fragments[i],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t,i;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const s=null==(t=this.hls)||null==(i=t.latestLevelDetails)?void 0:i.partList;s&&s.forEach((t=>t.clearElementaryStreamInfo()))}}function Ii(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 Di(t){return`${t.type}_${t.level}_${t.sn}`}function Pi(t,i){return t.filter((t=>{const s=i(t);return s||t.clearElementaryStreamInfo(),s}))}class Ci{constructor(t,i,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=i,this.aesMode=s}decrypt(t,i){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},i,t);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},i,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Ri{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],u=o[2],c=o[3],d=new Uint32Array(256);let f=0,v=0,g=0;for(g=0;g<256;g++)d[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){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],g=d[o],p=d[g];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*p^65537*g^257*o^16843008*f,a[s]=m<<24|m>>>8,l[s]=m<<16|m>>>16,u[s]=m<<8|m>>>24,c[s]=m,f?(f=o^d[d[d[p^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),u=this.sBox,c=this.rcon,d=this.invSubMix,f=d[0],v=d[1],g=d[2],p=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=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[255&y],y^=c[h/n|0]<<24):n>6&&h%n==4&&(y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[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[u[y>>>24]]^v[u[y>>>16&255]]^g[u[y>>>8&255]]^p[u[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],u=h[3],c=this.uint8ArrayToUint32Array_(s);let d=c[0],f=c[1],v=c[2],g=c[3];const p=new Int32Array(t),m=new Int32Array(p.length);let y,b,w,$,k,S,T,E,A,L,M,x,I,D;const P=this.networkToHostOrderSwap;for(;i<p.length;){for(A=P(p[i]),L=P(p[i+1]),M=P(p[i+2]),x=P(p[i+3]),k=A^n[0],S=x^n[1],T=M^n[2],E=L^n[3],I=4,D=1;D<e;D++)y=o[k>>>24]^a[S>>16&255]^l[T>>8&255]^u[255&E]^n[I],b=o[S>>>24]^a[T>>16&255]^l[E>>8&255]^u[255&k]^n[I+1],w=o[T>>>24]^a[E>>16&255]^l[k>>8&255]^u[255&S]^n[I+2],$=o[E>>>24]^a[k>>16&255]^l[S>>8&255]^u[255&T]^n[I+3],k=y,S=b,T=w,E=$,I+=4;y=r[k>>>24]<<24^r[S>>16&255]<<16^r[T>>8&255]<<8^r[255&E]^n[I],b=r[S>>>24]<<24^r[T>>16&255]<<16^r[E>>8&255]<<8^r[255&k]^n[I+1],w=r[T>>>24]<<24^r[E>>16&255]<<16^r[k>>8&255]<<8^r[255&S]^n[I+2],$=r[E>>>24]<<24^r[k>>16&255]<<16^r[S>>8&255]<<8^r[255&T]^n[I+3],m[i]=P(y^d),m[i+1]=P($^f),m[i+2]=P(w^v),m[i+3]=P(b^g),d=A,f=L,v=M,g=x,i+=4}return m.buffer}}class Oi{constructor(t,i,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=i,this.aesMode=s}expandKey(){const t=function(t){switch(t){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Ni{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.enableSoftwareAES=void 0,this.enableSoftwareAES=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?t.slice(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,e){return this.useSoftware?new Promise(((n,r)=>{const h=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(h,i,s,e);const o=this.flush();o?n(o.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),i,s,e)}softwareDecrypt(t,i,s,e){const{currentIV:n,currentResult:r,remainderData:h}=this;if(0!==e||16!==i.byteLength)return F.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),h&&(t=Tt(h,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;n&&(s=n);let a=this.softwareDecrypter;a||(a=this.softwareDecrypter=new Ri),a.expandKey(i);const l=r;return this.currentResult=a.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,l||null}webCryptoDecrypt(t,i,s,e){if(this.key!==i||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,i,s,e));this.key=i,this.fastAesKey=new Oi(this.subtle,i,e)}return this.fastAesKey.expandKey().then((i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ci(this.subtle,new Uint8Array(s),e).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized")))).catch((n=>(F.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(t,i,s,e))))}onWebCryptoError(t,i,s,e){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,i,s,e);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let i=t;const s=t.length-t.length%16;return s!==t.length&&(i=t.slice(0,s),this.remainderData=t.slice(s)),i}logOnce(t){this.logEnabled&&(F.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ui=Math.pow(2,17);class Fi{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 ji({type:p.NETWORK_ERROR,details:m.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(_i(t));t.gap=!1}const a=this.loader=n?new n(e):new r(e),l=Bi(t);t.loader=a;const u=ki(e.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ui};t.stats=a.stats;const d={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 ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:D({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 ji({type:p.NETWORK_ERROR,details:m.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:e,stats:i}))},onTimeout:(i,s,e)=>{this.resetLoader(t,a),o(new ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:e,stats:i}))}};i&&(d.onProgress=(s,e,n,r)=>i({frag:t,part:null,payload:n,networkDetails:r})),a.load(l,c,d)}))}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(_i(t,i));const a=this.loader=n?new n(e):new r(e),l=Bi(t,i);t.loader=a;const u=ki(e.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ui};i.stats=a.stats,a.load(l,c,{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 ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:i,response:D({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 ji({type:p.NETWORK_ERROR,details:m.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 ji({type:p.NETWORK_ERROR,details:m.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:i,error:new Error(`Timeout after ${c.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 Bi(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(f(n)&&f(r)){var h;let i=n,s=r;if("initSegment"===t.sn&&("AES-128"===(o=null==(h=t.decryptdata)?void 0:h.method)||"AES-256"===o)){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}var o;return e}function _i(t,i){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),e={type:p.MEDIA_ERROR,details:m.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return i&&(e.part=i),(i||t).stats.aborted=!0,new ji(e)}class ji extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Gi extends P{constructor(t,i){super(t,i),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(){}}class Hi{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}}const Ki={length:0,start:()=>0,end:()=>0};class Vi{static isBuffered(t,i){if(t){const s=Vi.getBuffered(t);for(let t=s.length;t--;)if(i>=s.start(t)&&i<=s.end(t))return!0}return!1}static bufferedRanges(t){if(t){const i=Vi.getBuffered(t);return Vi.timeRangesToArray(i)}return[]}static timeRangesToArray(t){const i=[];for(let s=0;s<t.length;s++)i.push({start:t.start(s),end:t.end(s)});return i}static bufferInfo(t,i,s){if(t){const e=Vi.bufferedRanges(t);if(e.length)return Vi.bufferedInfo(e,i,s)}return{len:0,start:i,end:i,bufferedIndex:-1}}static bufferedInfo(t,i,s){i=Math.max(0,i),t.length>1&&t.sort(((t,i)=>t.start-i.start||i.end-t.end));let e=-1,n=[];if(s)for(let r=0;r<t.length;r++){i>=t[r].start&&i<=t[r].end&&(e=r);const h=n.length;if(h){const i=n[h-1].end;t[r].start-i<s?t[r].end>i&&(n[h-1].end=t[r].end):n.push(t[r])}else n.push(t[r])}else n=t;let r,h=0,o=i,a=i;for(let t=0;t<n.length;t++){const l=n[t].start,u=n[t].end;if(-1===e&&i>=l&&i<=u&&(e=t),i+s>=l&&i<u)o=l,a=u,h=a-i;else if(i+s<l){r=l;break}}return{len:h,start:o||0,end:a||0,nextStart:r,buffered:t,bufferedIndex:e}}static getBuffered(t){try{return t.buffered||Ki}catch(t){return F.log("failed to get media.buffered",t),Ki}}}const Xi=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wi(t){return Xi.test(t)}function zi(t,i){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return i.replace(Xi,(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 qi(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 Yi(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}"`))}const Qi=/^(\d+)x(\d+)$/,Ji=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Zi{constructor(t,i){"string"==typeof t&&(t=Zi.parseAttrList(t,i)),x(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]}enumeratedStringList(t,i){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce(((t,i)=>(t[i.toLowerCase()]=!0,t)),i)}bool(t){return"YES"===this[t]}decimalResolution(t){const i=Qi.exec(this[t]);if(null!==i)return{width:parseInt(i[1],10),height:parseInt(i[2],10)}}static parseAttrList(t,i){let s;const e={};for(Ji.lastIndex=0;null!==(s=Ji.exec(t));){const n=s[1].trim();let r=s[2];const h=0===r.indexOf('"')&&r.lastIndexOf('"')===r.length-1;let o=!1;if(h)r=r.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(i&&(h||o))r=zi(i,r);else if(!o&&!h)switch(n){case"CLOSED-CAPTIONS":if("NONE"===r)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":F.warn(`${t}: attribute ${n} is missing quotes`)}e[n]=r}return e}}function ts(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class is{constructor(t,i,s=0){var e;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(e=null==i?void 0:i.tagOrder)?e:s,i){const s=i.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==s[i]){F.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=x(new Zi({}),s,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==i?void 0:i.endDate)||new Date(this.attr["END-DATE"]);f(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(F.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const i=this.duration;return null!==i?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*i):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(f(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&f(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class ss{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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,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}get hasProgramDateTime(){return!!this.fragments.length&&f(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;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 fragmentStart(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[0].start: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 maxPartIndex(){const t=this.partList;if(t){const i=this.lastPartIndex;if(-1!==i){for(let s=t.length;s--;)if(t[s].index>i)return t[s].index;return i}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){return!!(this.live&&this.age&&this.misses<3)&&this.age>Math.max(this.partEnd-this.fragmentStart,this.totalduration)+this.levelTargetDuration}}function es(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function ns(t){switch(t){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw new Error(`invalid full segment method ${t}`)}}function rs(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function hs(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const os="undefined"!=typeof self?self:void 0;var as={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ls="org.w3.clearkey",us="com.apple.streamingkeydelivery",cs="com.microsoft.playready",ds="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function fs(t){switch(t){case us:return as.FAIRPLAY;case cs:return as.PLAYREADY;case ds:return as.WIDEVINE;case ls:return as.CLEARKEY}}function vs(t){return"edef8ba979d64acea3c827dcd51d21ed"===t?as.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===t?as.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===t||"e2719d58a985b3c9781ab030af78d30e"===t?as.CLEARKEY:void 0}function gs(t){switch(t){case as.FAIRPLAY:return us;case as.PLAYREADY:return cs;case as.WIDEVINE:return ds;case as.CLEARKEY:return ls}}function ps(t){const{drmSystems:i,widevineLicenseUrl:s}=t,e=i?[as.FAIRPLAY,as.WIDEVINE,as.PLAYREADY,as.CLEARKEY].filter((t=>!!i[t])):[];return!e[as.WIDEVINE]&&s&&e.push(as.WIDEVINE),e}const ms=null!=os&&null!=(ys=os.navigator)&&ys.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ys;function bs(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=rs(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}let ws={};class $s{static clearKeyUriToKeyIdMap(){ws={}}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&&!es(t)}isSupported(){if(this.method){if(es(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case us:case ds:case cs:case ls: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(es(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(F.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 $s(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=rs(i)):s=function(t){const i=hs(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 ds:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case cs:{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;e=0,n=new Uint8Array,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([0,0,0,0]),t,r,n,h,s||new Uint8Array)}(t,0,i),this.keyId=bs(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=ws[this.uri];if(!t){const i=Object.keys(ws).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16),new DataView(t.buffer,12,4).setUint32(0,i),ws[this.uri]=t}this.keyId=t}return this}}const ks=/#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,Ss=/#EXT-X-MEDIA:(.*)/g,Ts=/^#EXT(?:INF|-X-TARGETDURATION):/m,Es=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),As=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|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 Ls{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 Q.buildAbsoluteURL(i,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Ts.test(t)}static parseMasterPlaylist(t,i){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Wi(t)},e=[];let n;for(ks.lastIndex=0;null!=(n=ks.exec(t));)if(n[1]){var r;const t=new Zi(n[1],s),h=zi(s,n[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Ls.resolve(h,i)},a=t.decimalResolution("RESOLUTION");a&&(o.width=a.width,o.height=a.height),Ps(t.CODECS,o);const l=t["SUPPLEMENTAL-CODECS"];l&&(o.supplemental={},Ps(l,o.supplemental)),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 Zi(t,s),e=i["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=i);break}case"SESSION-KEY":{const e=Is(t,i,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):F.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${t}"`);break}case"DEFINE":qi(s,new Zi(t,s),i);break;case"CONTENT-STEERING":{const e=new Zi(t,s);s.contentSteering={uri:Ls.resolve(e["SERVER-URI"],i),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Ds(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(Ss.lastIndex=0;null!==(e=Ss.exec(t));){const t=new Zi(e[1],s),r=t.TYPE;if(r){const s=h[r],e=n[r]||[];n[r]=e;const a=t.LANGUAGE,l=t["ASSOC-LANGUAGE"],u=t.CHANNELS,c=t.CHARACTERISTICS,d=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||a||"",type:r,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:a,url:t.URI?Ls.resolve(t.URI,i):""};if(l&&(f.assocLang=l),u&&(f.channels=u),c&&(f.characteristics=c),d&&(f.instreamId=d),null!=s&&s.length){const t=Ls.findGroup(s,f.groupId)||s[0];Cs(f,t,"audioCodec"),Cs(f,t,"textCodec")}e.push(f)}}return n}static parseLevelPlaylist(t,i,s,e,n,r){var h;const o={url:i},a=new ss(i),l=a.fragments,u=[];let c,d,v,g,p=null,m=0,y=0,b=0,w=0,$=0,k=null,S=new nt(e,o),T=-1,E=!1,A=null;if(Es.lastIndex=0,a.m3u8=t,a.hasVariableRefs=Wi(t),"#EXTM3U"!==(null==(h=Es.exec(t))?void 0:h[0]))return a.playlistParsingError=new Error("Missing format identifier #EXTM3U"),a;for(;null!==(c=Es.exec(t));){E&&(E=!1,S=new nt(e,o),S.playlistOffset=b,S.start=b,S.sn=m,S.cc=w,$&&(S.bitrate=$),S.level=s,p&&(S.initSegment=p,p.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),A&&(S.setByteRange(A),A=null)));const t=c[1];if(t){S.duration=parseFloat(t);const i=(" "+c[2]).slice(1);S.title=i||null,S.tagList.push(i?["INF",t,i]:["INF",t])}else if(c[3]){if(f(S.duration)){S.playlistOffset=b,S.start=b,v&&Ns(S,v,a),S.sn=m,S.level=s,S.cc=w,l.push(S);const t=(" "+c[3]).slice(1);S.relurl=zi(a,t),Rs(S,k,u),k=S,b+=S.duration,m++,y=0,E=!0}}else{if(c=c[0].match(As),!c){F.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<c.length&&void 0===c[d];d++);const t=(" "+c[d]).slice(1),n=(" "+c[d+1]).slice(1),h=c[d+2]?(" "+c[d+2]).slice(1):null;switch(t){case"BYTERANGE":k?S.setByteRange(n,k):S.setByteRange(n);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=n,S.tagList.push(["PROGRAM-DATE-TIME",n]),-1===T&&(T=l.length);break;case"PLAYLIST-TYPE":a.type&&Us(a,t,c),a.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==a.startSN?Us(a,t,c):l.length>0&&Fs(a,t,c),m=a.startSN=parseInt(n);break;case"SKIP":{a.skippedSegments&&Us(a,t,c);const i=new Zi(n,a),s=i.decimalInteger("SKIPPED-SEGMENTS");if(f(s)){a.skippedSegments+=s;for(let t=s;t--;)l.push(null);m+=s}const e=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");e&&(a.recentlyRemovedDateranges=(a.recentlyRemovedDateranges||[]).concat(e.split("\t")));break}case"TARGETDURATION":0!==a.targetduration&&Us(a,t,c),a.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==a.version&&Us(a,t,c),a.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":a.live||Us(a,t,c),a.live=!1;break;case"#":(n||h)&&S.tagList.push(h?[n,h]:[n]);break;case"DISCONTINUITY":w++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([t]);break;case"BITRATE":S.tagList.push([t,n]),$=1e3*parseInt(n),f($)?S.bitrate=$:$=0;break;case"DATERANGE":{const t=new Zi(n,a),i=new is(t,a.dateRanges[t.ID],a.dateRangeTagCount);a.dateRangeTagCount++,i.isValid||a.skippedSegments?a.dateRanges[i.id]=i:F.warn(`Ignoring invalid DATERANGE tag: "${n}"`),S.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new Zi(n,a);"IMPORT"in t?Yi(a,t,r):qi(a,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==a.startCC?Us(a,t,c):l.length>0&&Fs(a,t,c),a.startCC=w=parseInt(n);break;case"KEY":{const t=Is(n,i,a);if(t.isSupported()){if("NONE"===t.method){v=void 0;break}v||(v={}),v[t.keyFormat]&&(v=x({},v)),v[t.keyFormat]=t}else F.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${n}"`);break}case"START":a.startTimeOffset=Ds(n);break;case"MAP":{const t=new Zi(n,a);if(S.duration){const i=new nt(e,o);Os(i,t,s,v),p=i,S.initSegment=p,p.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime)}else{const i=S.byteRangeEndOffset;if(i){const t=S.byteRangeStartOffset;A=`${i-t}@${t}`}else A=null;Os(S,t,s,v),p=S,E=!0}p.cc=w;break}case"SERVER-CONTROL":g&&Us(a,t,c),g=new Zi(n),a.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),a.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{a.partTarget&&Us(a,t,c);const i=new Zi(n);a.partTarget=i.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const i=y>0?t[t.length-1]:void 0,s=y++,e=new Zi(n,a),r=new rt(e,S,o,s,i);t.push(r),S.duration+=r.duration;break}case"PRELOAD-HINT":{const t=new Zi(n,a);a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new Zi(n,a);a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:F.warn(`line parsed but not handled: ${c}`)}}}k&&!k.relurl?(l.pop(),b-=k.duration,a.partList&&(a.fragmentHint=k)):a.partList&&(Rs(S,k,u),S.cc=w,a.fragmentHint=S,v&&Ns(S,v,a)),a.targetduration||(a.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const L=l.length,M=l[0],I=l[L-1];if(b+=a.skippedSegments*a.targetduration,b>0&&L&&I){a.averagetargetduration=b/L;const t=I.sn;a.endSN="initSegment"!==t?t:0,a.live||(I.endList=!0),M&&void 0===a.startCC&&(a.startCC=M.cc),T>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}}(l,T),M&&u.unshift(M))}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(b+=a.fragmentHint.duration),a.totalduration=b,u.length&&a.dateRangeTagCount&&M&&Ms(u,a),a.endCC=w,a}}function Ms(t,i){const s=t.length;if(!s)return;const e=t[s-1],n=i.live?1/0:i.totalduration,r=Object.keys(i.dateRanges);for(let h=r.length;h--;){const o=i.dateRanges[r[h]],a=o.startDate.getTime();o.tagAnchor=e.ref;for(let e=s;e--;){const s=xs(i,a,t,e,n);if(-1!==s){o.tagAnchor=i.fragments[s].ref;break}}}}function xs(t,i,s,e,n){const r=s[e];if(r){const o=r.programDateTime;var h;if(i>=o||0===e)if(i<=o+1e3*(((null==(h=s[e+1])?void 0:h.start)||n)-r.start)){const n=s[e].sn-t.startSN,r=t.fragments;if(r.length>s.length)for(let h=(s[e+1]||r[r.length-1]).sn-t.startSN;h>n;h--){const t=r[h].programDateTime;if(i>=t&&i<t+1e3*r[h].duration)return h}return n}}return-1}function Is(t,i,s){var e,n;const r=new Zi(t,s),h=null!=(e=r.METHOD)?e:"",o=r.URI,a=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,u=null!=(n=r.KEYFORMAT)?n:"identity";o&&r.IV&&!a&&F.error(`Invalid IV: ${r.IV}`);const c=o?Ls.resolve(o,i):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new $s(h,c,u,d,a)}function Ds(t){const i=new Zi(t).decimalFloatingPoint("TIME-OFFSET");return f(i)?i:null}function Ps(t,i){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const e=s.filter((i=>Ct(i,t)));e.length&&(i[`${t}Codec`]=e.map((t=>t.split("/")[0])).join(","),s=s.filter((t=>-1===e.indexOf(t))))})),i.unknownCodecs=s}function Cs(t,i,s){const e=i[s];e&&(t[s]=e)}function Rs(t,i,s){t.rawProgramDateTime?s.push(t):null!=i&&i.programDateTime&&(t.programDateTime=i.endProgramDateTime)}function Os(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 Ns(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)}function Us(t,i,s){t.playlistParsingError=new Error(`#EXT-X-${i} must not appear more than once (${s[0]})`)}function Fs(t,i,s){t.playlistParsingError=new Error(`#EXT-X-${i} must appear before the first Media Segment (${s[0]})`)}function Bs(t,i){const s=i.startPTS;if(f(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.setDuration(n)}else i.setStart(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 _s(t,i,s,e,n,r){e-s<=0&&(F.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(f(a)){const t=Math.abs(a-s);i.deltaPTS=f(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 u=s-i.start;0!==i.start&&i.setStart(s),i.setDuration(e-i.start),i.startPTS=s,i.maxStartPTS=h,i.startDTS=n,i.endPTS=e,i.minEndPTS=o,i.endDTS=r;const c=i.sn;if(!t||c<t.startSN||c>t.endSN)return 0;let d;const v=c-t.startSN,g=t.fragments;for(g[v]=i,d=v;d>0;d--)Bs(g[d],g[d-1]);for(d=v;d<g.length-1;d++)Bs(g[d],g[d+1]);return t.fragmentHint&&Bs(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function js(t,i,s,e,n){return new Error(`${t} ${n.url}\nPlaylist starting @${i.startSN}\n${i.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function Gs(t,i,s=!0){const e=i.startSN+i.skippedSegments-t.startSN,n=t.fragments,r=e>=0;let h=0;if(r&&e<n.length)h=n[e].start;else if(r&&i.startSN===t.endSN+1)h=t.fragmentEnd;else if(r&&s)h=t.fragmentStart+e*i.levelTargetDuration;else{if(i.skippedSegments||0!==i.fragmentStart)return;h=t.fragmentStart}Hs(i,h)}function Hs(t,i){if(i){const s=t.fragments;for(let e=t.skippedSegments;e<s.length;e++)s[e].addStart(i);t.fragmentHint&&t.fragmentHint.addStart(i)}}function Ks(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)}function Vs(t,i,s){if(!t)return null;let e=t.fragments[i-t.startSN];return e||(e=t.fragmentHint,e&&e.sn===i?e:i<t.startSN&&s&&s.sn===i?s:null)}function Xs(t,i,s){return t?Ws(t.partList,i,s):null}function Ws(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 zs(t){t.forEach(((t,i)=>{var s;null==(s=t.details)||s.fragments.forEach((t=>{t.level=i,t.initSegment&&(t.initSegment.level=i)}))}))}function qs(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 Ys(t,i){if(t){const s=t.start+i;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Qs(t,i){const s=i.fragments;for(let i=0,e=s.length;i<e;i++)Ys(s[i],t);i.fragmentHint&&Ys(i.fragmentHint,t),i.alignedSliding=!0}function Js(t,i){if(!function(t,i){return!!(t&&i.startCC<t.endCC&&i.endCC>t.startCC)}(i,t))return;const s=Math.min(i.endCC,t.endCC),e=qs(i.fragments,s),n=qs(t.fragments,s);e&&n&&(F.log(`Aligning playlist at start of dicontinuity sequence ${s}`),Qs(e.start-n.start,t))}function Zs(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=qs(e,h),r=qs(s,h)),n&&r||(n=e[Math.floor(e.length/2)],r=qs(s,n.cc)||s[Math.floor(s.length/2)]);const o=n.programDateTime,a=r.programDateTime;o&&a&&Qs((a-o)/1e3-(r.start-n.start),t)}const te={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ie extends Gi{constructor(t,i,s,e,n){super(e,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=te.STOPPED,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.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.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:i,media:s,mediaBuffer:e,state:n}=this,r=s?s.currentTime:0,h=Vi.bufferInfo(e||s,r,t.maxBufferHole),o=!h.len;if(this.log(`Media seeking to ${f(r)?r.toFixed(3):r}, state: ${n}, ${o?"out of":"in"} buffer`),this.state===te.ENDED)this.resetLoadingState();else if(i){const s=t.maxFragLookUpTolerance,e=i.start-s,n=i.start+i.duration+s;if(o||n<h.start||e>h.end){const t=r>n;(r<e||t)&&(t&&i.loader&&(this.log(`Cancelling fragment load for seek (sn: ${i.sn})`),i.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,this.playlistType,!0),r>this.lastCurrentTime&&(this.lastCurrentTime=r),!this.loadingParts)){const t=Math.max(h.end,r),i=this.shouldLoadParts(this.getLevelDetails(),t);i&&(this.log(`LL-Part loading ON after seeking to ${r.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=i)}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${r} for seek without enough to start`),this.nextLoadPosition=r,o&&(this.startPosition=r)),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new Fi(t.config),this.keyLoader=s,this.fragmentTracker=i,this.config=t.config,this.decrypter=new Ni(t.config)}registerListeners(){const{hls:t}=this;t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===te.STOPPED)return;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=te.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:i}=this;return-1===i&&t?t:i}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,i){if(i.live||!this.media)return!1;const s=this.config.timelineOffset||0;if((t.end||0)<=s)return!1;const e=t.buffered;this.config.maxBufferHole&&e&&e.length>1&&(t=Vi.bufferedInfo(e,t.start,0));const n=t.nextStart;if(n&&n>s&&n<i.edge)return!1;if(this.media.currentTime<t.start)return!1;const r=i.partList;if(null!=r&&r.length){const t=r[r.length-1];return Vi.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}get timelineOffset(){const t=this.config.timelineOffset;var i;return t?(null==(i=this.getLevelDetails())?void 0:i.appliedTimelineOffset)||t:0}onMediaAttached(t,i){const s=this.media=this.mediaBuffer=i.media;s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),s.addEventListener("seeking",this.onMediaSeeking),s.addEventListener("ended",this.onMediaEnded);const e=this.config;this.levels&&e.autoStartLoad&&this.state===te.STOPPED&&this.startLoad(e.startPosition)}onMediaDetaching(t,i){const s=!!i.transferMedia,e=this.media;if(null!==e){if(e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e.removeEventListener("seeking",this.onMediaSeeking),e.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,i){}onManifestLoaded(t,i){this.startTimeOffset=i.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=te.STOPPED,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.startFragRequested=!0,this._loadFragForPlayback(t,i,s)}_loadFragForPlayback(t,i,s){this._doFragLoad(t,i,s,(t=>{const i=t.frag;if(this.fragContextChanged(i))return this.warn(`${i.type} sn: ${i.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(i,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(i);i.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const i=this.state,s=t.frag;this.fragContextChanged(s)?(i===te.FRAG_LOADING||!this.fragCurrent&&i===te.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=te.IDLE):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(y.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((i=>{this.state!==te.STOPPED&&this.state!==te.ERROR&&(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)===Ai){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)===Li&&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)}waitForLive(t){const i=t.details;return(null==i?void 0:i.live)&&"EVENT"!==i.type&&(this.levelLastLoaded!==t||i.expired)}flushMainBuffer(t,i,s=null){t-i&&this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:t,endOffset:i,type:s})}_loadInitSegment(t,i){this._doFragLoad(t,i).then((t=>{const i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:i}=this,{frag:s,payload:e}=t,n=s.decryptdata;if(e&&e.byteLength>0&&null!=n&&n.key&&n.iv&&es(n.method)){const r=self.performance.now();return this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer,ns(n.method)).catch((t=>{throw i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),t})).then((e=>{const n=self.performance.now();return i.trigger(y.FRAG_DECRYPTED,{frag:s,payload:e,stats:{tstart:r,tdecrypt:n}}),t.payload=e,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((i=>{this.state!==te.STOPPED&&this.state!==te.ERROR&&(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!==te.STOPPED&&(this.state=te.IDLE),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){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${i?" part: "+i.index:""} of ${this.fragInfo(t,!1,i)} > buffer:${s?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}(Vi.getBuffered(s)):"(detached)"})`),et(t)){var e;if(t.type!==E){const i=t.elementaryStreams;if(!Object.keys(i).some((t=>!!i[t])))return void(this.state=te.IDLE)}const i=null==(e=this.levels)?void 0:e[t.level];null!=i&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=te.IDLE}_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 Hi(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;this.fragCurrent=t;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;!t.encrypted||null!=(n=t.decryptdata)&&n.key?t.encrypted||(h=this.keyLoader.loadClear(t,r.encryptedFragments),h&&this.log("[eme] blocking frag load until media-keys acquired")):(this.log(`Loading key for ${t.sn} of [${r.startSN}-${r.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=te.KEY_LOADING,this.fragCurrent=t,h=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(y.KEY_LOADED,t),this.state===te.KEY_LOADING&&(this.state=te.IDLE),t})),this.hls.trigger(y.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(h=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const o=this.fragPrevious;if(et(t)&&(!o||t.sn!==o.sn)){const s=this.shouldLoadParts(i.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts&&et(t)){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 t=this.fragCurrent=a.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${a.index} (${o}/${n.length-1}) of ${this.fragInfo(t,!1,a)}) cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=a.start+a.duration,this.state=te.FRAG_LOADING,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(y.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)}}if(et(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${r?"["+r.startSN+"-"+r.endSN+"]":""}, target: ${parseFloat(s.toFixed(3))}`),f(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=te.FRAG_LOADING;const a=this.config.progressive;let l;return l=a&&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,a?e:void 0),h]).then((([t])=>(!a&&t&&e&&e(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(y.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}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(y.FRAG_LOADED,e);const h=Xs(s.details,t.sn,i.index+1)||Ws(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===m.INTERNAL_ABORTED?this.handleFragLoadAborted(i.frag,i.part):this.hls.trigger(y.ERROR,i)}else this.hls.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const i=this.getCurrentContext(t);if(!i||this.state!==te.PARSING)return void(this.fragCurrent||this.state===te.STOPPED||this.state===te.ERROR||(this.state=te.IDLE));const{frag:s,part:e,level:n}=i,r=self.performance.now();s.stats.parsing.end=r,e&&(e.stats.parsing.end=r);const h=this.getLevelDetails(),o=h&&s.sn>h.endSN||this.shouldLoadParts(h,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,e,n,t.partial)}shouldLoadParts(t,i){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(null!=t&&t.partList){var s;const n=t.partList[0];var e;if(i>=n.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0))if((this.hls.hasEnoughToStart?(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}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 ${this.playlistLabel()} ${e}. The current chunk will not be buffered.`),null;const h=i[e],o=h.details,a=r>-1?Xs(o,n,r):null,l=a?a.fragment:Vs(o,n,s);return l?(s&&s!==l&&(l.stats=s.stats),{frag:l,part:a,level:h}):null}bufferFragmentData(t,i,s,e,n){var r;if(!t||this.state!==te.PARSING)return;const{data1:h,data2:o}=t;let a=h;if(h&&o&&(a=Tt(h,o)),null==(r=a)||!r.length)return;const l=this.initPTS[i.cc];if(this.hls.trigger(y.BUFFER_APPENDING,{type:t.type,frag:i,part:s,chunkMeta:e,offset:l?-l.baseTime/l.timescale:void 0,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(!Vi.isBuffered(i,i.currentTime))return void this.flushMainBuffer(0,t.start);const s=i.currentTime,e=Vi.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){var s;const e=this.getLoadPosition();if(!f(e))return null;const n=this.lastCurrentTime>e||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,e,i,n)}getFwdBufferInfoAtPos(t,i,s,e){const n=Vi.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||r.gap)){const s=Math.max(Math.min(n.nextStart,r.end)-i,e);return Vi.bufferInfo(t,i,s)}}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=S){var s;const e=null==(s=this.fragmentTracker)?void 0:s.getAppendedFrag(t,i);return e&&"fragment"in e?e.fragment:e}getNextFragment(t,i){const s=i.fragments,e=s.length;if(!e)return null;const{config:n}=this,r=s[0].start,h=n.lowLatencyMode&&!!i.partList;let o=null;if(i.live){const s=n.initialLiveManifestSize;if(e<s)return this.warn(`Not enough fragments to start playback (have: ${e}, need: ${s})`),null;if(!i.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<r){var a;h&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(i);const s=this.hls.startPosition,e=this.hls.liveSyncPosition,n=o?(-1!==s&&s>=r?s:e)||o.start:t;this.log(`Setting startPosition to ${n} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${e} frag.start: ${null==(a=o)?void 0:a.start}`),this.startPosition=this.nextLoadPosition=n}}else t<=r&&(o=s[0]);o||(o=this.getFragmentAtPosition(t,this.loadingParts?i.partEnd:i.fragmentEnd,i));let l=this.filterReplacedPrimary(o,i);return!l&&o&&(l=this.filterReplacedPrimary(s[o.sn-i.startSN+1]||null,i)),this.mapToInitFragWhenRequired(l)}isLoopLoading(t,i){const s=this.fragmentTracker.getState(t);return(s===Mi||s===Li&&!!t.gap)&&this.nextLoadPosition>i}getNextFragmentLoopLoading(t,i,s,e,n){let r=null;if(t.gap&&(r=this.getNextFragment(this.nextLoadPosition,i),r&&!r.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,e,0);if(null!==t&&s.len+t.len>=n){const t=r.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${e}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,r}get primaryPrefetch(){var t,i;if(se(this.hls.config)&&(null==(t=this.hls.interstitialsManager)||null==(i=t.playingItem)?void 0:i.event))return!0;return!1}filterReplacedPrimary(t,i){if(!t)return t;if(se(this.hls.config)&&t.type!==E){const s=this.hls.interstitialsManager,e=null==s?void 0:s.bufferingItem;if(e){const s=e.event;if(s){if(s.appendInPlace||Math.abs(t.start-e.start)>1||0===e.start)return null}else{if(t.end<=e.start&&!1===(null==i?void 0:i.live))return null;if(t.start>e.end&&e.nextEvent&&(e.nextEvent.appendInPlace||t.start-e.end>1))return null}}const n=null==s?void 0:s.playerQueue;if(n)for(let i=n.length;i--;){const s=n[i].interstitial;if(s.appendInPlace&&t.start>=s.startTime&&t.end<=s.resumeTime)return 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){const i=t.fragments,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||!f(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;for(let e=0;e<t.length;++e){const n=t[e];if(mi(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=yi(t,s.cc,s.end),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,u=!!(this.loadingParts&&null!=l&&l.length&&o);let c;var d;(u&&o&&!this.bitrateTest&&l[l.length-1].fragment.sn===o.sn&&(r=r.concat(o),h=o.sn),t<i)?c=gi(n,r,t,t<this.lastCurrentTime||t>i-a||null!=(d=this.media)&&d.paused||!this.startFragRequested?0:a):c=r[r.length-1];if(c){const t=c.sn-s.startSN,i=this.fragmentTracker.getState(c);if((i===Mi||i===Li&&c.gap)&&(n=c),n&&c.sn===n.sn&&(!u||l[0].fragment.sn>c.sn||!s.live&&!u)&&n&&c.level===n.level){const i=r[t+1];c=c.sn<h&&this.fragmentTracker.getState(i)!==Mi?i:null}}return c}alignPlaylists(t,i,s){const e=t.fragments.length;if(!e)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,r=!i,h=t.alignedSliding&&f(n);if(r||!h&&!n){!function(t,i){t&&(Js(i,t),!i.alignedSliding&&t&&Zs(i,t),i.alignedSliding||!t||i.skippedSegments||Gs(t,i,!1))}(s,t);const n=t.fragmentStart;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${e}`),n}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;s<i&&(s=-1);const e=this.timelineOffset;if(-1===s){const n=null!==this.startTimeOffset,r=n?this.startTimeOffset:t.startTimeOffset;null!==r&&f(r)?(s=i+r,r<0&&(s+=t.edge),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${r} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):t.live?(s=this.hls.liveSyncPosition||i,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+e}this.nextLoadPosition=s+e}getLoadPosition(){var t;const{media:i}=this;let s=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&i?s=i.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(t,i){this.transmuxer&&t.type===this.playlistType&&et(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${i?" part "+i.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===te.FRAG_LOADING_WAITING_RETRY)||(this.state=te.IDLE)}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===m.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const r=i.errorAction,{action:h,flags:o,retryCount:a=0,retryConfig:l}=r||{},u=!!r&&!!l,c=u&&5===h,d=u&&!r.resolved&&1===o;if(!c&&d&&et(s)&&!s.endList)this.resetFragmentErrors(t),this.treatAsGap(s),r.resolved=!0;else if((c||d)&&a<l.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const e=$i(l,a);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${i.details}, retrying loading ${a+1}/${l.maxNumRetry} in ${e}ms`),r.resolved=!0,this.retryDate=self.performance.now()+e,this.state=te.FRAG_LOADING_WAITING_RETRY}else if(l&&r){if(this.resetFragmentErrors(t),!(a<l.maxNumRetry))return void this.warn(`${i.details} reached or exceeded max retry (${a})`);n||3===h||(r.resolved=!0)}else this.state=2===h?te.WAITING_LEVEL:te.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===te.PARSING||this.state===te.PARSED){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===T&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==te.STOPPED&&(this.state=te.IDLE)}afterBufferFlushed(t,i,s){if(!t)return;const e=Vi.getBuffered(t);this.fragmentTracker.detectEvictedFragments(i,e,s),this.state===te.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==te.STOPPED&&(this.state=te.IDLE)}resetStartWhenNotLoaded(t){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const i=t?t.details:null;null!=i&&i.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(i,i.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of ${this.playlistLabel()} ${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){const n=s.details;if(n){var r;if(!Object.keys(t.elementaryStreams).reduce(((i,r)=>{const h=t.elementaryStreams[r];if(h){const o=h.endPTS-h.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${o})`),i||!1;const a=e?0:_s(n,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:s,drift:a,type:r,frag:t,start:h.startPTS,end:h.endPTS}),!0}return i}),!1)&&(0===s.fragmentError&&this.treatAsGap(t,s),null===(null==(r=this.transmuxer)?void 0:r.error))){const i=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(i.message),this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=te.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${i?" part: "+i.index:""} of ${this.fragInfo(t,!1,i)})`),this.hls.trigger(y.FRAG_PARSED,{frag:t,part:i})}else this.warn("level.details undefined")}playlistLabel(){return this.playlistType===S?"level":"track"}fragInfo(t,i=!0,s){var e,n;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${(null!=(e=i&&!s?t.startPTS:(s||t).start)?e:NaN).toFixed(3)}-${(null!=(n=i&&!s?t.endPTS:(s||t).end)?n:NaN).toFixed(3)}]${s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(t,i){i&&i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),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}}function se(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class ee{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}}var ne,re={exports:{}},he=(ne||(ne=1,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,u=this._events[o],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,i),!0;case 3:return u.fn.call(u.context,i,e),!0;case 4:return u.fn.call(u.context,i,e,n),!0;case 5:return u.fn.call(u.context,i,e,n,r),!0;case 6:return u.fn.call(u.context,i,e,n,r,h),!0}for(l=1,a=new Array(c-1);l<c;l++)a[l-1]=arguments[l];u.fn.apply(u.context,a)}else{var d,f=u.length;for(l=0;l<f;l++)switch(u[l].once&&this.removeListener(t,u[l].fn,void 0,!0),c){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,i);break;case 3:u[l].fn.call(u[l].context,i,e);break;case 4:u[l].fn.call(u[l].context,i,e,n);break;default:if(!a)for(d=1,a=new Array(c-1);d<c;d++)a[d-1]=arguments[d];u[l].fn.apply(u[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=[],u=o.length;a<u;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}(re)),re.exports),oe=H(he);const ae="1.6.6",le={};function ue(t,i){return 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}function ce(t,i){return 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}function de(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}function fe(t,i){const s=i;let e=0;for(;ce(t,i);)e+=10,e+=de(t,i+6),ue(t,i+10)&&(e+=10),i+=e;if(e>0)return t.subarray(s,s+e)}function ve(t,i){return 255===t[i]&&240==(246&t[i+1])}function ge(t,i){return 1&t[i+1]?7:9}function pe(t,i){return(3&t[i+3])<<11|t[i+4]<<3|(224&t[i+5])>>>5}function me(t,i){return i+1<t.length&&ve(t,i)}function ye(t,i){if(me(t,i)){const s=ge(t,i);if(i+s>=t.length)return!1;const e=pe(t,i);if(e<=s)return!1;const n=i+e;return n===t.length||me(t,n)}return!1}function be(t,i,s,e,n){if(!t.samplerate){const r=function(t,i,s,e){const n=i[s+2],r=n>>2&15;if(r>12){const i=new Error(`invalid ADTS sampling index:${r}`);return void t.emit(y.ERROR,y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!0,error:i,reason:i.message})}const h=1+(n>>6&3),o=i[s+3]>>6&3|(1&n)<<2,a="mp4a.40."+h,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][r];let u=r;5!==h&&29!==h||(u-=3);const c=[h<<3|(14&u)>>1,(1&u)<<7|o<<3];return F.log(`manifest codec:${e}, parsed codec:${a}, channels:${o}, rate:${l} (ADTS object type:${h} sampling index:${r})`),{config:c,samplerate:l,channelCount:o,codec:a,parsedCodec:a,manifestCodec:e}}(i,s,e,n);if(!r)return;x(t,r)}}function we(t){return 9216e4/t}function $e(t,i,s,e,n){const r=e+n*we(t.samplerate),h=function(t,i){const s=ge(t,i);if(i+s<=t.length){const e=pe(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 u={unit:o,pts:r};return l||t.samples.push(u),{sample:u,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}}function ke(t,i){return ce(t,i)&&de(t,i+6)+10<=t.length-i}function Se(t,i=0,s=1/0){return function(t,i,s,e){const n=(r=t)instanceof ArrayBuffer?r:r.buffer;var r;let h=1;"BYTES_PER_ELEMENT"in e&&(h=e.BYTES_PER_ELEMENT);const o=(u=t)&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0,a=(o+t.byteLength)/h,l=Math.floor(Math.max(0,Math.min((o+i)/h,a)));var u;return new e(n,l,Math.floor(Math.min(l+Math.max(s,0),a))-l)}(t,i,s,Uint8Array)}function Te(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const i=j(t.data,!0),s=new Uint8Array(t.data.subarray(i.length+1));return{key:t.type,info:i,data:s.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let i=1;const s=j(t.data.subarray(i),!0);i+=s.length+1;const e=j(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=j(t.data);return{key:t.type,info:"",data:i}}(t):"APIC"===t.type?function(t){const i={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=t.data.subarray(1).indexOf(0);if(-1===s)return;const e=j(Se(t.data,1,s)),n=t.data[2+s],r=t.data.subarray(3+s).indexOf(0);if(-1===r)return;const h=j(Se(t.data,3+s,r));let o;return o="--\x3e"===e?j(Se(t.data,4+s+r)):(a=t.data.subarray(4+s+r))instanceof ArrayBuffer?a:0==a.byteOffset&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer,i.mimeType=e,i.pictureType=n,i.description=h,i.data=o,i;var a}(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let i=1;const s=j(t.data.subarray(i),!0);i+=s.length+1;const e=j(t.data.subarray(i));return{key:t.type,info:s,data:e}}const i=j(t.data.subarray(1));return{key:t.type,info:"",data:i}}(t)}function Ee(t){const i=String.fromCharCode(t[0],t[1],t[2],t[3]),s=de(t,4);return{type:i,size:s,data:t.subarray(10,10+s)}}const Ae=10,Le=10;function Me(t){let i=0;const s=[];for(;ce(t,i);){const e=de(t,i+6);t[i+5]>>6&1&&(i+=Ae),i+=Ae;const n=i+e;for(;i+Le<n;){const e=Ee(t.subarray(i)),n=Te(e);n&&s.push(n),i+=e.size+Ae}ue(t,i)&&(i+=Ae)}return s}function xe(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Ie(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)}}function De(t){const i=Me(t);for(let t=0;t<i.length;t++){const s=i[t];if(xe(s))return Ie(s)}}let Pe=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Ce(t="",i=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:i,sequenceNumber:-1,samples:[],dropped:0}}class Re{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=Tt(this.cachedData,t),this.cachedData=null);let s,e=fe(t,0),n=e?e.length:0;const r=this._audioTrack,h=this._id3Track,o=e?De(e):void 0,a=t.length;for((null===this.basePTS||0===this.frameIndex&&f(o))&&(this.basePTS=Oe(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:Pe.audioId3,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 ke(t,n)?(e=fe(t,n),h.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:e,type:Pe.audioId3,duration:Number.POSITIVE_INFINITY}),n+=e.length,s=n):n++;if(n===a&&s!==a){const i=t.slice(s);this.cachedData=this.cachedData?Tt(this.cachedData,i):i}}return{audioTrack:r,videoTrack:Ce(),id3Track:h,textTrack:Ce()}}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:Ce(),id3Track:this._id3Track,textTrack:Ce()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Oe=(t,i,s)=>f(t)?90*t:9e4*i+(s?9e4*s.baseTime/s.timescale:0);let Ne=null;const Ue=[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],Fe=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Be=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],_e=[0,1,1,4];function je(t,i,s,e,n){if(s+24>i.length)return;const r=Ge(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 Ge(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*Ue[14*(3===s?3-e:3===e?3:4)+n-1],a=Fe[3*(3===s?0:2===s?1:2)+r],l=3===h?1:2,u=Be[s][e],c=_e[e],d=8*u*c,f=Math.floor(u*o/a+(t[i+2]>>1&1))*c;if(null===Ne){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ne=t?parseInt(t[1]):0}return!!Ne&&Ne<=87&&2===e&&o>=224e3&&0===h&&(t[i+3]=128|t[i+3]),{sampleRate:a,channelCount:l,frameLength:f,samplesPerFrame:d}}}function He(t,i){return!(255!==t[i]||224&~t[i+1]||!(6&t[i+1]))}function Ke(t,i){return i+1<t.length&&He(t,i)}function Ve(t,i){if(i+1<t.length&&He(t,i)){const s=4,e=Ge(t,i);let n=s;null!=e&&e.frameLength&&(n=e.frameLength);const r=i+n;return r===t.length||Ke(t,r)}return!1}const Xe=(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 We(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 u=0;2===l?u+=2:(1&l&&1!==l&&(u+=2),4&l&&(u+=2));const c=(i[s+6]<<8|i[s+7])>>12-u&1,d=[2,1,2,3,3,4,4,5][l]+c,f=7&i[s+5],v=new Uint8Array([r<<6|i[s+5]>>3<<1|f>>2,(3&f)<<6|l<<3|c<<2|o>>4,o<<4&224]),g=e+n*(1536/h*9e4),p=i.subarray(s,s+a);return t.config=v,t.channelCount=d,t.samplerate=h,t.samples.push({unit:p,pts:g}),a}const ze=/\/emsg[-/]ID3/i;function qe(t,i){return f(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class Ye{constructor(t,i,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ni(i,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,0)}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}}}}class Qe{constructor(){this.VideoSample=null}createVideoSample(t,i,s){return{key:t,frame:!1,pts:i,dts:s,units:[],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)}}parseNALu(t,i,s){const e=i.byteLength;let n=t.naluState||0;const r=n,h=[];let o,a,l,u=0,c=-1,d=0;for(-1===n&&(c=0,d=this.getNALuType(i,0),n=0,u=1);u<e;)if(o=i[u++],n)if(1!==n)if(o)if(1===o){if(a=u-n-1,c>=0){const t={data:i.subarray(c,a),type:d};h.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(r&&u<=4-r&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-r)),a>0&&(s.data=Tt(s.data,i.subarray(0,a)),s.state=0))}u<e?(l=this.getNALuType(i,u),c=u,d=l,n=0):n=-1}else n=0;else n=3;else n=o?0:2;else n=o?0:1;if(c>=0&&n>=0){const t={data:i.subarray(c,e),type:d,state:n};h.push(t)}if(0===h.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Tt(s.data,i))}return t.naluState=n,h}}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&&F.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)}}class Ze extends Qe{parsePES(t,i,s,e){const n=this.parseNALu(t,s.data,e);let r,h=this.VideoSample,o=!1;s.data=null,h&&n.length&&!t.audFound&&(this.pushAccessUnit(h,t),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach((e=>{var n,a;switch(e.type){case 1:{let i=!1;r=!0;const n=e.data;if(o&&n.length>4){const t=this.readSliceType(n);2!==t&&4!==t&&7!==t&&9!==t||(i=!0)}var l;i&&null!=(l=h)&&l.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.frame=!0,h.key=i;break}case 5:r=!0,null!=(n=h)&&n.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 6:r=!0,Mt(e.data,1,s.pts,i.samples);break;case 7:{var u,c;r=!0,o=!0;const i=e.data,s=this.readSPS(i);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(u=t.pixelRatio)?void 0:u[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[i];const e=i.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let i=e[t].toString(16);i.length<2&&(i="0"+i),n+=i}t.codec=n}break}case 8:r=!0,t.pps=[e.data];break;case 9:r=!0,t.audFound=!0,null!=(a=h)&&a.frame&&(this.pushAccessUnit(h,t),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:r=!0;break;default:r=!1}h&&r&&h.units.push(e)})),e&&h&&(this.pushAccessUnit(h,t),this.VideoSample=null)}getNALuType(t,i){return 31&t[i]}readSliceType(t){const i=new Je(t);return i.readUByte(),i.readUEG(),i.readUEG()}skipScalingList(t,i){let s,e=8,n=8;for(let r=0;r<t;r++)0!==n&&(s=i.readEG(),n=(e+s+256)%256),e=0===n?e:n}readSPS(t){const i=new Je(t);let s,e,n,r=0,h=0,o=0,a=0;const l=i.readUByte.bind(i),u=i.readBits.bind(i),c=i.readUEG.bind(i),d=i.readBoolean.bind(i),f=i.skipBits.bind(i),v=i.skipEG.bind(i),g=i.skipUEG.bind(i),p=this.skipScalingList.bind(this);l();const m=l();if(u(5),f(3),l(),g(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const t=c();if(3===t&&f(1),g(),g(),f(1),d())for(e=3!==t?8:12,n=0;n<e;n++)d()&&p(n<6?16:64,i)}g();const y=c();if(0===y)c();else if(1===y)for(f(1),v(),v(),s=c(),n=0;n<s;n++)v();g(),f(1);const b=c(),w=c(),$=u(1);0===$&&f(1),f(1),d()&&(r=c(),h=c(),o=c(),a=c());let k=[1,1];if(d()&&d())switch(l()){case 1:k=[1,1];break;case 2:k=[12,11];break;case 3:k=[10,11];break;case 4:k=[16,11];break;case 5:k=[40,33];break;case 6:k=[24,11];break;case 7:k=[20,11];break;case 8:k=[32,11];break;case 9:k=[80,33];break;case 10:k=[18,11];break;case 11:k=[15,11];break;case 12:k=[64,33];break;case 13:k=[160,99];break;case 14:k=[4,3];break;case 15:k=[3,2];break;case 16:k=[2,1];break;case 255:k=[l()<<8|l(),l()<<8|l()]}return{width:Math.ceil(16*(b+1)-2*r-2*h),height:(2-$)*(w+1)*16-($?2:4)*(o+a),pixelRatio:k}}}class tn extends Qe{constructor(...t){super(...t),this.initVPS=null}parsePES(t,i,s,e){const n=this.parseNALu(t,s.data,e);let r,h=this.VideoSample,o=!1;s.data=null,h&&n.length&&!t.audFound&&(this.pushAccessUnit(h,t),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach((e=>{var n,a;switch(e.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),h.frame=!0,r=!0;break;case 16:case 17:case 18:case 21:var l;r=!0,o&&null!=(l=h)&&l.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 19:case 20:r=!0,null!=(n=h)&&n.frame&&!h.key&&(this.pushAccessUnit(h,t),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 39:r=!0,Mt(e.data,2,s.pts,i.samples);break;case 32:r=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=x(t.params,this.readVPS(e.data)),this.initVPS=e.data),t.vps=[e.data];break;case 33:if(r=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],e.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const i=this.readSPS(e.data);t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.codec=i.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const s in i.params)t.params[s]=i.params[s]}this.pushParameterSet(t.sps,e.data,t.vps),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0;break;case 34:if(r=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const i=this.readPPS(e.data);for(const s in i)t.params[s]=i[s]}this.pushParameterSet(t.pps,e.data,t.vps)}break;case 35:r=!0,t.audFound=!0,null!=(a=h)&&a.frame&&(this.pushAccessUnit(h,t),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:r=!1}h&&r&&h.units.push(e)})),e&&h&&(this.pushAccessUnit(h,t),this.VideoSample=null)}pushParameterSet(t,i,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(i)}getNALuType(t,i){return(126&t[i])>>>1}ebsp2rbsp(t){const i=new Uint8Array(t.byteLength);let s=0;for(let e=0;e<t.byteLength;e++)e>=2&&3===t[e]&&0===t[e-1]&&0===t[e-2]||(i[s]=t[e],s++);return new Uint8Array(i.buffer,0,s)}pushAccessUnit(t,i){super.pushAccessUnit(t,i),this.initVPS&&(this.initVPS=null)}readVPS(t){const i=new Je(t);return i.readUByte(),i.readUByte(),i.readBits(4),i.skipBits(2),i.readBits(6),{numTemporalLayers:i.readBits(3)+1,temporalIdNested:i.readBoolean()}}readSPS(t){const i=new Je(this.ebsp2rbsp(t));i.readUByte(),i.readUByte(),i.readBits(4);const s=i.readBits(3);i.readBoolean();const e=i.readBits(2),n=i.readBoolean(),r=i.readBits(5),h=i.readUByte(),o=i.readUByte(),a=i.readUByte(),l=i.readUByte(),u=i.readUByte(),c=i.readUByte(),d=i.readUByte(),f=i.readUByte(),v=i.readUByte(),g=i.readUByte(),p=i.readUByte(),m=[],y=[];for(let t=0;t<s;t++)m.push(i.readBoolean()),y.push(i.readBoolean());if(s>0)for(let t=s;t<8;t++)i.readBits(2);for(let t=0;t<s;t++)m[t]&&(i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte(),i.readUByte()),y[t]&&i.readUByte();i.readUEG();const b=i.readUEG();3==b&&i.skipBits(1);const w=i.readUEG(),$=i.readUEG(),k=i.readBoolean();let S=0,T=0,E=0,A=0;k&&(S+=i.readUEG(),T+=i.readUEG(),E+=i.readUEG(),A+=i.readUEG());const L=i.readUEG(),M=i.readUEG(),x=i.readUEG();for(let t=i.readBoolean()?0:s;t<=s;t++)i.skipUEG(),i.skipUEG(),i.skipUEG();if(i.skipUEG(),i.skipUEG(),i.skipUEG(),i.skipUEG(),i.skipUEG(),i.skipUEG(),i.readBoolean()&&i.readBoolean())for(let t=0;t<4;t++)for(let s=0;s<(3===t?2:6);s++)if(i.readBoolean()){const s=Math.min(64,1<<4+(t<<1));t>1&&i.readEG();for(let t=0;t<s;t++)i.readEG()}else i.readUEG();i.readBoolean(),i.readBoolean(),i.readBoolean()&&(i.readUByte(),i.skipUEG(),i.skipUEG(),i.readBoolean());const I=i.readUEG();let D=0;for(let t=0;t<I;t++){let s=!1;if(0!==t&&(s=i.readBoolean()),s){t===I&&i.readUEG(),i.readBoolean(),i.readUEG();let s=0;for(let t=0;t<=D;t++){const t=i.readBoolean();let e=!1;t||(e=i.readBoolean()),(t||e)&&s++}D=s}else{const t=i.readUEG(),s=i.readUEG();D=t+s;for(let s=0;s<t;s++)i.readUEG(),i.readBoolean();for(let t=0;t<s;t++)i.readUEG(),i.readBoolean()}}if(i.readBoolean()){const t=i.readUEG();for(let s=0;s<t;s++){for(let t=0;t<x+4;t++)i.readBits(1);i.readBits(1)}}let P=0,C=1,R=1,O=!0,N=1,U=0;i.readBoolean(),i.readBoolean();let F=!1;if(i.readBoolean()){if(i.readBoolean()){const t=i.readUByte();t>0&&t<16?(C=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],R=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(C=i.readBits(16),R=i.readBits(16))}if(i.readBoolean()&&i.readBoolean(),i.readBoolean()&&(i.readBits(3),i.readBoolean(),i.readBoolean()&&(i.readUByte(),i.readUByte(),i.readUByte())),i.readBoolean()&&(i.readUEG(),i.readUEG()),i.readBoolean(),i.readBoolean(),i.readBoolean(),F=i.readBoolean(),F&&(S+=i.readUEG(),T+=i.readUEG(),E+=i.readUEG(),A+=i.readUEG()),i.readBoolean()&&(N=i.readBits(32),U=i.readBits(32),i.readBoolean()&&i.readUEG(),i.readBoolean())){const t=i.readBoolean(),e=i.readBoolean();let n=!1;(t||e)&&(n=i.readBoolean(),n&&(i.readUByte(),i.readBits(5),i.readBoolean(),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5));for(let r=0;r<=s;r++){O=i.readBoolean();let s=!1;O||i.readBoolean()?i.readEG():s=i.readBoolean();const r=s?1:i.readUEG()+1;if(t)for(let t=0;t<r;t++)i.readUEG(),i.readUEG(),n&&(i.readUEG(),i.readUEG()),i.skipBits(1);if(e)for(let t=0;t<r;t++)i.readUEG(),i.readUEG(),n&&(i.readUEG(),i.readUEG()),i.skipBits(1)}}i.readBoolean()&&(i.readBoolean(),i.readBoolean(),i.readBoolean(),P=i.readUEG())}let B=w,_=$;if(k||F){let t=1,i=1;1===b?t=i=2:2==b&&(t=2),B=w-t*T-t*S,_=$-i*A-i*E}const j=e?["A","B","C"][e]:"",G=h<<24|o<<16|a<<8|l;let H=0;for(let t=0;t<32;t++)H=(H|(G>>t&1)<<31-t)>>>0;let K=H.toString(16);return 1===r&&"2"===K&&(K="6"),{codecString:`hvc1.${j}${r}.${K}.${n?"H":"L"}${p}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:e,general_profile_compatibility_flags:[h,o,a,l],general_constraint_indicator_flags:[u,c,d,f,v,g],general_level_idc:p,bit_depth:L+8,bit_depth_luma_minus8:L,bit_depth_chroma_minus8:M,min_spatial_segmentation_idc:P,chroma_format_idc:b,frame_rate:{fixed:O,fps:U/N}},width:B,height:_,pixelRatio:[C,R]}}readPPS(t){const i=new Je(this.ebsp2rbsp(t));i.readUByte(),i.readUByte(),i.skipUEG(),i.skipUEG(),i.skipBits(2),i.skipBits(3),i.skipBits(2),i.skipUEG(),i.skipUEG(),i.skipEG(),i.skipBits(2),i.readBoolean()&&i.skipUEG(),i.skipEG(),i.skipEG(),i.skipBits(4);const s=i.readBoolean(),e=i.readBoolean();let n=1;return e&&s?n=0:e?n=3:s&&(n=2),{parallelismType:n}}matchSPS(t,i){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,i).substr(3)}}const sn=188;class en{constructor(t,i,s,e){this.logger=void 0,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._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.logger=e,this.videoParser=null}static probe(t,i){const s=en.syncOffset(t);return s>0&&i.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(t){const i=t.length;let s=Math.min(940,i-sn)+1,e=0;for(;e<s;){let n=!1,r=-1,h=0;for(let o=e;o<i;o+=sn){if(71!==t[o]||i-o!==sn&&71!==t[o+sn]){if(h)return-1;break}if(h++,-1===r&&(r=o,0!==r&&(s=Math.min(r+18612,t.length-sn)+1)),n||(n=0===nn(t,o)),n&&h>1&&(0===r&&h>2||o+sn>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=en.createTrack("video"),this._videoTrack.duration=e,this._audioTrack=en.createTrack("audio",e),this._id3Track=en.createTrack("id3"),this._txtTrack=en.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=s}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,u=r.pesData,c=h.pid,d=o.pid,f=h.pesData,v=o.pesData,g=null,p=this.pmtParsed,m=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=Tt(this.remainderData,t)).length,this.remainderData=null),y<sn&&!e)return this.remainderData=t,{audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};const b=Math.max(0,en.syncOffset(t));y-=(y-b)%sn,y<t.byteLength&&!e&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let w=0;for(let i=b;i<y;i+=sn)if(71===t[i]){const e=!!(64&t[i+1]),y=nn(t,i);let w;if((48&t[i+3])>>4>1){if(w=i+5+t[i+4],w===i+sn)continue}else w=i+4;switch(y){case l:if(e){if(u&&(n=ln(u,this.logger))){if(null===this.videoParser)switch(r.segmentCodec){case"avc":this.videoParser=new Ze;break;case"hevc":this.videoParser=new tn}null!==this.videoParser&&this.videoParser.parsePES(r,a,n,!1)}u={data:[],size:0}}u&&(u.data.push(t.subarray(w,i+sn)),u.size+=i+sn-w);break;case c:if(e){if(f&&(n=ln(f,this.logger)))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(w,i+sn)),f.size+=i+sn-w);break;case d:e&&(v&&(n=ln(v,this.logger))&&this.parseID3PES(o,n),v={data:[],size:0}),v&&(v.data.push(t.subarray(w,i+sn)),v.size+=i+sn-w);break;case 0:e&&(w+=t[w]+1),m=this._pmtId=rn(t,w);break;case m:{e&&(w+=t[w]+1);const n=hn(t,w,this.typeSupported,s,this.observer,this.logger);l=n.videoPid,l>0&&(r.pid=l,r.segmentCodec=n.segmentVideoCodec),c=n.audioPid,c>0&&(h.pid=c,h.segmentCodec=n.segmentAudioCodec),d=n.id3Pid,d>0&&(o.pid=d),null===g||p||(this.logger.warn(`MPEG-TS PMT found at ${i} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,i=b-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=y}}else w++;w>0&&on(this.observer,new Error(`Found ${w} TS packet/s that do not start with 0x47`),void 0,this.logger),r.pesData=u,h.pesData=f,o.pesData=v;const $={audioTrack:h,videoTrack:r,id3Track:o,textTrack:a};return e&&this.extractRemainingSamples($),$}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=ln(r,this.logger))){if(null===this.videoParser)switch(s.segmentCodec){case"avc":this.videoParser=new Ze;break;case"hevc":this.videoParser=new tn}null!==this.videoParser&&(this.videoParser.parsePES(s,n,a,!0),s.pesData=null)}else s.pesData=r;if(h&&(a=ln(h,this.logger))){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&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=h;o&&(a=ln(o,this.logger))?(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 Ye(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.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 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=Tt(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&&!me(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",on(this.observer,new Error(t),i,this.logger),!i)return}if(be(t,this.observer,o,n,this.audioCodec),void 0!==i.pts)h=i.pts;else{if(!e)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const i=we(t.samplerate);h=e.sample.pts+i}}let a,l=0;for(;n<r;){if(a=$e(t,o,n,h,l),n+=a.length,a.missing){this.aacOverFlow=a;break}for(l++;n<r-1&&!me(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(Ke(s,r)){const i=je(t,s,r,h,n);if(!i)break;r+=i.length,n++}else r++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,i){{const s=i.data,e=i.pts;if(void 0===e)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const n=s.length;let r,h=0,o=0;for(;o<n&&(r=We(t,s,o,e,h++))>0;)o+=r}}parseID3PES(t,i){if(void 0===i.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=x({},i,{type:this._videoTrack?Pe.emsg:Pe.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function nn(t,i){return((31&t[i+1])<<8)+t[i+2]}function rn(t,i){return(31&t[i+10])<<8|t[i+11]}function hn(t,i,s,e,n,r){const h={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=i+3+((15&t[i+1])<<8|t[i+2])-4;for(i+=12+((15&t[i+10])<<8|t[i+11]);i<o;){const o=nn(t,i),a=(15&t[i+3])<<8|t[i+4];switch(t[i]){case 207:if(!e){an("ADTS AAC",r);break}case 15:-1===h.audioPid&&(h.audioPid=o);break;case 21:-1===h.id3Pid&&(h.id3Pid=o);break;case 219:if(!e){an("H.264",r);break}case 27:-1===h.videoPid&&(h.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===h.audioPid&&(h.audioPid=o,h.segmentAudioCodec="mp3"):r.log("MPEG audio found, not supported in this browser");break;case 193:if(!e){an("AC-3",r);break}case 129:s.ac3?-1===h.audioPid&&(h.audioPid=o,h.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===h.audioPid&&a>0){let e=i+5,n=a;for(;n>2;){106===t[e]&&(!0!==s.ac3?r.log("AC-3 audio found, not supported in this browser for now"):(h.audioPid=o,h.segmentAudioCodec="ac3"));const i=t[e+1]+2;e+=i,n-=i}}break;case 194:case 135:return on(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),h;case 36:-1===h.videoPid&&(h.videoPid=o,h.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"))}i+=a+5}return h}function on(t,i,s,e){e.warn(`parsing error: ${i.message}`),t.emit(y.ERROR,y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:i,reason:i.message})}function an(t,i){i.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function ln(t,i){let s,e,n,r,h,o=0;const a=t.data;if(!t||0===t.size)return null;for(;a[0].length<19&&a.length>1;)a[0]=Tt(a[0],a[1]),a.splice(1,1);if(s=a[0],1===(s[0]<<16)+(s[1]<<8)+s[2]){if(e=(s[4]<<8)+s[5],e&&e>t.size-6)return null;const l=s[7];192&l&&(r=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&l?(h=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,r-h>54e5&&(i.warn(`${Math.round((r-h)/9e4)}s delta between PTS and DTS, align them`),r=h)):h=r),n=s[8];let u=n+9;if(t.size<=u)return null;t.size-=u;const c=new Uint8Array(t.size);for(let t=0,i=a.length;t<i;t++){s=a[t];let i=s.byteLength;if(u){if(u>i){u-=i;continue}s=s.subarray(u),i-=u,u=0}c.set(s,o),o+=i}return e&&(e-=n+3),{data:c,pts:r,dts:h,len:e}}return null}class un{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 cn=Math.pow(2,32)-1;class dn{static init(){let t;for(t in dn.types={avc1:[],avcC:[],hvc1:[],hvcC:[],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:[]},dn.types)dn.types.hasOwnProperty(t)&&(dn.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]);dn.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]);dn.STTS=dn.STSC=dn.STCO=n,dn.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),dn.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),dn.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),dn.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]);dn.FTYP=dn.box(dn.types.ftyp,r,o,r,h),dn.DINF=dn.box(dn.types.dinf,dn.box(dn.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 dn.box(dn.types.hdlr,dn.HDLR_TYPES[t])}static mdat(t){return dn.box(dn.types.mdat,t)}static mdhd(t,i){i*=t;const s=Math.floor(i/(cn+1)),e=Math.floor(i%(cn+1));return dn.box(dn.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 dn.box(dn.types.mdia,dn.mdhd(t.timescale||0,t.duration||0),dn.hdlr(t.type),dn.minf(t))}static mfhd(t){return dn.box(dn.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return dn.box(dn.types.minf,"audio"===t.type?dn.box(dn.types.smhd,dn.SMHD):dn.box(dn.types.vmhd,dn.VMHD),dn.DINF,dn.stbl(t))}static moof(t,i,s){return dn.box(dn.types.moof,dn.mfhd(t),dn.traf(s,i))}static moov(t){let i=t.length;const s=[];for(;i--;)s[i]=dn.trak(t[i]);return dn.box.apply(null,[dn.types.moov,dn.mvhd(t[0].timescale||0,t[0].duration||0)].concat(s).concat(dn.mvex(t)))}static mvex(t){let i=t.length;const s=[];for(;i--;)s[i]=dn.trex(t[i]);return dn.box.apply(null,[dn.types.mvex,...s])}static mvhd(t,i){i*=t;const s=Math.floor(i/(cn+1)),e=Math.floor(i%(cn+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 dn.box(dn.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 dn.box(dn.types.sdtp,s)}static stbl(t){return dn.box(dn.types.stbl,dn.stsd(t),dn.box(dn.types.stts,dn.STTS),dn.box(dn.types.stsc,dn.STSC),dn.box(dn.types.stsz,dn.STSZ),dn.box(dn.types.stco,dn.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=dn.box(dn.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],u=t.pixelRatio[1];return dn.box(dn.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,dn.box(dn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),dn.box(dn.types.pasp,new Uint8Array([l>>24,l>>16&255,l>>8&255,255&l,u>>24,u>>16&255,u>>8&255,255&u])))}static esds(t){return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t.config,6,1,2])}static audioStsd(t){const i=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,i>>8&255,255&i,0,0])}static mp4a(t){return dn.box(dn.types.mp4a,dn.audioStsd(t),dn.box(dn.types.esds,dn.esds(t)))}static mp3(t){return dn.box(dn.types[".mp3"],dn.audioStsd(t))}static ac3(t){return dn.box(dn.types["ac-3"],dn.audioStsd(t),dn.box(dn.types.dac3,t.config))}static stsd(t){const{segmentCodec:i}=t;if("audio"===t.type){if("aac"===i)return dn.box(dn.types.stsd,dn.STSD,dn.mp4a(t));if("ac3"===i&&t.config)return dn.box(dn.types.stsd,dn.STSD,dn.ac3(t));if("mp3"===i&&"mp3"===t.codec)return dn.box(dn.types.stsd,dn.STSD,dn.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===i)return dn.box(dn.types.stsd,dn.STSD,dn.avc1(t));if("hevc"===i&&t.vps)return dn.box(dn.types.stsd,dn.STSD,dn.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${i}/${t.codec})`)}static tkhd(t){const i=t.id,s=(t.duration||0)*(t.timescale||0),e=t.width||0,n=t.height||0,r=Math.floor(s/(cn+1)),h=Math.floor(s%(cn+1));return dn.box(dn.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=dn.sdtp(t),e=t.id,n=Math.floor(i/(cn+1)),r=Math.floor(i%(cn+1));return dn.box(dn.types.traf,dn.box(dn.types.tfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e])),dn.box(dn.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])),dn.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,dn.box(dn.types.trak,dn.tkhd(t),dn.mdia(t))}static trex(t){const i=t.id;return dn.box(dn.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,u,c;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,u=o.flags,c=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,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*h);return dn.box(dn.types.trun,r)}static initSegment(t){dn.types||dn.init();const i=dn.moov(t);return Tt(dn.FTYP,i)}static hvc1(t){const i=t.params,s=[t.vps,t.sps,t.pps],e=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),s.length]);let n=e.length;for(let t=0;t<s.length;t+=1){n+=3;for(let i=0;i<s[t].length;i+=1)n+=2+s[t][i].length}const r=new Uint8Array(n);r.set(e,0),n=e.length;const h=s.length-1;for(let t=0;t<s.length;t+=1){r.set(new Uint8Array([32+t|(t===h?128:0),0,s[t].length]),n),n+=3;for(let i=0;i<s[t].length;i+=1)r.set(new Uint8Array([s[t][i].length>>8,255&s[t][i].length]),n),n+=2,r.set(s[t][i],n),n+=s[t][i].length}const o=dn.box(dn.types.hvcC,r),a=t.width,l=t.height,u=t.pixelRatio[0],c=t.pixelRatio[1];return dn.box(dn.types.hvc1,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,a>>8&255,255&a,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,dn.box(dn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),dn.box(dn.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))}}dn.types=void 0,dn.HDLR_TYPES=void 0,dn.STTS=void 0,dn.STSC=void 0,dn.STCO=void 0,dn.STSZ=void 0,dn.VMHD=void 0,dn.SMHD=void 0,dn.STSD=void 0,dn.FTYP=void 0,dn.DINF=void 0;function fn(t,i,s=1,e=!1){const n=t*i*s;return e?Math.round(n):n}function vn(t,i=!1){return fn(t,1e3,1/9e4,i)}let gn,pn=null,mn=null;function yn(t,i,s,e){return{duration:i,size:s,cts:e,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class bn extends P{constructor(t,i,s,e){if(super("mp4-remuxer",e),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=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===pn){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);pn=t?parseInt(t[1]):0}if(null===mn){const t=navigator.userAgent.match(/Safari\/(\d+)/i);mn=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){this.log("initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("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=wn(n,s),r=n-t),r>0?t:n}),s);return i&&this.debug("PTS rollover detected"),e}remux(t,i,s,e,n,r,h,o){let a,l,u,c,d,f,v=n,g=n;const p=i.pid>-1,m=i.samples.length,y=t.samples.length>0,b=h&&m>0||m>1;if((!(t.pid>-1)||y)&&(!p||b)||this.ISGenerated||h){if(this.ISGenerated){var w,$,k,S;const t=this.videoTrackConfig;(t&&(i.width!==t.width||i.height!==t.height||(null==(w=i.pixelRatio)?void 0:w[0])!==(null==($=t.pixelRatio)?void 0:$[0])||(null==(k=i.pixelRatio)?void 0:k[1])!==(null==(S=t.pixelRatio)?void 0:S[1]))||!t&&b||null===this.nextAudioTs&&y)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(t,i,n,r));const s=this.isVideoContiguous;let e,h=-1;if(b&&(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){this.warn(`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,g+=(i.samples[0].pts-t)/i.inputTimeScale,e=g}else-1===h&&(this.warn(`No keyframe found out of ${m} video samples`),f=!1);if(this.ISGenerated){if(y&&b){const s=this.getVideoStartPts(i.samples),e=(wn(t.samples[0].pts,s)-s)/i.inputTimeScale;v+=Math.max(0,e),g+=Math.max(0,-e)}if(y){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(t,i,n,r)),l=this.remuxAudio(t,v,this.isAudioContiguous,r,p||b||o===T?g:void 0),b){const e=l?l.endPTS-l.startPTS:0;i.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(t,i,n,r)),a=this.remuxVideo(i,g,s,e)}}else b&&(a=this.remuxVideo(i,g,s,0));a&&(a.firstKeyFrame=h,a.independent=-1!==h,a.firstKeyFramePTS=e)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(d=$n(s,n,this._initPTS,this._initDTS)),e.samples.length&&(c=kn(e,n,this._initPTS))),{audio:l,video:a,initSegment:u,independent:f,text:c,id3:d}}generateIS(t,i,s,e){const n=t.samples,r=i.samples,h=this.typeSupported,o={},a=this._initPTS;let l,u,c,d,f=!a||e,v="audio/mp4";if(f&&(l=u=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":h.mpeg?(v="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:v,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):dn.initSegment([t]),metadata:{channelCount:t.channelCount}},f&&(d=t.id,c=t.inputTimeScale,a&&c===a.timescale?f=!1:l=u=n[0].pts-Math.round(c*s))}if(i.sps&&i.pps&&r.length){if(i.timescale=i.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:i.codec,initSegment:dn.initSegment([i]),metadata:{width:i.width,height:i.height}},f)if(d=i.id,c=i.inputTimeScale,a&&c===a.timescale)f=!1;else{const t=this.getVideoStartPts(r),i=Math.round(c*s);u=Math.min(u,wn(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,f?(this._initPTS={baseTime:l,timescale:c},this._initDTS={baseTime:u,timescale:c}):l=c=void 0,{tracks:o,initPTS:l,timescale:c,trackId:d}}remuxVideo(t,i,s,e){const n=t.inputTimeScale,r=t.samples,h=[],o=r.length,a=this._initPTS,l=a.baseTime*n/a.timescale;let u,c,d=this.nextVideoTs,f=8,v=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,w=!1;if(!s||null===d){const t=l+i*n,e=r[0].pts-wn(r[0].dts,r[0].pts);pn&&null!==d&&Math.abs(t-e-(d+l))<15e3?s=!0:d=t-e-l}const $=d+l;for(let t=0;t<o;t++){const i=r[t];i.pts=wn(i.pts,$),i.dts=wn(i.dts,$),i.dts<r[t>0?t-1:t].dts&&(w=!0)}w&&r.sort((function(t,i){return t.dts-i.dts||t.pts-i.pts})),u=r[0].dts,c=r[r.length-1].dts;const k=c-u,S=k?Math.round(k/(o-1)):v||t.inputTimeScale/30;if(s){const s=u-$,e=s>S,n=s<-1;if((e||n)&&(this.warn(e?`${(t.segmentCodec||"").toUpperCase()}: ${vn(s,!0)} ms (${s}dts) hole between fragments detected at ${i.toFixed(3)}`:`${(t.segmentCodec||"").toUpperCase()}: ${vn(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${i.toFixed(3)}`),!n||$>=r[0].pts||pn)){u=$;const t=r[0].pts-s;if(e)r[0].dts=u,r[0].pts=t;else{let i=!0;for(let e=0;e<r.length&&!(r[e].dts>t&&i);e++){const t=r[e].pts;if(r[e].dts-=s,r[e].pts-=s,e<r.length-1){const s=r[e+1].pts;i=s<=r[e].pts==s<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${vn(t,!0)}/${vn(u,!0)}, delta: ${vn(s,!0)} ms`)}}u=Math.max(0,u);let T=0,E=0,A=u;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;E+=n,T+=e,i.length=n,i.dts<A?(i.dts=A,A+=S/4|0||1):A=i.dts,g=Math.min(i.pts,g),b=Math.max(i.pts,b)}c=r[o-1].dts;const L=E+4*T+8;let M;try{M=new Uint8Array(L)}catch(t){return void this.observer.emit(y.ERROR,y.ERROR,{type:p.MUX_ERROR,details:m.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:L,reason:`fail allocating video mdat ${L}`})}const I=new DataView(M.buffer);I.setUint32(0,L),M.set(dn.types.mdat,4);let D=!1,P=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const i=r[t],s=i.units;let a,u=0;for(let t=0,i=s.length;t<i;t++){const i=s[t],e=i.data,n=i.data.byteLength;I.setUint32(f,n),f+=4,M.set(e,f),f+=n,u+=4+n}if(t<o-1)v=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:S;if(a=t>0?i.pts-r[t-1].pts:S,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(s.maxBufferHole*n),r=(e?g+e*n:this.nextAudioTs+l)-i.pts;r>t?(v=r-h,v<0?v=h:D=!0,this.log(`It is approximately ${r/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=h}else v=h}const c=Math.round(i.pts-i.dts);P=Math.min(P,v),R=Math.max(R,v),C=Math.min(C,a),O=Math.max(O,a),h.push(yn(i.key,v,u,c))}if(h.length)if(pn){if(pn<70){const t=h[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(mn&&O-C<R-P&&S/R<.025&&0===h[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=u;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:S,h[i].cts=0,t=e}}v=D||!v?S:v,this.nextVideoTs=d=c+v-l,this.videoSampleDuration=v,this.isVideoContiguous=!0;const N={data1:dn.moof(t.sequenceNumber++,u,x(t,{samples:h})),data2:M,startPTS:(g-l)/n,endPTS:(b+v-l)/n,startDTS:(u-l)/n,endDTS:d/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,u="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],d=void 0!==n;let f=t.samples,v=u?0:8,g=this.nextAudioTs||-1;const b=l.baseTime*r/l.timescale,w=b+i*r;if(this.isAudioContiguous=s=s||f.length&&g>0&&(e&&Math.abs(w-(g+b))<9e3||Math.abs(wn(f[0].pts,w)-(g+b))<20*a),f.forEach((function(t){t.pts=wn(t.pts,w)})),!s||g<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;g=0===n?0:e&&!d?Math.max(0,w-b):f[0].pts-b}if("aac"===t.segmentCodec){const i=this.config.maxAudioFramesDrift;for(let s=0,e=g+b;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&&(this.warn(`Audio frame @ ${(h/r).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/r)} ms.`),this.nextAudioTs=g=h-b,e=h);else if(o>=i*a&&l<1e4&&d){let i=Math.round(o/a);for(e=h-i*a;e<0&&i&&a;)i--,e+=a;0===s&&(this.nextAudioTs=g=e-b),this.warn(`Injecting ${i} audio frames @ ${((e-b)/r).toFixed(3)}s due to ${Math.round(1e3*o/r)} ms gap.`);for(let r=0;r<i;r++){let i=un.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);i||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),i=n.unit.subarray()),f.splice(s,0,{unit:i,pts:e}),e+=a,s++}}n.pts=e,e+=a}}let $,k=null,S=null,T=0,E=f.length;for(;E--;)T+=f[E].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!==S)c[i-1].duration=Math.round((r-S)/h);else{if(s&&"aac"===t.segmentCodec&&(r=g+b),k=r,!(T>0))return;T+=v;try{$=new Uint8Array(T)}catch(t){return void this.observer.emit(y.ERROR,y.ERROR,{type:p.MUX_ERROR,details:m.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:T,reason:`fail allocating audio mdat ${T}`})}u||(new DataView($.buffer).setUint32(0,T),$.set(dn.types.mdat,4))}$.set(n,v);const a=n.byteLength;v+=a,c.push(yn(!0,o,a,0)),S=r}const A=c.length;if(!A)return;g=S-b,this.nextAudioTs=g+h*c[c.length-1].duration;const L=u?new Uint8Array(0):dn.moof(t.sequenceNumber++,k/h,x({},t,{samples:c}));t.samples=[];const M=(k-b)/r,I=g/r,D={data1:L,data2:$,startPTS:M,endPTS:I,startDTS:M,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,D}}function wn(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 $n(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=wn(n.pts-s.baseTime*r/s.timescale,i*r)/r,n.dts=wn(n.dts-e.baseTime*r/e.timescale,i*r)/r}const h=t.samples;return t.samples=[],{samples:h}}function kn(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=wn(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}}function Sn(t,i,s=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(s?t.duration:0))/t.timescale:i}function Tn(t,i,s){const e=null==t?void 0:t.codec;return e&&e.length>4?e:i===Z?"ec-3"===e||"ac-3"===e||"alac"===e?e:"fLaC"===e||"Opus"===e?jt(e,!1):(s.warn(`Unhandled audio codec "${e}" in mp4 MAP`),e||"mp4a"):(s.warn(`Unhandled video codec "${e}" in mp4 MAP`),e||"avc1")}try{gn=self.performance.now.bind(self.performance)}catch(t){gn=Date.now}const En=[{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=Ce("video",1),r=this.audioTrack=Ce("audio",1),h=this.txtTrack=Ce("text",1);if(this.id3Track=Ce("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=mt(t);if(o.video){const{id:t,timescale:i,codec:s,supplemental:e}=o.video;n.id=t,n.timescale=h.timescale=i,n.codec=s,n.supplemental=e}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=dt(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=Tt(this.remainderData,t));const i=function(t){const i={valid:null,remainder:null},s=gt(t,["moof"]);if(s.length<2)return i.remainder=t,i;const e=s[s.length-1];return i.valid=t.slice(0,e.byteOffset-8),i.remainder=t.slice(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=Et(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=Et(t,i),{videoTrack:i,audioTrack:Ce(),id3Track:e,textTrack:Ce()}}extractID3Track(t,i){const s=this.id3Track;if(t.samples.length){const e=gt(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"!==ut(t.subarray(l,l+1));)s+=ut(t.subarray(l,l+1)),l+=1;for(s+=ut(t.subarray(l,l+1)),l+=1;"\0"!==ut(t.subarray(l,l+1));)e+=ut(t.subarray(l,l+1)),l+=1;e+=ut(t.subarray(l,l+1)),l+=1,n=dt(t,12),r=dt(t,16),o=dt(t,20),a=dt(t,24),l=28}else if(1===i){l+=4,n=dt(t,l),l+=4;const i=dt(t,l);l+=4;const r=dt(t,l);for(l+=4,h=2**32*i+r,v(h)||(h=Number.MAX_SAFE_INTEGER,F.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=dt(t,l),l+=4,a=dt(t,l),l+=4;"\0"!==ut(t.subarray(l,l+1));)s+=ut(t.subarray(l,l+1)),l+=1;for(s+=ut(t.subarray(l,l+1)),l+=1;"\0"!==ut(t.subarray(l,l+1));)e+=ut(t.subarray(l,l+1)),l+=1;e+=ut(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(ze.test(e.schemeIdUri)){const t=qe(e,i);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:Pe.emsg,duration:n})}else if(this.config.enableEmsgKLVMetadata&&e.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=qe(e,i);s.samples.push({data:e.payload,len:e.payload.byteLength,dts:t,pts:t,type:Pe.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(t,i,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends P{constructor(t,i,s,e){super("passthrough-remuxer",e),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,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const i=this.initPTS;i&&t&&i.baseTime===t.baseTime&&i.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,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&>(t,["moov","trak"]).forEach((t=>{const i=gt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let e=gt(i,["enca"]);const n=e.length>0;n||(e=gt(i,["encv"])),e.forEach((t=>{gt(t.subarray(n?28:78),["sinf"]).forEach((t=>{const i=St(t);if(i){const t=i.subarray(8,24);t.some((t=>0!==t))||(F.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${G(t)} -> ${G(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=mt(t);e.audio&&(i=Tn(e.audio,Z,this)),e.video&&(s=Tn(e.video,tt,this));const n={};e.audio&&e.video?n.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:e.video.supplemental,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,supplemental:e.video.supplemental,initSegment:t,id:"main"}:this.warn("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 u={audio:void 0,video:void 0,text:e,id3:s,initSegment:void 0};f(l)||(l=this.lastEndTime=n||0);const c=i.samples;if(null==c||!c.length)return u;const d={initPTS:void 0,timescale:void 0,trackId:void 0};let v=this.initData;if(null!=(h=v)&&h.length||(this.generateInitSegment(c),v=this.initData),null==(o=v)||!o.length)return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,i,s){const e={},n=gt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const r=n[t],h=gt(r,["tfhd"])[0],o=dt(h,4),a=i[o];if(!a)continue;const l=e[o]||(e[o]={start:NaN,duration:0,sampleCount:0,timescale:a.timescale,type:a.type}),u=gt(r,["tfdt"])[0];if(u){const t=u[0];let i=dt(u,4);1===t&&(i===ot?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(i*=ot+1,i+=dt(u,8))),f(i)&&(!f(l.start)||i<l.start)&&(l.start=i)}const c=a.default,d=dt(h,0)|(null==c?void 0:c.flags);let v=(null==c?void 0:c.duration)||0;8&d&&(v=dt(h,2&d?12:8));const g=gt(r,["trun"]);let p=l.start||0,m=0,y=v;for(let t=0;t<g.length;t++){const i=g[t],s=dt(i,4),e=l.sampleCount;l.sampleCount+=s;const n=1&i[2],r=2&i[2],h=4&i[2],o=8&i[2];let a=8,u=s;for(1&i[3]&&(a+=4),4&i[3]&&s&&(1&i[a+1]||void 0!==l.keyFrameIndex||(l.keyFrameIndex=e),a+=4,n?(y=dt(i,a),a+=4):y=v,r&&(a+=4),o&&(a+=4),p+=y,m+=y,u--);u--;)n?(y=dt(i,a),a+=4):y=v,r&&(a+=4),h&&(1&i[a+1]||void 0===l.keyFrameIndex&&(l.keyFrameIndex=l.sampleCount-(u+1),l.keyFrameStart=p),a+=4),o&&(a+=4),p+=y,m+=y;!m&&v&&(m+=v*s)}l.duration+=m}if(!Object.keys(e).some((t=>e[t].duration))){let i=0;const s=gt(t,["sidx"]);for(let t=0;t<s.length;t++){const e=pt(s[t]);if(null!=e&&e.references){const t=e.references.reduce(((t,i)=>t+i.info.duration||0),0);i=Math.max(i,t+e.earliestPresentationTime/e.timescale)}}i&&f(i)&&Object.keys(e).forEach((t=>{e[t].duration||(e[t].duration=i*e[t].timescale-e[t].start)}))}return e}(c,v,this),p=v.audio?g[v.audio.id]:null,m=v.video?g[v.video.id]:null,y=Sn(m,1/0),b=Sn(p,1/0),w=Sn(m,0,!0),$=Sn(p,0,!0);let k,S=n,T=0;if(p&&(!m||!a&&b<y||a&&a.trackId===v.audio.id)?(d.trackId=v.audio.id,k=p,T=$-b):m&&(d.trackId=v.video.id,k=m,T=w-y),k){const t=k.timescale;S=k.start/t,d.initPTS=k.start-n*t,d.timescale=t,a||(this.initPTS=a={baseTime:d.initPTS,timescale:t,trackId:d.trackId})}!r&&a||!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,S,n,T)&&d.timescale===a.timescale||(d.initPTS=S-n,d.timescale=1,a&&1===a.timescale&&this.warn(`Adjusting initPTS @${n} from ${a.baseTime/a.timescale} to ${d.initPTS}`),this.initPTS=a={baseTime:d.initPTS,timescale:1});const E=t?S-a.baseTime/a.timescale:l,A=E+T;T>0?this.lastEndTime=A:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const L=!!v.audio,M=!!v.video;let x="";L&&(x+="audio"),M&&(x+="video");const I={data1:c,startPTS:E,startDTS:E,endPTS:A,endDTS:A,type:x,hasAudio:L,hasVideo:M,nb:1,dropped:0};u.audio=L&&!M?I:void 0,u.video=M?I:void 0;const D=null==m?void 0:m.sampleCount;if(D){const t=m.keyFrameIndex,i=-1!==t;I.nb=D,I.dropped=0===t||this.isVideoContiguous?0:i?t:D,I.independent=i,I.firstKeyFrame=t,i&&m.keyFrameStart&&(I.firstKeyFramePTS=(m.keyFrameStart-a.baseTime)/a.timescale),this.isVideoContiguous||(u.independent=i),this.isVideoContiguous||(this.isVideoContiguous=i),I.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${D} dropped: ${I.dropped} start: ${I.firstKeyFramePTS||"NA"}`)}return u.initSegment=d,u.id3=$n(s,n,a,a),e.samples.length&&(u.text=kn(e,n,a)),u}}},{demux:en,remux:bn},{demux:class extends Re{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,i){if(!t)return!1;const s=fe(t,0);let e=(null==s?void 0:s.length)||0;if(Ve(t,e))return!1;for(let s=t.length;e<s;e++)if(ye(t,e))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)&&ve(t,i)&&pe(t,i)<=t.length-i}(t,i)}appendFrame(t,i,s){be(t,this.observer,i,s,t.manifestCodec);const e=$e(t,i,s,this.basePTS,this.frameIndex);if(e&&0===e.missing)return e}},remux:bn},{demux:class extends Re{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=fe(t,0);let s=(null==i?void 0:i.length)||0;if(i&&11===t[s]&&119===t[s+1]&&void 0!==De(i)&&Xe(t,s)<=16)return!1;for(let i=t.length;s<i;s++)if(Ve(t,s))return F.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,i){return function(t,i){return He(t,i)&&4<=t.length-i}(t,i)}appendFrame(t,i,s){if(null!==this.basePTS)return je(t,i,s,this.basePTS,this.frameIndex)}},remux:bn}];En.splice(2,0,{demux:class extends Re{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=We(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=fe(t,0);if(!i)return!1;const s=i.length;return 11===t[s]&&119===t[s+1]&&void 0!==De(i)&&Xe(t,s)<16}},remux:bn});class An{constructor(t,i,s,e,n,r){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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.id=n,this.logger=r}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,i,s,e){const n=s.transmuxing;n.executeStart=gn();let r=new Uint8Array(t);const{currentTransmuxState:h,transmuxConfig:o}=this;e&&(this.currentTransmuxState=e);const{contiguous:a,discontinuity:l,trackSwitch:u,accurateTimeOffset:c,timeOffset:d,initSegmentChange:f}=e||h,{audioCodec:v,videoCodec:g,defaultInitPts:b,duration:w,initSegmentData:$}=o,k=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(k&&es(k.method)){const t=this.getDecrypter(),i=ns(k.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(r,k.key.buffer,k.iv.buffer,i).then((t=>{const i=this.push(t,null,s);return this.decryptionPromise=null,i})),this.decryptionPromise;{let e=t.softwareDecrypt(r,k.key.buffer,k.iv.buffer,i);if(s.part>-1){const i=t.flush();e=i?i.buffer:i}if(!e)return n.executeEnd=gn(),Ln(s);r=new Uint8Array(e)}}const S=this.needsProbing(l,u);if(S){const t=this.configureTransmuxer(r);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),n.executeEnd=gn(),Ln(s)}(l||u||f||S)&&this.resetInitSegment($,v,g,w,i),(l||f||S)&&this.resetInitialTimestamp(b),a||this.resetContiguity();const T=this.transmux(r,k,d,c,s);this.asyncResult=Mn(T);const E=this.currentTransmuxState;return E.contiguous=!0,E.discontinuity=!1,E.trackSwitch=!1,n.executeEnd=gn(),T}flush(t){const i=t.transmuxing;i.executeStart=gn();const{decrypter:s,currentTransmuxState:e,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then((()=>this.flush(t)));const r=[],{timeOffset:h}=e;if(s){const i=s.flush();i&&r.push(this.push(i.buffer,null,t))}const{demuxer:o,remuxer:a}=this;if(!o||!a){i.executeEnd=gn();const s=[Ln(t)];return this.asyncResult?Promise.resolve(s):s}const l=o.flush(h);return Mn(l)?(this.asyncResult=!0,l.then((i=>(this.flushRemux(r,i,t),r)))):(this.flushRemux(r,l,t),this.asyncResult?Promise.resolve(r):r)}flushRemux(t,i,s){const{audioTrack:e,videoTrack:n,id3Track:r,textTrack:h}=i,{accurateTimeOffset:o,timeOffset:a}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===S?"level":"track"} ${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=gn()}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}=this;let n;for(let i=0,s=En.length;i<s;i++){var r;if(null!=(r=En[i].demux)&&r.probe(t,this.logger)){n=En[i];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const h=this.demuxer,o=this.remuxer,a=n.remux,l=n.demux;o&&o instanceof a||(this.remuxer=new a(s,i,e,this.logger)),h&&h instanceof l||(this.demuxer=new l(s,i,e,this.logger),this.probe=l.probe)}needsProbing(t,i){return!this.demuxer||!this.remuxer||t||i}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Ni(this.config)),t}}const Ln=t=>({remuxResult:{},chunkMeta:t});function Mn(t){return"then"in t&&t.then instanceof Function}class xn{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 In{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}}let Dn=0;class Pn{constructor(t,i,s,e){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Dn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const i=t.data,s=this.hls;if(s&&null!=i&&i.event&&i.instanceNo===this.instanceNo)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":s.logger[i.data.logType]&&s.logger[i.data.logType](i.data.message);break;default:i.data=i.data||{},i.data.frag=this.frag,i.data.part=this.part,i.data.id=this.id,s.trigger(i.event,i.data)}},this.onWorkerError=t=>{if(!this.hls)return;const i=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})};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||void 0,t===y.ERROR&&(i.parent=this.id,i.part=this.part,this.error=i.error),this.hls.trigger(t,i)};this.observer=new oe,this.observer.on(y.FRAG_DECRYPTED,r),this.observer.on(y.ERROR,r);const h=Vt(n.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(n.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{n.workerPath?(s.log(`loading Web Worker ${n.workerPath} for "${i}"`),this.workerContext=function(t){const i=le[t];if(i)return i.clientCount++,i;const s=new self.URL(t,self.location.href).href,e={worker:new self.Worker(s),scriptURL:s,clientCount:1};return le[t]=e,e}(n.workerPath)):(s.log(`injecting Web Worker for "${i}"`),this.workerContext=function(){const t=le[ae];if(t)return t.clientCount++,t;const i=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(i),e={worker:new self.Worker(s),objectURL:s,clientCount:1};return le[ae]=e,e}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:h,id:i,config:ri(n)})}catch(e){s.warn(`Error setting up "${i}" Web Worker, fallback to inline`,e),this.terminateWorker(),this.error=null,this.transmuxer=new An(this.observer,h,n,"",i,t.logger)}return}}this.transmuxer=new An(this.observer,h,n,"",i,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Dn++;const i=this.hls.config,s=Vt(i.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:ri(i)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const i=le[t||ae];if(i&&1==i.clientCount--){const{worker:s,objectURL:e}=i;delete le[t||ae],e&&self.URL.revokeObjectURL(e),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,i,s,e,n,r,h,o,a,l){var u,c;a.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,v=r?r.start:n.start,g=n.decryptdata,p=this.frag,m=!(p&&n.cc===p.cc),y=!(p&&a.level===p.level),b=p?a.sn-p.sn:-1,w=this.part?a.part-this.part.index:-1,$=!y&&(1===b||0===b&&(1===w||0===b&&a.id>1&&a.id===(null==p?void 0:p.stats.chunkCount)&&w<=0)),k=self.performance.now();(y||b||0===n.stats.parsing.start)&&(n.stats.parsing.start=k),!r||!w&&$||(r.stats.parsing.start=k);const T=!(p&&(null==(u=n.initSegment)?void 0:u.url)===(null==(c=p.initSegment)?void 0:c.url)),E=new In(m,$,o,y,v,T);if(!$||m||T){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${a.sn}${a.part>-1?" part: "+a.part:""} ${this.id===S?"level":"track"}: ${a.level} id: ${a.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${$}\n accurateTimeOffset: ${o}\n timeOffset: ${v}\n initSegmentChange: ${T}`);const t=new xn(s,e,i,h,l);this.configureTransmuxer(t)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:t,decryptdata:g,chunkMeta:a,state:E},t instanceof ArrayBuffer?[t]:[]);else if(f){const i=f.push(t,g,a,E);Mn(i)?i.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,a,"transmuxer-interface push error")})):this.handleTransmuxComplete(i)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:i,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:t});else if(s){const i=s.flush(t);Mn(i)?i.then((i=>{this.handleFlushResult(i,t)})).catch((i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")})):this.handleFlushResult(i,t)}}transmuxerError(t,i,s){this.hls&&(this.error=t,this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_PARSING_ERROR,chunkMeta:i,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,i){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(i)}configureTransmuxer(t){const{instanceNo:i,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:i,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class Cn extends P{constructor(t,i){super(i,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,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.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){this.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&&ii(s);return new si(r,h>=0?h:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,i){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,i){if(i)try{return i.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return 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;e.advancedDateTime=Date.now()-h;const o=this.hls.config.timelineOffset;if(o!==e.appliedTimelineOffset){const t=Math.max(o||0,0);e.appliedTimelineOffset=t,e.fragments.forEach((i=>{i.start=i.playlistOffset+t}))}if(e.live||null!=s&&s.live){const o="levelInfo"in i?i.levelInfo:i.track;if(e.reloaded(s),s&&e.fragments.length>0){!function(t,i){if(t===i)return;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 l=n;l<=r;l++){const n=a[h+l];let r=o[l];if(e&&!r&&n&&(r=i.fragments[l]=n),n&&r){if(s(n,r,l,o),n.url&&n.url!==r.url)return void(i.playlistParsingError=js(`media sequence mismatch ${r.sn}:`,t,i,0,r));if(n.cc!==r.cc)return void(i.playlistParsingError=js(`discontinuity sequence mismatch (${n.cc}!=${r.cc})`,t,i,0,r))}}}(t,i,((t,e,r,h)=>{if((!i.startCC||i.skippedSegments)&&e.cc!==t.cc){const s=t.cc-e.cc;for(let t=r;t<h.length;t++)h[t].cc+=s;i.endCC=h[h.length-1].cc}f(t.startPTS)&&f(t.endPTS)&&(e.setStart(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.setDuration(t.endPTS-t.startPTS),e.duration&&(n=e),i.PTSKnown=i.alignedSliding=!0),t.hasStreams&&(e.elementaryStreams=t.elementaryStreams),e.loader=t.loader,t.hasStats&&(e.stats=t.stats),t.initSegment&&(e.initSegment=t.initSegment,s=t.initSegment)}));const r=i.fragments,h=i.fragmentHint?r.concat(i.fragmentHint):r;if(s&&h.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){F.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){const{dateRanges:s,recentlyRemovedDateranges:e}=i,n=x({},t);e&&e.forEach((t=>{delete n[t]}));const r=Object.keys(n).length;return r&&Object.keys(s).forEach((t=>{const i=n[t],e=new is(s[t].attr,i);e.isValid?(n[t]=e,i||(e.tagOrder+=r)):F.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ri(s[t].attr)}"`)})),n}(t.dateRanges,i));const s=t.fragments.filter((t=>t.rawProgramDateTime));if(t.hasProgramDateTime&&!i.hasProgramDateTime)for(let t=1;t<h.length;t++)null===h[t].programDateTime&&Rs(h[t],h[t-1],s);Ms(s,i)}i.endCC=r[r.length-1].cc}if(!i.startCC){var o;const s=Vs(t,i.startSN-1);i.startCC=null!=(o=null==s?void 0:s.cc)?o:r[0].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?_s(i,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Gs(t,i),r.length&&(i.totalduration=i.edge-r[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const a=i.advancedDateTime;if(i.advanced&&a){const t=i.edge;i.driftStart||(i.driftStartTime=a,i.driftStart=t),i.driftEndTime=a,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}(s,e);const t=e.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var a;const{networkDetails:r}=i;return void s.trigger(y.ERROR,{type:p.NETWORK_ERROR,details:m.LEVEL_PARSING_ERROR,fatal:!1,url:e.url,error:t,reason:t.message,level:i.level||void 0,parent:null==(a=e.fragments[0])?void 0:a.type,networkDetails:r,stats:n})}e.playlistParsingError=null}}-1===e.requestScheduled&&(e.requestScheduled=n.loading.start);const l=this.hls.mainForwardBufferInfo,u=Ks(e,1e3*(e.edge-(l?l.end-l.len:0)));if(e.requestScheduled+u<r?e.requestScheduled=r:e.requestScheduled+=u,this.log(`live playlist ${t} ${e.advanced?"REFRESHED "+e.lastPartSn+"-"+e.lastPartIndex:e.updated?"UPDATED":"MISSED"}`),!this.canLoad||!e.live)return;let c,d,v;if(e.canBlockReload&&e.endSN&&e.advanced){const t=this.hls.config.lowLatencyMode,n=e.lastPartSn,h=e.endSN,a=e.lastPartIndex,l=n===h;-1!==a?l?(d=h+1,v=t?0:a):(d=n,v=t?a+1:e.maxPartIndex):d=h+1;const u=e.age,f=u+e.ageHeader;let g=Math.min(f-e.partTarget,1.5*e.targetduration);if(g>0){if(f>3*e.targetduration)this.log(`Playlist last advanced ${u.toFixed(2)}s ago. Omitting segment and part directives.`),d=void 0,v=void 0;else if(null!=s&&s.tuneInGoal&&f-e.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${g} with playlist age: ${e.age}`),g=0;else{const t=Math.floor(g/e.targetduration);d+=t,void 0!==v&&(v+=Math.round(g%e.targetduration/e.partTarget)),this.log(`CDN Tune-in age: ${e.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${g} skip sn ${t} to part ${v}`)}e.tuneInGoal=g}if(c=this.getDeliveryDirectives(e,i.deliveryDirectives,d,v),t||!l)return e.requestScheduled=r,void this.loadingPlaylist(o,c)}else(e.canBlockReload||e.canSkipUntil)&&(c=this.getDeliveryDirectives(e,i.deliveryDirectives,d,v));c&&void 0!==d&&e.canBlockReload&&(e.requestScheduled=n.loading.first+Math.max(u-2*h,u/2)),this.scheduleLoading(o,c,e)}else this.clearTimer()}scheduleLoading(t,i,s){const e=s||t.details;if(!e)return void this.loadingPlaylist(t,i);const n=self.performance.now(),r=e.requestScheduled;if(n>=r)return void this.loadingPlaylist(t,i);const h=r-n;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(h)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(t,i)),h)}getDeliveryDirectives(t,i,s,e){let n=ii(t);return null!=i&&i.skip&&t.deltaUpdateFailed&&(s=i.msn,e=i.part,n=""),new si(s,e,n)}checkRetry(t){const i=t.details,s=bi(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(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=$i(h,r);this.clearTimer(),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}}function Rn(t,i){if(t.length!==i.length)return!1;for(let s=0;s<t.length;s++)if(!On(t[s].attrs,i[s].attrs))return!1;return!0}function On(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 Nn(t,i){return i.label.toLowerCase()===t.name.toLowerCase()&&(!i.language||i.language.toLowerCase()===(t.lang||"").toLowerCase())}class Un{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,i,s){if(null===this.queues||null===this.tracks)return;const e=this.queues[i];e.push(t),1!==e.length||s||this.executeNext(i)}appendBlocker(t){return new Promise((i=>{this.append({label:"async-blocker",execute:i,onStart:()=>{},onComplete:()=>{},onError:()=>{}},t)}))}prependBlocker(t){return new Promise((i=>{this.queues&&this.queues[t].unshift({label:"async-blocker-prepend",execute:i,onStart:()=>{},onComplete:()=>{},onError:()=>{}})}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t=>{var i;const s=null==(i=t[0])?void 0:i.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(t[0].execute(),t.splice(0,1))}))}unblockAudio(t){null!==this.queues&&this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];if(i.length){const e=i[0];try{e.execute()}catch(i){var s;if(e.onError(i),null===this.queues||null===this.tracks)return;const n=null==(s=this.tracks[t])?void 0:s.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var i;return(null==(i=this.queues)?void 0:i[t][0])||null}toString(){const{queues:t,tracks:i}=this;return null===t||null===i?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var i,s;return null!=(i=this.queues)&&i[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var i;const s=null==(i=this.tracks)?void 0:i[t],e=null==s?void 0:s.buffer;return e?`SourceBuffer${e.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var i;return(null==(i=this.queues)?void 0:i[t].map((t=>t.label)).join(", "))||""}}const Fn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Bn="HlsJsTrackRemovedError";class _n extends Error{constructor(t){super(t),this.name=Bn}}function jn(t){const i=t.querySelectorAll("source");[].slice.call(i).forEach((i=>{t.removeChild(i)}))}function Gn(t){return"audio"===t?1:0}class Hn{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(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.BUFFER_CODECS,this.onBufferCodecs,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.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&&f(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,i){this.hls.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}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.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),i.autoLevelCapping=s,i.autoLevelEnabled&&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,Hn.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 Math.min(t,this.hls.config.maxDevicePixelRatio)}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 Kn="m",Vn="a",Xn="v",Wn="av",zn="i",qn="tt",Yn="h",Qn="CMCD-Object",Jn="CMCD-Request",Zn="CMCD-Session",tr="CMCD-Status",ir={[Qn]:["br","d","ot","tb"],[Jn]:["bl","dl","mtp","nor","nrr","su"],[Zn]:["cid","pr","sf","sid","st","v"],[tr]:["bs","rtp"]};class sr{constructor(t,i){Array.isArray(t)&&(t=t.map((t=>t instanceof sr?t:new sr(t)))),this.value=t,this.params=i}}const er="Dict";function nr(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)}class rr{constructor(t){this.description=t}}const hr="Bare Item",or="Boolean",ar="Byte Sequence";const lr="Integer";function ur(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw nr(t,lr);return t.toString()}function cr(t,i){if(t<0)return-cr(-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}const dr="Decimal";function fr(t){const i=cr(t,3);if(Math.floor(Math.abs(i)).toString().length>12)throw nr(t,dr);const s=i.toString();return s.includes(".")?s:`${s}.0`}const vr="String",gr=/[\x00-\x1f\x7f]+/,pr="Token";function mr(t){const i=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw nr(i,pr);return i}function yr(t){switch(typeof t){case"number":if(!f(t))throw nr(t,hr);return Number.isInteger(t)?ur(t):fr(t);case"string":return function(t){if(gr.test(t))throw nr(t,vr);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return mr(t);case"boolean":return function(t){if("boolean"!=typeof t)throw nr(t,or);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${ur(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return function(t){if(!1===ArrayBuffer.isView(t))throw nr(t,ar);return`:${i=t,btoa(String.fromCharCode(...i))}:`;var i}(t);if(t instanceof rr)return mr(t);default:throw nr(t,hr)}}const br="Key";function wr(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw nr(t,br);return t}function $r(t){return null==t?"":Object.entries(t).map((([t,i])=>!0===i?`;${wr(t)}`:`;${wr(t)}=${yr(i)}`)).join("")}function kr(t){return t instanceof sr?`${yr(t.value)}${$r(t.params)}`:yr(t)}const Sr=t=>Math.round(t),Tr=t=>100*Sr(t/100),Er={br:Sr,d:Sr,bl:Tr,dl:Tr,mtp:Tr,nor:(t,i)=>((null==i?void 0: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:Tr,tb:Sr};function Ar(t,i={}){return t?function(t,i){return function(t,i={whitespace:!0}){if("object"!=typeof t)throw nr(t,er);const s=t instanceof Map?t.entries():Object.entries(t),e=(null==i?void 0:i.whitespace)?" ":"";return Array.from(s).map((([t,i])=>{i instanceof sr==0&&(i=new sr(i));let s=wr(t);var e;return!0===i.value?s+=$r(i.params):(s+="=",Array.isArray(i.value)?s+=`(${(e=i).value.map(kr).join(" ")})${$r(e.params)}`:s+=kr(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=x({},Er,null==i?void 0:i.formatters),r=null==i?void 0:i.filter;return e.forEach((e=>{if(null==r?void 0:r(e))return;let h=t[e];const o=n[e];o&&(h=o(h,i)),"v"===e&&1===h||"pr"==e&&1===h||function(t){return"number"==typeof t?f(t):null!=t&&""!==t&&!1!==t}(h)&&(function(t){return"ot"===t||"sf"===t||"st"===t}(e)&&"string"==typeof h&&(h=new rr(h)),s[e]=h)})),s}(t,i),x({whitespace:!1},i)):""}const Lr=/CMCD=[^&#]+/;function Mr(t,i,s,e){t&&Object.keys(i).forEach((n=>{const r=t.filter((t=>t.groupId===n)).map((t=>{const r=x({},t);return r.details=void 0,r.attrs=new Zi(r.attrs),r.url=r.attrs.URI=xr(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 xr(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}function Ir(t,i,s){Dr(t,i,s),t.addEventListener(i,s)}function Dr(t,i,s){t.removeEventListener(i,s)}class Pr extends P{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Pr.CDMCleanupPromise?[Pr.CDMCleanupPromise]:[],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=ps(this.config));const i=t.map(gs).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(i)}this.keyFormatPromise.then((n=>{const r=fs(n);let h,o;if("sinf"===i){if(r!==as.FAIRPLAY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${r}`);const n=ut(new Uint8Array(s));try{const t=St(rs(JSON.parse(n).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=new Uint8Array(t.subarray(8,24)),o=as.FAIRPLAY}catch(t){return void this.warn(`${e} Failed to parse sinf: ${t}`)}}else{if(r!==as.WIDEVINE&&r!==as.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=It(new DataView(t,e));i.push(s),e+=s.size}}return i}(s),a=n.filter((t=>!!t.systemId&&vs(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=>vs(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=vs(l.systemId),0===l.version&&l.data)if(o===as.WIDEVINE){const t=l.data.length-22;h=new Uint8Array(l.data.subarray(t,t+16))}else o===as.PLAYREADY&&(h=bs(l.data))}if(!o||!h)return;const a=G(h),{keyIdToKeySessionPromise:l,mediaKeySessions:u}=this;let c=l[a];for(let t=0;t<u.length;t++){const e=u[t],n=e.decryptdata;if(!n.keyId)continue;const r=G(n.keyId);if(a===r||-1!==n.uri.replace(/-/g,"").indexOf(a)){if(c=l[r],n.pssh)break;delete l[r],n.pssh=new Uint8Array(s),n.keyId=h,c=l[a]=c.then((()=>this.generateRequestWithPreferredKeySession(e,i,s,"encrypted-event-key-match"))),c.catch((t=>this.handleError(t)));break}}if(!c){if(o!==r)return void this.log(`Ignoring "${t.type}" event with ${o} init data for selected key-system ${r}`);c=l[a]=this.getKeySystemSelectionPromise([o]).then((({keySystem:t,mediaKeys:e})=>{var n;this.throwIfDestroyed();const r=new $s("ISO-23001-7",a,null!=(n=gs(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")}))})),c.catch((t=>this.handleError(t)))}}))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),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(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(y.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(y.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:i,widevineLicenseUrl:s}=this.config,e=i[t];return e?e.licenseUrl:t===as.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 Cr?i:new Cr({type:p.KEY_SYSTEM_ERROR,details:m.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===ms&&"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 as.FAIRPLAY:n=["cenc","sinf"];break;case as.WIDEVINE:case as.PLAYREADY:n=["cenc"];break;case as.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: ${ri(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((s=>(this.log(`Media-keys created for "${t}"`),i.hasMediaKeys=!0,e.then((i=>i?this.setMediaKeysServerCertificate(s,t,i):s))))),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: ${G(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.buffer,"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 G(t.keyId)}updateKeySession(t,i){var s;const e=t.mediaKeysSession;return this.log(`Updating key-session "${e.sessionId}" for keyID ${G((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${i?i.byteLength:i})`),e.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map((t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys}))).filter((({hasMediaKeys:t})=>!!t)).map((({keySystem:t})=>gs(t))).filter((t=>!!t))}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then((({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i)))}selectKeySystem(t){return new Promise(((i,s)=>this.getKeySystemSelectionPromise(t).then((({keySystem:t})=>{const e=gs(t);e?i(e):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)))}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){const i=ps(this.config),s=t.map(fs).filter((t=>!!t&&-1!==i.indexOf(t)));return this.selectKeySystem(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.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(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:n,decryptdata:i}))))))),(this.keyIdToKeySessionPromise[s]=n.then((t=>this.generateRequestWithPreferredKeySession(t,"cenc",i.pssh?i.pssh.buffer:null,"playlist-key")))).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(y.ERROR,t instanceof Cr?t.data:{type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const i=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[i];if(!s){const i=fs(t.keyFormat),s=i?[i]:ps(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=ps(this.config)),0===t.length)throw new Cr({type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ri({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,i){if(this.mediaKeys===i)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const e=Promise.all(s).then((()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(i)}));return this.mediaKeys=i,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,t.decryptdata.pssh=(s=e.initData?e.initData:null)?new Uint8Array(s):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 oe,u=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=>{l.eventNames().length?l.emit("error",t):this.handleError(t)})):"license-release"===e?t.keySystem===as.FAIRPLAY&&(this.updateKeySession(t,hs("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${e}"`)},c=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))};Ir(t.mediaKeysSession,"message",u),Ir(t.mediaKeysSession,"keystatuseschange",c);const d=new Promise(((t,i)=>{l.on("error",i),l.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?i(new Cr({type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?i(new Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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)=>{if("string"==typeof s&&"object"==typeof i){const t=s;s=i,i=t}this.log(`key status change "${i}" for keyStatuses keyId: ${G("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${G(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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:D({url:h.url,data:void 0},i)},`"${t}" certificate request failed (${e}). Status: ${i.code} (${i.text})`))},onTimeout:(i,s,n)=>{r(new Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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 hs(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 Cr({type:p.KEY_SYSTEM_ERROR,details:m.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==as.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(i,s)),i.send(s)}))}))}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,i){if(!this.config.emeEnabled)return;const s=i.media;this.media=s,Ir(s,"encrypted",this.onMediaEncrypted),Ir(s,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media;t&&(Dr(t,"encrypted",this.onMediaEncrypted),Dr(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,$s.clearKeyUriToKeyIdMap();const e=s.length;Pr.CDMCleanupPromise=Promise.all(s.map((t=>this.removeSession(t))).concat(null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch((t=>{var i;this.log(`Could not clear media keys: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})})))).catch((t=>{var i;this.log(`Could not close sessions and clear media keys: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})})).then((()=>{e&&this.log("finished closing key sessions and clearing media keys")}))}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);e>-1&&this.mediaKeySessions.splice(e,1);const{drmSystemOptions:n}=this.config,r=function(t){var i;return"persistent-license"===t.sessionType||!(null==(i=t.sessionTypes)||!i.some((t=>"persistent-license"===t)))}(n)?new Promise(((t,s)=>{self.setTimeout((()=>s(new Error("MediaKeySession.remove() timeout"))),8e3),i.remove().then(t)})):Promise.resolve();return r.catch((t=>{var i;this.log(`Could not remove session: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})})).then((()=>i.close())).catch((t=>{var i;this.log(`Could not close session: ${t}`),null==(i=this.hls)||i.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})}))}}}Pr.CDMCleanupPromise=void 0;class Cr 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}}function Rr(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 Or(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){F.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){F.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function Nr(t,i){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues)for(let s=t.cues.length;s--;)i&&t.cues[s].removeEventListener("enter",i),t.removeCue(t.cues[s]);"disabled"===s&&(t.mode=s)}function Ur(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,n=0,r=s;for(;n<=r;)if(e=Math.floor((r+n)/2),i<t[e].startTime)r=e-1;else{if(!(i>t[e].startTime&&n<s))return e;n=e+1}return t[n].startTime-i<i-t[r].startTime?n:r}(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 Fr(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}function Br(t){let i=5381,s=t.length;for(;s;)i=33*i^t.charCodeAt(--s);return(i>>>0).toString()}const _r=.025;let jr=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Gr(t,i,s){return`${t.identifier}-${s+1}-${Br(i)}`}class Hr{constructor(t,i){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=i,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var i;if(t>0&&t>=this.assetList.length)return!0;const s=this.playoutLimit;return!(t<=0||isNaN(s))&&(0===s||((null==(i=this.assetList[t])?void 0:i.startOffset)||0)>s)}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const i=this.dateRange.tagAnchor;if(i)return Kr(t,i)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const i=this.dateRange.startTime;return i-Kr(i,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,i=f(t)?t:this.duration;return this.cumulativeDuration+i}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const i=this.resumeAnchor;if(i)return Kr(t,i)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<_r))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let i;return i=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<i&&(i=t),i}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?jr.Range:jr.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Kr(t,i){return t-i.start<i.duration/2&&!(Math.abs(t-(i.start+i.duration))<_r)?i.start:i.start+i.duration}function Vr(t,i,s){const e=new self.URL(t,s);return"data:"!==e.protocol&&e.searchParams.set("_HLS_primary_id",i),e}function Xr(t,i){for(;null!=(s=t.assetList[++i])&&s.error;)var s;return i}function Wr(t){const i=t.timelineStart,s=t.duration||0;return`["${t.identifier}" ${i.toFixed(2)}-${(i+s).toFixed(2)}]`}class zr{constructor(t,i,s,e){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new t(i);this.interstitial=s,this.assetItem=e;let r=e.uri;try{r=Vr(r,i.primarySessionId).href}catch(t){}n.loadSource(r);const h=()=>{this.hasDetails=!0};n.once(y.LEVEL_LOADED,h),n.once(y.AUDIO_TRACK_LOADED,h),n.once(y.SUBTITLE_TRACK_LOADED,h),n.on(y.MEDIA_ATTACHING,((t,{media:i})=>{this.removeMediaListeners(),this.mediaAttached=i,this.interstitial.playoutLimit&&(i.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(y.BUFFER_APPENDED,(()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,n.trigger(y.BUFFERED_TO_END,void 0))})))}))}get appendInPlace(){var t;return(null==(t=this.interstitial)?void 0:t.appendInPlace)||!1}bufferedInPlaceToEnd(t){var i;if(!this.appendInPlace)return!1;if(null!=(i=this.hls)&&i.bufferedToEnd)return!0;if(!t||!this._bufferedEosTime)return!1;const s=Vi.bufferInfo(t,this.timelineOffset,0);return this.getAssetTime(s.end)>=this._bufferedEosTime-.02}reachedPlayout(t){return this.startOffset+t>=this.interstitial.playoutLimit}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const i=Vi.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(i.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){return this.assetItem.duration||0}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const i=this.timelineOffset;if(t!==i&&Math.abs(t-i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}getAssetTime(t){const i=this.duration;return Math.min(Math.max(0,t-this.timelineOffset),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){this.hls.attachMedia(t)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}resetDetails(){const t=this.hls;if(this.hasDetails){t.stopLoad();const i=t=>delete t.details;t.levels.forEach(i),t.allAudioTracks.forEach(i),t.allSubtitleTracks.forEach(i),this.hasDetails=!1}}on(t,i,s){this.hls.on(t,i)}once(t,i,s){this.hls.once(t,i)}off(t,i,s){this.hls.off(t,i)}toString(){var t;return`HlsAssetPlayer: ${Wr(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class qr extends P{constructor(t,i){super("interstitials-sched",i),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((t=>t.reset())),this.events=this.items=null}resetErrorsInRange(t,i){return this.events?this.events.reduce(((s,e)=>t<=e.startOffset&&i>e.startOffset?(delete e.error,s+1):s),0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,i){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const e=this.items;if(e)for(e[s]||(void 0===i&&(i=t.start),s=this.findItemIndexAtTime(i));s>=0&&null!=(n=e[s])&&n.event;){var n;s--}return s}findItemIndexAtTime(t,i){const s=this.items;if(s)for(let e=0;e<s.length;e++){let n=s[e];if(i&&"primary"!==i&&(n=n[i]),t===n.start||t>n.start&&t<n.end)return e}return-1}findJumpRestrictedIndex(t,i){const s=this.items;if(s)for(let e=t;e<=i&&s[e];e++){const t=s[e].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return e}return-1}findEventIndex(t){const i=this.items;if(i)for(let e=i.length;e--;){var s;if((null==(s=i[e].event)?void 0:s.identifier)===t)return e}return-1}findAssetIndex(t,i){const s=t.assetList,e=s.length;if(e>1)for(let t=0;t<e;t++){const e=s[t];if(!e.error){const s=e.timelineStart;if(i===s||i>s&&i<s+(e.duration||0))return t}}return 0}get assetIdAtEnd(){var t,i;const s=null==(t=this.items)||null==(i=t[this.length-1])?void 0:i.event;if(s){const t=s.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,i){const s=t.main.details,{dateRanges:e}=s,n=this.events,r=this.parseDateRanges(e,{url:s.url},i),h=Object.keys(e),o=n?n.filter((t=>!h.includes(t.identifier))):[];r.length&&r.sort(((t,i)=>{const s=t.cue.pre,e=t.cue.post,n=i.cue.pre,r=i.cue.post;if(s&&!n)return-1;if(n&&!s)return 1;if(e&&!r)return 1;if(r&&!e)return-1;if(!(s||n||e||r)){const s=t.startTime,e=i.startTime;if(s!==e)return s-e}return t.dateRange.tagOrder-i.dateRange.tagOrder})),this.events=r,o.forEach((t=>{this.removeEvent(t)})),this.updateSchedule(t,o)}updateSchedule(t,i=[]){const s=this.events||[];if(s.length||i.length||this.length<2){const e=this.items,n=this.parseSchedule(s,t);(i.length||(null==e?void 0:e.length)!==n.length||n.some(((t,i)=>Math.abs(t.playout.start-e[i].playout.start)>.005||Math.abs(t.playout.end-e[i].playout.end)>.005)))&&(this.items=n,this.onScheduleUpdate(i,e))}}parseDateRanges(t,i,s){const e=[],n=Object.keys(t);for(let r=0;r<n.length;r++){const h=n[r],o=t[h];if(o.isInterstitial){let t=this.eventMap[h];t?t.setDateRange(o):(t=new Hr(o,i),this.eventMap[h]=t,!1===s&&(t.appendInPlace=s)),e.push(t)}}return e}parseSchedule(t,i){const s=[],e=i.main.details,n=e.live?1/0:e.edge;let r=0;if((t=t.filter((t=>!(t.error||t.cue.once&&t.hasPlayed)))).length){this.resolveOffsets(t,i);let e=0,o=0;if(t.forEach(((i,h)=>{const a=i.cue.post,l=t[h-1]||null,u=a?n:i.startOffset,c=i.duration,d=i.timelineOccupancy===jr.Range?c:0,f=(null==l?void 0:l.startTime)===u,v=u+i.cumulativeDuration;let g=i.appendInPlace?v+c:u+i.resumptionOffset;if(i.cue.pre||!a&&u<=0){const t=o;o+=d,i.timelineStart=v;const e=r;r+=c,s.push({event:i,start:v,end:g,playout:{start:e,end:r},integrated:{start:t,end:o}})}else{if(!(u<=n))return;{if(!f){const n=u-e;if(n>.033){const a=o;o+=n;const l=r;r+=n,s.push({previousEvent:t[h-1]||null,nextEvent:i,start:e,end:e+n,playout:{start:l,end:r},integrated:{start:a,end:o}})}else n>0&&l&&(l.cumulativeDuration+=n,s[s.length-1].end=u)}a&&(g=v),i.timelineStart=v;const n=o;o+=d;const p=r;r+=c,s.push({event:i,start:v,end:g,playout:{start:p,end:r},integrated:{start:n,end:o}})}}const p=i.resumeTime;e=a||p>n?n:p})),e<n){var h;const t=o,i=n-e;o+=i;const a=r;r+=i,s.push({previousEvent:(null==(h=s[s.length-1])?void 0:h.event)||null,nextEvent:null,start:e,end:e+i,playout:{start:a,end:r},integrated:{start:t,end:o}})}this.setDurations(n,r,o)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:n,playout:{start:t,end:n},integrated:{start:t,end:n}}),this.setDurations(n,n,n)}return s}setDurations(t,i,s){this.durations={primary:t,playout:i,integrated:s}}resolveOffsets(t,i){const s=i.main.details,e=s.live?1/0:s.edge;let n=0,r=-1;t.forEach(((h,o)=>{const a=h.cue.post,l=h.cue.pre?0:a?e:h.startTime;this.updateAssetDurations(h),r===l?h.cumulativeDuration=n:(n=0,r=l),!a&&h.snapOptions.in&&(h.resumeAnchor=gi(null,s.fragments,h.startOffset+h.resumptionOffset,0,0)||void 0),h.appendInPlace&&!h.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(h,i)||(h.appendInPlace=!1)),!h.appendInPlace&&o+1<t.length&&t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${h}`));const u=f(h.resumeOffset)?h.resumeOffset:h.duration;n+=u}))}primaryCanResumeInPlaceAt(t,i){const s=t.resumeTime,e=t.startTime+t.resumptionOffset;return Math.abs(s-e)>_r?(this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${e}`),!1):i?!Object.keys(i).some((e=>{const n=i[e].details,r=n.edge;if(s>=r)return this.log(`"${t.identifier}" resumption ${s} past ${e} playlist end ${r}`),!1;const h=gi(null,n.fragments,s);if(!h)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${e} playlist (${n.fragStart}-${n.fragmentEnd})`),!0;const o="audio"===e?.175:0;return!(Math.abs(h.start-s)<_r+o||Math.abs(h.end-s)<_r+o||(this.log(`"${t.identifier}" resumption ${s} not aligned with ${e} fragment bounds (${h.start}-${h.end} sn: ${h.sn} cc: ${h.cc})`),0))})):(this.log(`"${t.identifier}" resumption ${s} can not be aligned with media (none selected)`),!1)}updateAssetDurations(t){if(!t.assetListLoaded)return;const i=t.timelineStart;let s=0,e=!1,n=!1;t.assetList.forEach((t=>{const r=i+s;t.startOffset=s,t.timelineStart=r,e||(e=null===t.duration),n||(n=!!t.error),s+=t.error?0:t.duration||0})),t.duration=e&&!n?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function Yr(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Qr{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,i){const s=t.assetListUrl;let e;try{e=Vr(s,this.hls.sessionId,t.baseUrl)}catch(i){const e=this.assignAssetListError(t,m.ASSET_LIST_LOAD_ERROR,i,s);return void this.hls.trigger(y.ERROR,e)}i&&"data:"!==e.protocol&&e.searchParams.set("_HLS_start_offset",""+i);const n=this.hls.config,r=new(0,n.loader)(n),h=n.interstitialAssetListLoadPolicy.default;return r.load({responseType:"json",url:e.href},{loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},{onSuccess:(i,s,e,n)=>{const r=i.data;if(Array.isArray(null==r?void 0:r.ASSETS))t.assetListResponse=r,this.hls.trigger(y.ASSET_LIST_LOADED,{event:t,assetListResponse:r,networkDetails:n});else{const i=this.assignAssetListError(t,m.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),e.url,s,n);this.hls.trigger(y.ERROR,i)}},onError:(i,s,e,n)=>{const r=this.assignAssetListError(t,m.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${i.code} ${i.text} (${s.url})`),s.url,n,e);this.hls.trigger(y.ERROR,r)},onTimeout:(i,s,e)=>{const n=this.assignAssetListError(t,m.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,i,e);this.hls.trigger(y.ERROR,n)}}),this.hls.trigger(y.ASSET_LIST_LOADING,{event:t}),r}assignAssetListError(t,i,s,e,n,r){return t.error=s,{type:p.NETWORK_ERROR,details:i,fatal:!1,interstitial:t,url:e,error:s,networkDetails:r,stats:n}}}function Jr(t){null==t||t.play().catch((()=>{}))}class Zr{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)}}}const th={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},ih=t=>String.fromCharCode(th[t]||t),sh=15,eh=100,nh={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rh={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hh={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},oh={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ah=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class lh{constructor(){this.time=null,this.verboseLevel=0}log(t,i){if(this.verboseLevel>=t){const s="function"==typeof i?i():i;F.log(`${this.time} [${t}] ${s}`)}}}const uh=function(t){const i=[];for(let s=0;s<t.length;s++)i.push(t[s].toString(16));return i};class ch{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 dh{constructor(){this.uchar=" ",this.penState=new ch}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 fh{constructor(t){this.chars=[],this.pos=0,this.currPenState=new ch,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<eh;t++)this.chars.push(new dh);this.logger=t}equals(t){for(let i=0;i<eh;i++)if(!this.chars[i].equals(t.chars[i]))return!1;return!0}copy(t){for(let i=0;i<eh;i++)this.chars[i].copy(t.chars[i])}isEmpty(){let t=!0;for(let i=0;i<eh;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>eh&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=eh)}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=ih(t);this.pos>=eh?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<eh;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<eh;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 vh{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let i=0;i<sh;i++)this.rows.push(new fh(t));this.logger=t}reset(){for(let t=0;t<sh;t++)this.rows[t].clear();this.currRow=14}equals(t){let i=!0;for(let s=0;s<sh;s++)if(!this.rows[s].equals(t.rows[s])){i=!1;break}return i}copy(t){for(let i=0;i<sh;i++)this.rows[i].copy(t.rows[i])}isEmpty(){let t=!0;for(let i=0;i<sh;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 = "+ri(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<sh;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 = "+ri(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<sh;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 gh{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 vh(s),this.nonDisplayedMemory=new vh(s),this.lastOutputScreen=new vh(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: "+ri(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 ph{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 lh;this.channels=[null,new gh(t,i,e),new gh(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,(()=>"["+uh([i[t],i[t+1]])+"] -> ("+uh([s,e])+")"));const h=this.cmdHistory;if(s>=16&&s<=31){if(yh(s,e,h)){mh(null,null,h),this.logger.log(3,(()=>"Repeated command ("+uh([s,e])+") is dropped"));continue}mh(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 mh(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 "+uh([s,e])+" orig: "+uh([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 ("+uh([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?nh[t]:hh[t]:1===e?rh[t]:oh[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 '"+ih(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 = "+uh(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=ah[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()}mh(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 mh(t,i,s){s.a=t,s.b=i}function yh(t,i,s){return s.a===t&&s.b===i}var bh=function(){if(null!=os&&os.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="",u=!1,c=i,d=r,f=h,v=null,g="",p=!0,m="auto",y="start",b=50,w="middle",$=50,k="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 u},set:function(t){u=!!t}})),Object.defineProperty(o,"startTime",n({},a,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=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 g},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.");g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},a,{get:function(){return p},set:function(t){p=!!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 b},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");b=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},a,{get:function(){return w},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");w=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},a,{get:function(){return $},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");$=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},a,{get:function(){return k},set:function(t){const i=e(t);if(!i)throw new SyntaxError("An invalid or illegal string was specified.");k=i,this.hasBeenReset=!0}})),o.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class wh{decode(t,i){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function $h(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 kh{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 Sh(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 Th=new bh(0,0,""),Eh="middle"===Th.align?"middle":"center";function Ah(t,i,s){const e=t;function n(){const i=$h(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 kh;Sh(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",Eh,"end"]);break;case"position":n=i.split(","),e.percent(t,n[0]),2===n.length&&e.alt("positionAlign",n[1],["start",Eh,"end","line-left","line-right","auto"]);break;case"size":e.percent(t,i);break;case"align":e.alt(t,i,["start",Eh,"end","left","right"])}}),/:/,/\s/),i.region=e.get("region",null),i.vertical=e.get("vertical","");let n=e.get("line","auto");"auto"===n&&-1===Th.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",Eh);let r=e.get("position","auto");"auto"===r&&50===Th.position&&(r="start"===i.align||"left"===i.align?0:"end"===i.align||"right"===i.align?100:50),i.position=r}(t,i)}function Lh(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class Mh{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new wh,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=Lh(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)?Sh(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 bh(0,0,""),i.state="CUE",-1===t.indexOf("--\x3e")){i.cue.id=t;continue}case"CUE":if(!i.cue){i.state="BADCUE";continue}try{Ah(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 xh=/\r\n|\n\r|\n|\r/g,Ih=function(t,i,s=0){return t.slice(s,s+i.length)===i};function Dh(t,i,s){return Br(t.toString())+Br(i.toString())+Br(s)}const Ph="stpp.ttml.im1t",Ch=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rh=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oh={left:"start",center:"center",right:"end",start:"start",end:"end"};function Nh(t,i,s,e){const n=gt(new Uint8Array(t),["mdat"]);if(0===n.length)return void e(new Error("Could not parse IMSC1 mdat"));const r=n.map((t=>j(t))),h=function(t,i,s=1,e=!1){return fn(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=Fh(Uh(s,"styling","style")),o=Fh(Uh(s,"layout","region")),a=Uh(s,"body","[begin]");return[].map.call(a,(t=>{const s=Bh(t,r);if(!s||!t.hasAttribute("begin"))return null;const e=Gh(t.getAttribute("begin"),n),a=Gh(t.getAttribute("dur"),n);let l=Gh(t.getAttribute("end"),n);if(null===e)throw jh(t);if(null===l){if(null===a)throw jh(t);l=e+a}const u=new bh(e-i,l-i,s);u.id=Dh(u.startTime,u.endTime,u.text);const c=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=_h(i,e,r)||_h(t,e,r)||_h(n,e,r);return h&&(s[r]=h),s}),{})}(o[t.getAttribute("region")],h[t.getAttribute("style")],h),{textAlign:d}=c;if(d){const t=Oh[d];t&&(u.lineAlign=t),u.align=d}return x(u,c),u})).filter((t=>null!==t))}(t,h))))}catch(t){e(t)}}function Uh(t,i,s){const e=t.getElementsByTagName(i)[0];return e?[].slice.call(e.querySelectorAll(s)):[]}function Fh(t){return t.reduce(((t,i)=>{const s=i.getAttribute("xml:id");return s&&(t[s]=i),t}),{})}function Bh(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?Bh(s,i):i?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function _h(t,i,s){return t&&t.hasAttributeNS(i,s)?t.getAttributeNS(i,s):null}function jh(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Gh(t,i){if(!t)return null;let s=$h(t);return null===s&&(Ch.test(t)?s=function(t,i){const s=Ch.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):Rh.test(t)&&(s=function(t,i){const s=Rh.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}class Hh{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}}function Kh(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Vh(t,i){return!!t&&t.kind===Kh(i)&&Nn(i,t)}const Xh=/\s/,Wh={newCue(t,i,s,e){const n=[];let r,h,o,a,l;const u=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 c;for(let t=0;t<r.chars.length;t++)Xh.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=Lh(l.trim()),f=Dh(i,s,e);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(h=new u(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=>Or(t,i)))),n}},zh=/(\d+)-(\d+)\/(\d+)/;class qh{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||Yh,this.controller=new self.AbortController,this.stats=new J}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(x({},t.headers))};return t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),s}(t,this.controller.signal),r="arraybuffer"===t.responseType,h=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:a}=i.loadPolicy;this.context=t,this.config=i,this.callbacks=s,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),i.timeout=o&&f(o)?o:a,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(e,t,this.response))}),i.timeout),(Mn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var n;this.response=this.loader=s;const h=Math.max(self.performance.now(),e.loading.start);if(self.clearTimeout(this.requestTimeout),i.timeout=a,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(e,t,this.response))}),a-(h-e.loading.start)),!s.ok){const{status:t,statusText:i}=s;throw new Qh(i||"fetch, bad network response",t,s)}e.loading.first=h,e.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const i=zh.exec(t);if(i)return parseInt(i[2])-parseInt(i[1])+1}(i);if(f(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(s.headers)||e.total;const o=null==(n=this.callbacks)?void 0:n.onProgress;return o&&f(i.highWaterMark)?this.loadProgressively(s,e,t,i.highWaterMark,o):r?s.arrayBuffer():"json"===t.responseType?s.json():s.text()})).then((s=>{var n,r;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),e.loading.end=Math.max(self.performance.now(),e.loading.first);const a=s[h];a&&(e.loaded=e.total=a);const l={url:o.url,data:s,code:o.status},u=null==(n=this.callbacks)?void 0:n.onProgress;u&&!f(i.highWaterMark)&&u(e,t,s,o),null==(r=this.callbacks)||r.onSuccess(l,e,t,o)})).catch((i=>{var s;self.clearTimeout(this.requestTimeout),e.aborted||null==(s=this.callbacks)||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 ee,h=t.body.getReader(),o=()=>h.read().then((h=>{if(h.done)return r.dataLength&&n(i,s,r.flush().buffer,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().buffer,t)):n(i,s,a.buffer,t),o()})).catch((()=>Promise.reject()));return o()}}function Yh(t,i){return new self.Request(t.url,i)}class Qh extends Error{constructor(t,i,s){super(t),this.code=void 0,this.details=void 0,this.code=i,this.details=s}}const Jh=/^age:\s*[\d.]+\s*$/im;class Zh{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 J,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=>{var n;null==(n=this.callbacks)||n.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&&f(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,a="text"===i.responseType?i.responseText:null;if(e>=200&&e<300){const n=null!=a?a:i.response;if(null!=n){var r,h;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);const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&o(s,t,n,i),void(null==(h=this.callbacks)||h.onSuccess({url:i.responseURL,data:n,code:e},s,t,i))}}const l=n.loadPolicy.errorRetry;var o;Si(l,s.retry,!1,{url:t.url,data:void 0,code:e})?this.retry(l):(F.error(`${e} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:e,text:i.statusText},t,i,s))}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Si(t,this.stats.retry,!0))this.retry(t);else{var i;F.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=$i(t,s.retry),s.retry++,F.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&&Jh.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 to=D(D({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:Zh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends P{constructor(t){super("abr",t.logger),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.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:e,hls:n}=this,{autoLevelEnabled:r,media:h}=n;if(!s||!h)return;const o=performance.now(),a=e?e.stats:s.stats,l=e?e.duration:s.duration,u=o-a.loading.start,c=n.minAutoLevel,d=s.level,v=this._nextAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||d<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r)return;const g=v>-1&&v!==d,p=!!t||g;if(!p&&(h.paused||!h.playbackRate||!h.readyState))return;const m=n.mainForwardBufferInfo;if(!p&&null===m)return;const b=this.bwEstimator.getEstimateTTFB(),w=Math.abs(h.playbackRate);if(u<=Math.max(b,l/(2*w)*1e3))return;const $=m?m.len/w:0,k=a.loading.first?a.loading.first-a.loading.start:-1,S=a.loaded&&k>-1,T=this.getBwEstimate(),E=n.levels,A=Math.max(a.loaded,Math.round(l*(s.bitrate||E[d].averageBitrate)/8));let L=S?u-k:u;L<1&&S&&(L=Math.min(u,8*a.loaded/T));const M=S?1e3*a.loaded/L:0,x=b/1e3,I=M?(A-a.loaded)/M:8*A/T+x;if(I<=$)return;const D=M?8*M:T,P=!0===(null==(i=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:i.live),C=this.hls.config.abrBandWidthUpFactor;let R,O=Number.POSITIVE_INFINITY;for(R=d-1;R>c&&(O=this.getTimeToLoadFrag(x,D,l*E[R].maxBitrate,!E[R].details||P),!(O<Math.min($,l+x)));R--);if(O>=I)return;if(O>10*l)return;S?this.bwEstimator.sample(u-Math.min(b,k),a.loaded):this.bwEstimator.sampleTTFB(u);const N=E[R].maxBitrate;this.getBwEstimate()*C>N&&this.resetEstimator(N);const U=this.findBestLevel(N,c,R,0,$,1,1);U>-1&&(R=U),this.warn(`Fragment ${s.sn}${e?" part "+e.index:""} of level ${d} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${$.toFixed(3)} s\n Estimated load time for current fragment: ${I.toFixed(3)} s\n Estimated load time for down switch fragment: ${O.toFixed(3)} s\n TTFB estimate: ${0|k} ms\n Current BW estimate: ${f(T)?0|T:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${R} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=R,this.clearTimer();const F=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===R&&R>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${R>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,R>c){let i=this.findBestLevel(this.hls.levels[c].bitrate,c,R,0,t,1,1);-1===i&&(i=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=i,this.resetEstimator(this.hls.levels[i].bitrate)}}};g||I>2*O?F():this.timer=self.setInterval(F,1e3*O),n.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.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 L(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.FRAG_LOADING,this.onFragLoading,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.FRAG_LOADING,this.onFragLoading,this),t.off(y.FRAG_LOADED,this.onFragLoaded,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,i){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},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 m.BUFFER_ADD_CODEC_ERROR:case m.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case m.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?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:e}=i.stats,n=e.end-e.first;f(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(i.levelInfo)}onFragLoaded(t,{frag:i,part:s}){const e=s?s.stats:i.stats;if(i.type===S&&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(y.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!==S||"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 this.warn(`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;if(s.levels.length<=1)return s.loadLevel;const{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,u=n.abrBandWidthUpFactor;if(a){const t=this.findBestLevel(o,r,e,a,0,l,u);if(t>=0)return this.rebufferNotice=-1,t}let c=h?Math.min(h,n.maxStarvationDelay):n.maxStarvationDelay;if(!a){const t=this.bitrateTestDelay;t&&(c=(h?Math.min(h,n.maxLoadingDelay):n.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),l=u=1)}const d=this.findBestLevel(o,r,e,a,c,l,u);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${a?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=s.levels[r],v=s.loadLevelObj;return v&&(null==f?void 0:f.bitrate)<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,u=-1===l?this.hls.firstLevel:l,{fragCurrent:c,partCurrent:d}=this,{levels:v,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===v.length)return 0;const y=v[u],b=!(null==(o=this.hls.latestLevelDetails)||!o.live),w=-1===p||-1===l;let $,k="SDR",S=(null==y?void 0:y.frameRate)||0;const{audioPreference:T,videoPreference:E}=m,A=this.audioTracksByGroup||(this.audioTracksByGroup=oi(g));let L=-1;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,e)=>{if(!s.codecSet)return t;const n=s.audioGroups;let r=t[s.codecSet];r||(t[s.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:e,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,s.bitrate);const h=Math.min(s.height,s.width);return r.minHeight=Math.min(r.minHeight,h),r.minFramerate=Math.min(r.minFramerate,s.frameRate),r.minIndex=Math.min(r.minIndex,e),r.maxScore=Math.max(r.maxScore,s.score),r.fragmentError+=s.fragmentError,r.videoRanges[s.videoRange]=(r.videoRanges[s.videoRange]||0)+1,n&&n.forEach((t=>{if(!t)return;const s=i.groups[t];s&&(r.hasDefaultAudio=r.hasDefaultAudio||i.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!i.hasDefaultAudio&&!i.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{r.channels[t]=(r.channels[t]||0)+s.channels[t]})))})),t}),{})}(v,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=null==n?void 0:n.videoCodec,l=h&&2===parseInt(h);let u=!1,c=!1,d=1/0,v=1/0,g=1/0,p=1/0,m=0,y=[];const{preferHDR:b,allowedVideoRanges:w}=function(t,i){let s=!1,e=[];if(t&&(s="SDR"!==t,e=[t]),i){e=i.allowedVideoRanges||ti.slice(0);const t="SDR"!==e.join("")&&!i.videoCodec;s=void 0!==i.preferHDR?i.preferHDR:t&&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}(),s||(e=["SDR"])}return{preferHDR:s,allowedVideoRanges:e}}(i,n);for(let i=r.length;i--;){const s=t[r[i]];u||(u=s.channels[2]>0),d=Math.min(d,s.minHeight),v=Math.min(v,s.minFramerate),g=Math.min(g,s.minBitrate),w.filter((t=>s.videoRanges[t]>0)).length>0&&(c=!0)}d=f(d)?d:0,v=f(v)?v:0;const $=Math.max(1080,d),k=Math.max(30,v);g=f(g)?g:s,s=Math.max(g,s),c||(i=void 0);const S=r.length>1;return{codecSet:r.reduce(((i,e)=>{const n=t[e];if(e===i)return i;if(y=c?w.filter((t=>n.videoRanges[t]>0)):[],S){if(n.minBitrate>s)return hi(e,`min bitrate of ${n.minBitrate} > current estimate of ${s}`),i;if(!n.hasDefaultAudio)return hi(e,"no renditions with default or auto-select sound found"),i;if(o&&e.indexOf(o.substring(0,4))%5!=0)return hi(e,`audio codec preference "${o}" not found`),i;if(h&&!l){if(!n.channels[h])return hi(e,`no renditions with ${h} channel sound found (channels options: ${Object.keys(n.channels)})`),i}else if((!o||l)&&u&&0===n.channels[2])return hi(e,"no renditions with stereo sound found"),i;if(n.minHeight>$)return hi(e,`min resolution of ${n.minHeight} > maximum of ${$}`),i;if(n.minFramerate>k)return hi(e,`min framerate of ${n.minFramerate} > maximum of ${k}`),i;if(!y.some((t=>n.videoRanges[t]>0)))return hi(e,`no variants with VIDEO-RANGE of ${ri(y)} found`),i;if(a&&e.indexOf(a.substring(0,4))%5!=0)return hi(e,`video codec preference "${a}" not found`),i;if(n.maxScore<m)return hi(e,`max score of ${n.maxScore} < selected max of ${m}`),i}return i&&(Ft(e)>=Ft(i)||n.fragmentError>t[i].fragmentError)?i:(p=n.minIndex,m=n.maxScore,e)}),void 0),videoRanges:y,preferHDR:b,minFramerate:v,minBitrate:g,minIndex:p}}(e,k,t,T,E),{codecSet:r,videoRanges:h,minFramerate:o,minBitrate:a,minIndex:l,preferHDR:u}=n;L=l,$=r,k=u?h[h.length-1]:h[0],S=o,t=Math.max(t,a),this.log(`picked start tier ${ri(n)}`)}else $=null==y?void 0:y.codecSet,k=null==y?void 0:y.videoRange;const M=d?d.duration:c?c.duration:0,x=this.bwEstimator.getEstimateTTFB()/1e3,I=[];for(let o=s;o>=i;o--){var D,P;const i=v[o],c=o>u;if(!i)continue;if(m.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&qt(i,A,k,S,t,T)?(i.supportedPromise=Yt(i,A,s,this.supportedCache),i.supportedPromise.then((t=>{if(!this.hls)return;i.supportedResult=t;const s=this.hls.levels,e=s.indexOf(i);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${e} ${ri(t)}`):t.supported?t.decodingInfoResults.some((t=>!1===t.smooth||!1===t.powerEfficient))&&this.log(`MediaCapabilities decodingInfo for level ${e} not smooth or powerEfficient: ${ri(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${e} ${ri(t)}`),e>-1&&s.length>1&&(this.log(`Removing unsupported level ${e}`),this.hls.removeLevel(e),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):i.supportedResult=Wt}if(($&&i.codecSet!==$||k&&i.videoRange!==k||c&&S>i.frameRate||!c&&S>0&&S<i.frameRate||null!=(D=i.supportedResult)&&null!=(P=D.decodingInfoResults)&&P.some((t=>!1===t.smooth)))&&(!w||o!==L)){I.push(o);continue}const g=i.details,y=(d?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||M;let E;E=c?h*t:r*t;const C=M&&e>=2*M&&0===n?i.averageBitrate:i.maxBitrate,R=this.getTimeToLoadFrag(x,E,C*y,void 0===g);if(E>=C&&(o===l||0===i.loadError&&0===i.fragmentError)&&(R<=x||!f(R)||b&&!this.bitrateTestDelay||R<a)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(I.length&&this.trace(`Skipped level(s) ${I.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${v[I[0]].codecs}" ${v[I[0]].videoRange}; not compatible with "${$}" ${k}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(E)})-bitrate=${Math.round(E-C)} ttfb:${x.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${a.toFixed(1)} fetchDuration:${R.toFixed(1)} firstSelection:${w} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${p}`)),w&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const i=this.deriveNextAutoLevel(t);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}deriveNextAutoLevel(t){const{maxAutoLevel:i,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),i)}},bufferController:class extends P{constructor(t,i){var s;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=()=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=()=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:i,mediaSource:s}=this;t&&this.log("Media source opened"),i&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:i,mediaSource:s}),null!==this.mediaSource&&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&&this.error(`Media element src was set while attaching MediaSource (${i} > ${t})`)},this.hls=t,this.fragmentTracker=i,this.appendSource=(s=B(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.BUFFER_RESET,this.onBufferReset,this),t.on(y.BUFFER_APPENDING,this.onBufferAppending,this),t.on(y.BUFFER_CODECS,this.onBufferCodecs,this),t.on(y.BUFFER_EOS,this.onBufferEos,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.FRAG_PARSED,this.onFragParsed,this),t.on(y.FRAG_CHANGED,this.onFragChanged,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.BUFFER_RESET,this.onBufferReset,this),t.off(y.BUFFER_APPENDING,this.onBufferAppending,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.BUFFER_EOS,this.onBufferEos,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.FRAG_PARSED,this.onFragParsed,this),t.off(y.FRAG_CHANGED,this.onFragChanged,this),t.off(y.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:i}=this;if(!t)return null;const s={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const i=this.isQueued();(t||i)&&this.warn(`Transfering MediaSource with${i?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const e=this.transferData;return!this.sourceBufferCount&&e&&e.mediaSource===i?x(s,e.tracks):this.sourceBuffers.forEach((t=>{const[i]=t;i&&(s[i]=x({},this.tracks[i]),this.removeBuffer(i)),t[0]=t[1]=null})),{media:t,mediaSource:i,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,i){var s;let e=2;(i.audio&&!i.video||!i.altAudio)&&(e=1),this.bufferCodecEventsTotal=e,this.log(`${e} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&e&&this.bufferCreated()}onMediaAttaching(t,i){const s=this.media=i.media,e=B(this.appendSource);if(this.transferData=this.overrides=void 0,s&&e){const t=!!i.mediaSource;(t||i.overrides)&&(this.transferData=i,this.overrides=i.overrides);const n=this.mediaSource=i.mediaSource||new e;if(this.assignMediaSource(n),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const i=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||i&&n instanceof i,jn(s),function(t,i){const s=self.document.createElement("source");s.type="video/mp4",s.src=i,t.appendChild(s)}(s,t),s.load()}catch(i){s.src=t}else s.src=t}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var i,s;this.log(`${(null==(i=this.transferData)?void 0:i.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.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))}attachTransferred(){const t=this.media,i=this.transferData;if(!i||!t)return;const s=this.tracks,e=i.tracks,n=e?Object.keys(e):null,r=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(e&&n&&n&&n.length){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${ri(s,((t,i)=>"initSegment"===t?void 0:i))};\ntransfer tracks: ${ri(e,((t,i)=>"initSegment"===t?void 0:i))}}`),!_(e,s)){i.mediaSource=null,i.tracks=void 0;const n=t.currentTime,r=this.details,h=Math.max(n,(null==r?void 0:r.fragments[0].start)||0);return h-n>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${n} -> ${h}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(e)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${n}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,i),void(t.currentTime=h))}this.transferData=void 0,n.forEach((t=>{const i=t,s=e[i];if(s){const t=s.buffer;if(t){const e=this.fragmentTracker,n=s.id;if(e.hasFragments(n)||e.hasParts(n)){const s=Vi.getBuffered(t);e.detectEvictedFragments(i,s,n,null,!0)}const r=Gn(i);this.sourceBuffers[r]=[i,t],t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(i),this.trackSourceBuffer(i,s)}}})),r(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),r()}get mediaSourceOpenOrEnded(){var t;const i=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===i||"ended"===i}onMediaDetaching(t,i){const s=!!i.transferMedia;this.transferData=this.overrides=void 0;const{media:e,mediaSource:n,_objectUrl:r}=this;if(n){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach((([t])=>{t&&this.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===n.readyState;try{const i=n.sourceBuffers;for(let s=i.length;s--;)t&&i[s].abort(),n.removeSourceBuffer(i[s]);t&&n.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}e&&(e.removeEventListener("emptied",this._onMediaEmptied),s||(r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(e.removeAttribute("src"),this.appendSource&&jn(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(y.MEDIA_DETACHED,i)}onBufferReset(){this.sourceBuffers.forEach((([t])=>{t&&this.resetBuffer(t)})),this.initTracks()}resetBuffer(t){var i;const s=null==(i=this.tracks[t])?void 0:i.buffer;if(this.removeBuffer(t),s)try{var e;null!=(e=this.mediaSource)&&e.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Gn(t)]=[null,null];const i=this.tracks[t];i&&(i.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Un(this.tracks)}onBufferCodecs(t,i){const s=this.tracks,e=Object.keys(i);this.log(`BUFFER_CODECS: "${e}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in i&&(s.audio||s.video)||s.audiovideo&&("audio"in i||"video"in i),r=!n&&this.sourceBufferCount&&this.media&&e.some((t=>!s[t]));n||r?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${e}" SourceBuffers`):(e.forEach((t=>{var e,n,r;const h=i[t],{id:o,codec:a,levelCodec:l,container:u,metadata:c,supplemental:d}=h;let f=s[t];const v=null==(e=this.transferData)||null==(n=e.tracks)?void 0:n[t],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;f||(f=s[t]={buffer:void 0,listeners:[],codec:a,supplemental:d,container:u,levelCodec:l,metadata:c,id:o});const y=Gt(p,m),b=null==y?void 0:y.replace(Fn,"$1");let w=Gt(a,l);const $=null==(r=w)?void 0:r.replace(Fn,"$1");w&&y&&b!==$&&("audio"===t.slice(0,5)&&(w=jt(w,this.appendSource)),this.log(`switching codec ${p} to ${w}`),w!==(f.pendingCodec||f.codec)&&(f.pendingCodec=w),f.container=u,this.appendChangeType(t,u,w))})),(this.tracksReady||this.sourceBufferCount)&&(i.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((t,i)=>{const s=this.tracks[i];return t[i]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t}),{})}appendChangeType(t,i,s){const e=`${i};codecs=${s}`;this.append({label:`change-type=${e}`,execute:()=>{const n=this.tracks[t];if(n){const r=n.buffer;null!=r&&r.changeType&&(this.log(`changing ${t} sourceBuffer type to ${e}`),r.changeType(e),n.codec=s,n.container=i)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:i=>{this.warn(`Failed to change ${t} SourceBuffer type`,i)}},t,this.isPending(this.tracks[t]))}blockAudio(t){var i;const s=t.start,e=s+.05*t.duration;if(!0===(null==(i=this.fragmentTracker.getAppendedFrag(s,S))?void 0:i.gap))return;const n={label:"block-audio",execute:()=>{var t;const i=this.tracks.video;(this.lastVideoAppendEnd>e||null!=i&&i.buffer&&Vi.isBuffered(i.buffer,e)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(e,S))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:n,frag:t},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:i}=this;t&&i&&(this.blockedAudioAppend=null,i.unblockAudio(t.op))}onBufferAppending(t,i){const{tracks:s}=this,{data:e,type:n,parent:r,frag:h,part:o,chunkMeta:a,offset:l}=i,u=a.buffering[n],{sn:c,cc:d}=h,v=self.performance.now();u.start=v;const g=h.stats.buffering,b=o?o.stats.buffering:null;0===g.start&&(g.start=v),b&&0===b.start&&(b.start=v);const w=s.audio;let $=!1;"audio"===n&&"audio/mpeg"===(null==w?void 0:w.container)&&($=!this.lastMpegAudioChunk||1===a.id||this.lastMpegAudioChunk.sn!==a.sn,this.lastMpegAudioChunk=a);const k=s.video,S=null==k?void 0:k.buffer;if(S&&"initSegment"!==c){const t=o||h,i=this.blockedAudioAppend;if("audio"!==n||"main"===r||this.blockedAudioAppend){if("video"===n){const s=t.end;if(i){const t=i.frag.start;(s>t||s<this.lastVideoAppendEnd||Vi.isBuffered(S,t))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const i=t.start+.05*t.duration,s=S.buffered,e=this.currentOp("video");s.length||e?!e&&!Vi.isBuffered(S,i)&&this.lastVideoAppendEnd<i&&this.blockAudio(t):this.blockAudio(t)}}const T=(o||h).start,E={label:`append-${n}`,execute:()=>{var t;u.executeStart=self.performance.now();const i=null==(t=this.tracks[n])?void 0:t.buffer;i&&($?this.updateTimestampOffset(i,T,.1,n,c,d):void 0!==l&&f(l)&&this.updateTimestampOffset(i,l,1e-6,n,c,d)),this.appendExecutor(e,n)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();u.executeEnd=u.end=t,0===g.first&&(g.first=t),b&&0===b.first&&(b.first=t);const i={};this.sourceBuffers.forEach((([t,s])=>{t&&(i[t]=Vi.getBuffered(s))})),this.appendErrors[n]=0,"audio"===n||"video"===n?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:h,part:o,chunkMeta:a,parent:h.type,timeRanges:i})},onError:t=>{var i;const s={type:p.MEDIA_ERROR,parent:h.type,details:m.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:h,part:o,chunkMeta:a,error:t,err:t,fatal:!1},e=null==(i=this.media)?void 0:i.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)s.details=m.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!e)s.errorAction=Ti(!0);else if(t.name===Bn&&0===this.sourceBufferCount)s.errorAction=Ti(!0);else{const t=++this.appendErrors[n];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${e||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||e)&&(s.fatal=!0)}this.hls.trigger(y.ERROR,s)}};this.append(E,n,this.isPending(this.tracks[n]))}getFlushOp(t,i,s){return this.log(`queuing "${t}" remove ${i}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,i,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove ${i}-${s} from "${t}" SourceBuffer`,e)}}}onBufferFlushing(t,i){const{type:s,startOffset:e,endOffset:n}=i;s?this.append(this.getFlushOp(s,e,n),s):this.sourceBuffers.forEach((([t])=>{t&&this.append(this.getFlushOp(t,e,n),t)}))}onFragParsed(t,i){const{frag:s,part:e}=i,n=[],r=e?e.elementaryStreams:s.elementaryStreams;r[it]?n.push("audiovideo"):(r[Z]&&n.push("audio"),r[tt]&&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(y.FRAG_BUFFERED,{frag:s,part:e,stats:e?e.stats:s.stats,id:s.type})}),n).catch((t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(t,i){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var i,s;return t&&(!(null!=(i=this.tracks[t])&&i.ended)||(null==(s=this.tracks[t])?void 0:s.ending))}))}onBufferEos(t,i){var s;this.sourceBuffers.forEach((([t])=>{if(t){const s=this.tracks[t];i.type&&i.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}}));const e=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var i;return t&&!(null!=(i=this.tracks[t])&&i.ended)}))&&(e?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(y.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach((([t])=>{if(null!==t){const i=this.tracks[t];i&&(i.ending=!1)}}))}onLevelUpdated(t,{details:i}){i.fragments.length&&(this.details=i,this.updateDuration())}updateDuration(){this.blockUntilOpen((()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)}))}onError(t,i){if(i.details===m.BUFFER_APPEND_ERROR&&i.frag){var s;const t=null==(s=i.errorAction)?void 0:s.nextAutoLevel;f(t)&&t!==i.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:i,media:s}=this;if(!s||null===i)return;if(!this.sourceBufferCount)return;const e=t.config,n=s.currentTime,r=i.levelTargetDuration,h=i.live&&null!==e.liveBackBufferLength?e.liveBackBufferLength:e.backBufferLength;if(f(h)&&h>=0){const t=Math.max(h,r),i=Math.floor(n/r)*r-t;this.flushBackBuffer(n,r,i)}if(f(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){this.sourceBuffers.forEach((([t,i])=>{if(i){const n=Vi.getBuffered(i);if(n.length>0&&s>n.start(0)){var e;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:s});const i=this.tracks[t];if(null!=(e=this.details)&&e.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=i&&i.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}}))}flushFrontBuffer(t,i,s){this.sourceBuffers.forEach((([i,e])=>{if(e){const n=Vi.getBuffered(e),r=n.length;if(r<2)return;const h=n.start(r-1),o=n.end(r-1);if(s>h||t>=h&&t<=o)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:i})}}))}getDurationAndRange(){var t;const{details:i,mediaSource:s}=this;if(!i||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const e=i.edge;if(i.live&&this.hls.config.liveDurationInfinity){if(i.fragments.length&&i.live&&s.setLiveSeekableRange){const t=Math.max(0,i.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,e)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return f(n)?{duration:n}:null;const r=this.media.duration;return e>(f(s.duration)?s.duration:0)&&e>r||!f(r)?{duration:e}:null}updateMediaSource({duration:t,start:i,end:s}){const e=this.mediaSource;this.media&&e&&"open"===e.readyState&&(e.duration!==t&&(f(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),e.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${e.duration}. Setting seekable range to ${i}-${s}.`),e.setLiveSeekableRange(i,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:i,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${i} codec events expected: ${t}) ${ri(s)}`),this.tracksReady){var e;const t=null==(e=this.transferData)?void 0:e.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach((([i,s])=>{if(i){const e=this.tracks[i];t[i]={buffer:s,container:e.container,codec:e.codec,supplemental:e.supplemental,levelCodec:e.levelCodec,id:e.id,metadata:e.metadata}}})),this.hls.trigger(y.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([t])=>{this.executeNext(t)}))}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:i,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in t){const r=n,h=t[r];if(this.isPending(h)){const t=this.getTrackCodec(h,r),n=`${h.container};codecs=${t}`;h.codec=t,this.log(`creating sourceBuffer(${n})${this.currentOp(r)?" Queued":""} ${ri(h)}`);try{const t=s.addSourceBuffer(n);i[Gn(r)]=[r,t],h.buffer=t}catch(t){var e;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(r),null==(e=this.operationQueue)||e.removeBlockers(),delete this.tracks[r],void this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:r,mimeType:n,parent:h.id})}this.trackSourceBuffer(r,h)}}this.bufferCreated()}getTrackCodec(t,i){const s=t.supplemental;let e=t.codec;s&&("video"===i||"audiovideo"===i)&&Rt(s,"video")&&(e=function(t,i){const s=[];if(t){const i=t.split(",");for(let t=0;t<i.length;t++)Ct(i[t],"video")||s.push(i[t])}return i&&s.push(i),s.join(",")}(e,s));const n=Gt(e,t.levelCodec);return n?"audio"===i.slice(0,5)?jt(n,this.appendSource):n:""}trackSourceBuffer(t,i){const s=i.buffer;if(!s)return;const e=this.getTrackCodec(i,t);this.tracks[t]={buffer:s,codec:e,container:i.container,levelCodec:i.levelCodec,supplemental:i.supplemental,metadata:i.metadata,id:i.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",((t,i)=>{const s=i.removedRanges;null!=s&&s.length&&this.hls.trigger(y.BUFFER_FLUSHED,{type:t})}))}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 i=this.currentOp(t);i&&i.onStart()}onSBUpdateEnd(t){var i;if("closed"===(null==(i=this.mediaSource)?void 0:i.readyState))return void this.resetBuffer(t);const s=this.currentOp(t);s&&(s.onComplete(),this.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(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:e,fatal:!1});const n=this.currentOp(t);n&&n.onError(e)}updateTimestampOffset(t,i,s,e,n,r){Math.abs(i-t.timestampOffset)>=s&&(this.log(`Updating ${e} SourceBuffer timestampOffset to ${i} (sn: ${n} cc: ${r})`),t.timestampOffset=i)}removeExecutor(t,i,s){const{media:e,mediaSource:n}=this,r=this.tracks[t],h=null==r?void 0:r.buffer;if(!e||!n||!h)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=f(e.duration)?e.duration:1/0,a=f(n.duration)?n.duration:1/0,l=Math.max(0,i),u=Math.min(s,o,a);u>l&&(!r.ending||r.ended)?(r.ended=!1,this.log(`Removing [${l},${u}] from the ${t} SourceBuffer`),h.remove(l,u)):this.shiftAndExecuteNext(t)}appendExecutor(t,i){const s=this.tracks[i],e=null==s?void 0:s.buffer;if(!e)throw new _n(`Attempting to append to the ${i} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,e.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch((t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some((([t,i])=>t&&i.updating))}isQueued(){return this.sourceBuffers.some((([t])=>t&&!!this.currentOp(t)))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,i=this.sourceBufferTypes){if(!i.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:s}=this,e=i.map((t=>this.appendBlocker(t)));return i.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(e).then((()=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(t){t.forEach((t=>{var i;const s=null==(i=this.tracks[t])?void 0:i.buffer;s&&!s.updating&&this.shiftAndExecuteNext(t)}))}append(t,i,s){this.operationQueue&&this.operationQueue.append(t,i,s)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((t,i)=>t+(this.isPending(this.tracks[i])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((t,[i])=>t+(i?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([t])=>t)).filter((t=>!!t))}addBufferListener(t,i,s){const e=this.tracks[t];if(!e)return;const n=e.buffer;if(!n)return;const r=s.bind(this,t);e.listeners.push({event:i,listener:r}),n.addEventListener(i,r)}removeBufferListeners(t){const i=this.tracks[t];if(!i)return;const s=i.buffer;s&&(i.listeners.forEach((t=>{s.removeEventListener(t.event,t.listener)})),i.listeners.length=0)}},capLevelController:Hn,errorController:class extends P{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(y.ERROR,this.onError,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.ERROR,this.onError,this),t.off(y.ERROR,this.onErrorOut,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.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)===S?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,i){var s;if(i.fatal)return;const e=this.hls,n=i.context;switch(i.details){case m.FRAG_LOAD_ERROR:case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_ERROR:case m.KEY_LOAD_TIMEOUT:return void(i.errorAction=this.getFragRetryOrSwitchAction(i));case m.FRAG_PARSING_ERROR:if(null!=(s=i.frag)&&s.gap)return void(i.errorAction=Ti());case m.FRAG_GAP:case m.FRAG_DECRYPT_ERROR:return i.errorAction=this.getFragRetryOrSwitchAction(i),void(i.errorAction.action=2);case m.LEVEL_EMPTY_ERROR:case m.LEVEL_PARSING_ERROR:{var r,h;const t=i.parent===S?i.level:e.loadLevel;i.details===m.LEVEL_EMPTY_ERROR&&null!=(r=i.context)&&null!=(h=r.levelDetails)&&h.live?i.errorAction=this.getPlaylistRetryOrSwitchAction(i,t):(i.levelRetry=!1,i.errorAction=this.getLevelSwitchAction(i,t))}return;case m.LEVEL_LOAD_ERROR:case m.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(i.errorAction=this.getPlaylistRetryOrSwitchAction(i,n.level)));case m.AUDIO_TRACK_LOAD_ERROR:case m.AUDIO_TRACK_LOAD_TIMEOUT:case m.SUBTITLE_LOAD_ERROR:case m.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=e.loadLevelObj;if(t&&(n.type===$&&t.hasAudioGroup(n.groupId)||n.type===k&&t.hasSubtitleGroup(n.groupId)))return i.errorAction=this.getPlaylistRetryOrSwitchAction(i,e.loadLevel),i.errorAction.action=2,void(i.errorAction.flags=1)}return;case m.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=e.loadLevelObj,s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?i.errorAction={action:2,flags:2,hdcpLevel:s}:this.keySystemError(i)}return;case m.BUFFER_ADD_CODEC_ERROR:case m.REMUX_ALLOC_ERROR:case m.BUFFER_APPEND_ERROR:var o;return void(i.errorAction||(i.errorAction=this.getLevelSwitchAction(i,null!=(o=i.level)?o:e.loadLevel)));case m.INTERNAL_EXCEPTION:case m.BUFFER_APPENDING_ERROR:case m.BUFFER_FULL_ERROR:case m.LEVEL_SWITCH_ERROR:case m.BUFFER_STALLED_ERROR:case m.BUFFER_SEEK_OVER_HOLE:case m.BUFFER_NUDGE_ON_STALL:return void(i.errorAction=Ti())}i.type===p.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=wi(this.hls.config.playlistLoadPolicy,t),e=this.playlistError++;if(Si(s,e,bi(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=wi(t.details.startsWith("key")?r:n,t),o=i.levels.reduce(((t,i)=>t+i.fragmentError),0);if(e&&(t.details!==m.FRAG_GAP&&e.fragmentError++,Si(h,o,bi(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===m.BUFFER_APPEND_ERROR&&e.fragmentError++;let a=-1;const{levels:l,loadLevel:u,minAutoLevel:c,maxAutoLevel:d}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(n=t.frag)?void 0:n.type,v=(f===T&&i===m.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(i===m.BUFFER_ADD_CODEC_ERROR||i===m.BUFFER_APPEND_ERROR))&&l.some((({audioCodec:t})=>e.audioCodec!==t)),g="video"===t.sourceBufferName&&(i===m.BUFFER_ADD_CODEC_ERROR||i===m.BUFFER_APPEND_ERROR)&&l.some((({codecSet:t,audioCodec:i})=>e.codecSet!==t&&e.audioCodec===i)),{type:p,groupId:y}=null!=(r=t.context)?r:{};for(let s=l.length;s--;){const n=(s+u)%l.length;if(n!==u&&n>=c&&n<=d&&0===l[n].loadError){var h,o;const s=l[n];if(i===m.FRAG_GAP&&f===S&&t.frag){const i=l[n].details;if(i){const s=gi(t.frag,i.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===$&&s.hasAudioGroup(y)||p===k&&s.hasSubtitleGroup(y))continue;if(f===T&&null!=(h=e.audioGroups)&&h.some((t=>s.hasAudioGroup(t)))||f===E&&null!=(o=e.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||v&&e.audioCodec===s.audioCodec||!v&&e.audioCodec!==s.audioCodec||g&&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===m.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=Zt[Zt.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){if(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,t.details===m.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const i=Xt(t.mimeType),s=this.hls.levels;for(let e=s.length;e--;)s[e][`${t.sourceBufferName}Codec`]===i&&this.hls.removeLevel(e)}}},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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}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(y.FPS_DROP,{currentDropped:t,currentDecoded:n,totalDroppedFrames:s}),r>0&&t>h.config.fpsDroppedMonitoringThreshold*n){let t=h.currentLevel;h.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=t)&&(t-=1,h.trigger(y.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:ms,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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:Wh,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 ie{constructor(t,i,s){super(t,i,s,"subtitle-stream-controller",E),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,i){this.stopLoad(),this.state=te.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=i?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,i){this.tracksBuffered=[],super.onMediaDetaching(t,i)}onLevelLoaded(t,i){this.mainDetails=i.details}onSubtitleFragProcessed(t,i){const{frag:s,success:e}=i;if(this.fragContextChanged(s)||(et(s)&&(this.fragPrevious=s),this.state=te.IDLE),!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),this.media&&this.tick()}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,E)}}onError(t,i){const s=i.frag;(null==s?void 0:s.type)===E&&(i.details===m.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==te.STOPPED&&(this.state=te.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:i}){this.levels&&Rn(this.levels,i)?this.levels=i.map((t=>new ei(t))):(this.tracksBuffered=[],this.levels=i.map((t=>{const i=new ei(t);return this.tracksBuffered[i.id]=[],i})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,E),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.state!==te.STOPPED&&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){if(r.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);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?(Zs(r,t),a=r.fragmentStart):i&&(a=i.start,Hs(r,a)),t&&!this.startFragRequested&&this.setStartPosition(t,a)}o.details=r,this.levelLastLoaded=o,h===e&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:r,id:h,groupId:i.groupId}),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===te.IDLE)&&(gi(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&&es(e.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),e.key.buffer,e.iv.buffer,ns(e.method)).catch((t=>{throw n.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((s=>{const e=performance.now();n.trigger(y.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:t,tdecrypt:e}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=te.IDLE}))}}doTick(){if(this.media){if(this.state===te.IDLE){const{currentTrackId:t,levels:i}=this,s=null==i?void 0:i[t];if(!s||!i.length||!s.details)return;if(this.waitForLive(s))return;const{config:e}=this,n=this.getLoadPosition(),r=Vi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,e.maxBufferHole),{end:h,len:o}=r,a=s.details;if(o>this.hls.maxBufferLength+a.levelTargetDuration)return;const l=a.fragments,u=l.length,c=a.edge;let d=null;const f=this.fragPrevious;if(h<c){const t=e.maxFragLookUpTolerance,i=h>c-t?0:t;d=gi(f,l,Math.max(l[0].start,h),i),!d&&f&&f.start<l[0].start&&(d=l[0])}else d=l[u-1];if(d=this.filterReplacedPrimary(d,s.details),!d)return;const v=l[d.sn-a.startSN-1];if(v&&v.cc===d.cc&&this.fragmentTracker.getState(v)===Ei&&(d=v),this.fragmentTracker.getState(d)===Ei){const t=this.mapToInitFragWhenRequired(d);t&&this.loadFragment(t,s,h)}}}else this.state=te.IDLE}loadFragment(t,i,s){et(t)?super.loadFragment(t,i,s):this._loadInitSegment(t,i)}get mediaBufferTimeRanges(){return new Zr(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Cn{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.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Fr(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(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVEL_LOADING,this.onLevelLoading,this),t.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(y.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(t,i){const s=this.media;if(!s)return;const e=!!i.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,e||Fr(s.textTracks).forEach((t=>{Nr(t)}))}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=li(i,t);if(s>-1)n=t[s];else{const t=li(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(y.SUBTITLE_TRACKS_UPDATED,r),-1!==e&&-1===this.trackId&&this.setSubtitleTrack(e)}}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||ui(n,t)))return e}if(t){for(let s=0;s<i.length;s++)if(On(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(On(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(Nn(i[s],t))return s}return-1}onError(t,i){!i.fatal&&i.context&&(i.context.type!==k||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){if(-1===t.id)return this.setSubtitleTrack(-1),null;const i=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&ui(t,s))return s;const e=li(t,this.tracksInGroup);if(e>-1){const t=this.tracksInGroup[e];return this.setSubtitleTrack(e),t}if(s)return null;{const s=li(t,i);if(s>-1)return i[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,i){super.loadingPlaylist(t,i);const s=t.id,e=t.groupId,n=this.getUrlWithDirectives(t.url,i),r=t.details,h=null==r?void 0:r.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${e}${void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:""}${h&&r.live?" age "+h.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:i||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const i=Fr(t.textTracks),s=this.currentTrack;let e;if(s&&(e=i.filter((t=>Nn(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||!f(t))return void this.warn(`Invalid subtitle track id: ${t}`);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(y.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(y.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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(y.FRAG_LOADING,this.onFragLoading,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this),t.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(y.FRAG_LOADING,this.onFragLoading,this),t.off(y.FRAG_LOADED,this.onFragLoaded,this),t.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Hh(this,"textTrack1"),i=new Hh(this,"textTrack2"),s=new Hh(this,"textTrack3"),e=new Hh(this,"textTrack4");this.cea608Parser1=new ph(1,t,i),this.cea608Parser2=new ph(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(y.CUES_PARSED,{type:"captions",cues:n,track:t})}}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){const{unparsedVttFrags:r}=this;s===S&&(this.initPTS[i.cc]={baseTime:e,timescale:n}),r.length&&(this.unparsedVttFrags=[],r.forEach((t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,t):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))}getExistingTrack(t,i){const{media:s}=this;if(s)for(let e=0;e<s.textTracks.length;e++){const n=s.textTracks[e];if(Vh(n,{name:t,lang:i,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))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,Nr(s[t]),Rr(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(y.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,i.mediaSource||this._cleanTracks()}onMediaDetaching(t,i){const s=!!i.transferMedia;if(this.media=null,s)return;const{captionsTracks:e}=this;Object.keys(e).forEach((t=>{Nr(e[t]),delete e[t]})),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++)Nr(i[t])}onSubtitleTracksUpdated(t,i){const s=i.subtitleTracks||[],e=s.some((t=>t.textCodec===Ph));if(this.config.enableWebVTT||e&&this.config.enableIMSC1){if(Rn(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,i=t?Fr(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]&&Vh(i[s],t)){e=i[s],i[s]=null;break}e&&(s=e)}if(s)Nr(s);else{const i=Kh(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&&this.hls.logger.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(y.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===S){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===E)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===Ph?this._parseIMSC1(s,e):this._parseVTTs(i)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,i){const s=this.hls;Nh(i,this.initPTS[t.cc],(i=>{this._appendCues(i,t.level),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(y.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 Mh,a=j(new Uint8Array(t)).trim().replace(xh,"\n").split("\n"),l=[],u=i?function(t,i=1){return fn(t,9e4,1/i)}(i.baseTime,i.timescale):0;let c,d="00:00.000",v=0,g=0,p=!0;o.oncue=function(t){const r=s[e];let h=s.ccOffset;const o=(v-u)/9e4;if(null!=r&&r.new&&(void 0!==g?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(c=new Error("Missing initPTS for VTT MPEGTS"));h=o-s.presentationOffset}const a=t.endTime-t.startTime,d=wn(9e4*(t.startTime+h-g),9e4*n)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+a,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=Dh(t.startTime,t.endTime,f)),t.endTime>0&&l.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?h(c):r(l)},a.forEach((t=>{if(p){if(Ih(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{Ih(t,"LOCAL:")?d=t.slice(6):Ih(t,"MPEGTS:")&&(v=parseInt(t.slice(7)))}));try{g=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(!(f(i)&&f(s)&&f(e)&&f(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*e,i+=36e5*n,i}(d)/1e3}catch(t){c=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}(null!=(i=s.initSegment)&&i.data?Tt(s.initSegment.data,new Uint8Array(e)).buffer:e,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(y.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),o.logger.log(`Failed to parse VTT cue: ${i}`),n&&h>s.cc||o.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:i})}))}_fallbackToIMSC1(t,i){const s=this.tracks[t.level];s.textCodec||Nh(i,this.initPTS[t.cc],(()=>{s.textCodec=Ph,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=>Or(s,t)))}else{const e=this.tracks[i];if(!e)return;s.trigger(y.CUES_PARSED,{type:"subtitles",cues:t,track:e.default?"default":"subtitles"+i})}}onFragDecrypted(t,i){const{frag:s}=i;s.type===E&&this.onFragLoaded(y.FRAG_LOADED,i)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,i){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:e}=i;if(s.type!==S||"NONE"!==this.closedCaptionsForLevel(s))for(let t=0;t<e.length;t++){const i=e[t].bytes;if(i){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(i);this.cea608Parser1.addData(e[t].pts,s[0]),this.cea608Parser2.addData(e[t].pts,s[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=>Ur(t[e],i,s)))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==e){const{textTracks:t}=this;Object.keys(t).forEach((s=>Ur(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 ie{constructor(t,i,s){super(t,i,s,"audio-stream-controller",T),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!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.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(y.BUFFER_RESET,this.onBufferReset,this),t.on(y.BUFFER_CREATED,this.onBufferCreated,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(y.FRAG_LOADING,this.onFragLoading,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(y.BUFFER_RESET,this.onBufferReset,this),t.off(y.BUFFER_CREATED,this.onBufferCreated,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(y.FRAG_LOADING,this.onFragLoading,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:i,id:s,initPTS:e,timescale:n}){if(s===S){const t=i.cc,s=this.fragCurrent;if(this.initPTS[t]={baseTime:e,timescale:n},this.log(`InitPTS for cc: ${t} found from main: ${e}/${n}`),this.mainAnchor=i,this.state===te.WAITING_INIT_PTS){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==t)&&this.syncWithAnchor(i,null==s?void 0:s.frag)}else!this.hls.hasEnoughToStart&&s&&s.cc!==t?(s.abortRequests(),this.syncWithAnchor(i,s)):this.state===te.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,i){var s;const e=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(i&&(null==e?void 0:e.cc)===i.cc)return;const n=(e||t).cc,r=yi(this.getLevelDetails(),n,this.getLoadPosition());r&&(this.log(`Waiting fragment cc (${null==i?void 0:i.cc}) cancelled because video is at cc ${t.cc}`),this.startFragRequested=!1,this.nextLoadPosition=r.start,this.resetLoadingState(),this.state===te.IDLE&&this.doTickIdle())}startLoad(t,i){if(!this.levels)return this.startPosition=t,void(this.state=te.STOPPED);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s,this.state=te.IDLE):this.state=te.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=i?-1:t,this.tick()}doTick(){switch(this.state){case te.IDLE:this.doTickIdle();break;case te.WAITING_TRACK:{const{levels:t,trackId:i}=this,s=null==t?void 0:t[i],e=null==s?void 0:s.details;if(e&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(e))break;this.state=te.WAITING_INIT_PTS}break}case te.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),s=this.retryDate;if(!s||i>=s||null!=(t=this.media)&&t.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=te.IDLE}break}case te.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:i,part:s,cache:e,complete:n}=t,r=this.mainAnchor;if(void 0!==this.initPTS[i.cc]){this.waitingData=null,this.state=te.FRAG_LOADING;const t={frag:i,part:s,payload:e.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),n&&super._handleFragmentLoadComplete(t)}else r&&r.cc!==t.frag.cc&&this.syncWithAnchor(r,t.frag)}else this.state=te.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:i,levels:s,media:e,trackId:n}=this;if(!this.buffering||!e&&!this.primaryPrefetch&&(this.startFragRequested||!i.config.startFragPrefetch)||null==s||!s[n])return;const r=s[n],h=r.details;if(!h||this.waitForLive(r)||this.waitForCdnTuneIn(h))return this.state=te.WAITING_TRACK,void(this.startFragRequested=!1);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,Z,T));const a=this.getFwdBufferInfo(o,T);if(null===a)return;if(!this.switchingTrack&&this._streamEnded(a,h))return i.trigger(y.BUFFER_EOS,{type:"audio"}),void(this.state=te.ENDED);const l=a.len,u=i.maxBufferLength,c=h.fragments,d=c[0].start,f=this.getLoadPosition(),v=this.flushing?f:a.end;if(this.switchingTrack&&e&&h.PTSKnown&&f<d&&(a.end>d||a.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),e.currentTime=d+.05),l>=u&&!this.switchingTrack&&v<c[c.length-1].start)return;let g=this.getNextFragment(v,h);if(g&&this.isLoopLoading(g,v)&&(g=this.getNextFragmentLoopLoading(g,h,a,S,u)),!g)return void(this.bufferFlushed=!0);let p=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&p&&et(g)&&!g.endList&&(!h.live||!this.loadingParts&&v<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(p)===Mi&&(this.mainFragLoading=p=null),p&&et(p))){if(g.start>p.end){const t=this.fragmentTracker.getFragAtPos(v,S);t&&t.end>p.end&&(p=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(g.start>p.end)return}this.loadFragment(g,r,v)}onMediaDetaching(t,i){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,i)}onAudioTracksUpdated(t,{audioTracks:i}){this.resetTransmuxer(),this.levels=i.map((t=>new ei(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.switchingTrack=i,this.flushAudioIfNeeded(i),this.state!==te.STOPPED&&(this.setInterval(100),this.state=te.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=i,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,i){this.mainDetails=i.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,i){var s;const{levels:e}=this,{details:n,id:r,groupId:h,track:o}=i;if(!e)return void this.warn(`Audio tracks reset while loading track ${r} "${o.name}" of "${h}"`);const a=this.mainDetails;if(!a||n.endCC>a.endCC||a.expired)return this.cachedTrackLoadedData=i,void(this.state!==te.STOPPED&&(this.state=te.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${o.name}" of "${h}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const l=e[r];let u=0;if(n.live||null!=(s=l.details)&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var c;l.details&&(u=this.alignPlaylists(n,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)),n.alignedSliding||(Js(n,a),n.alignedSliding||Zs(n,a),u=n.fragmentStart)}l.details=n,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(a,u),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:i.groupId}),this.state!==te.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=te.IDLE),this.tick()}_handleFragmentLoadProgress(t){var i;const s=t.frag,{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 u=r.defaultAudioCodec||a.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Pn(this.hls,T,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 Hi(s.level,s.sn,s.stats.chunkCount,n.byteLength,i,-1!==i);c.push(n,f,u,"",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 ee,complete:!1};t.push(new Uint8Array(n)),this.state!==te.STOPPED&&(this.state=te.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,i){this.bufferFlushed=this.flushing=!1;const s=i.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,i){!this.audioOnly&&i.frag.type===S&&et(i.frag)&&(this.mainFragLoading=i,this.state===te.IDLE&&this.tick())}onFragBuffered(t,i){const{frag:s,part:e}=i;if(s.type===T)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(et(s)){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,D({},t)))}this.fragBufferedComplete(s,e),this.media&&this.tick()}else this.audioOnly||s.type!==S||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,i){var s;if(i.fatal)this.state=te.ERROR;else switch(i.details){case m.FRAG_GAP:case m.FRAG_PARSING_ERROR:case m.FRAG_DECRYPT_ERROR:case m.FRAG_LOAD_ERROR:case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_ERROR:case m.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(T,i);break;case m.AUDIO_TRACK_LOAD_ERROR:case m.AUDIO_TRACK_LOAD_TIMEOUT:case m.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==te.WAITING_TRACK||(null==(s=i.context)?void 0:s.type)!==$||(this.state=te.IDLE);break;case m.BUFFER_ADD_CODEC_ERROR:case m.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)||this.resetLoadingState();break;case m.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case m.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}onBufferFlushing(t,{type:i}){i!==tt&&(this.flushing=!0)}onBufferFlushed(t,{type:i}){if(i!==tt){this.flushing=!1,this.bufferFlushed=!0,this.state===te.ENDED&&(this.state=te.IDLE);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,i,T),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:u}=l,{audio:c,text:d,id3:f,initSegment:v}=n;if(!this.fragContextChanged(o)&&u){if(this.state=te.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,v.tracks,t,r),e.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:v.tracks})}if(c){const{startPTS:t,endPTS:i,startDTS:s,endDTS:e}=c;a&&(a.elementaryStreams[Z]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(Z,t,i,s,e),this.bufferFragmentData(c,o,a,r)}if(null!=f&&null!=(i=f.samples)&&i.length){const t=x({id:s,frag:o,details:u},f);e.trigger(y.FRAG_PARSING_METADATA,t)}if(d){const t=x({id:s,frag:o,details:u},d);e.trigger(y.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,i,s,e){if(this.state!==te.PARSING)return;if(i.video&&delete i.video,i.audiovideo&&delete i.audiovideo,!i.audio)return;const n=i.audio;n.id=T;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(y.BUFFER_CODECS,i);const h=n.initSegment;null!=h&&h.byteLength&&this.hls.trigger(y.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.switchingTrack||e===Ei||e===Li)if(et(t))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=te.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==i.details.fragmentStart&&Zs(i.details,s)}else super.loadFragment(t,i,s);else this._loadInitSegment(t,i);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;ui({name:i,lang:s,assocLang:e,characteristics:n,audioCodec:r,channels:h},t,ci)||(fi(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:i}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,i.trigger(y.AUDIO_TRACK_SWITCHED,D({},t))}},audioTrackController:class extends Cn{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVEL_LOADING,this.onLevelLoading,this),t.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(y.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=li(i,t,ci);if(s>-1)n=t[s];else{const t=li(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(y.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(y.ERROR,{type:p.MEDIA_ERROR,details:m.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}}onError(t,i){!i.fatal&&i.context&&(i.context.type!==$||i.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(i.context.groupId)||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&&ui(t,e,ci))return e;const n=li(t,this.tracksInGroup,ci);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),u=di(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 li(t,r,n)>-1}));return u>-1?u:di(i,e,(i=>{const e=i.audioGroups,r=s.filter((t=>!e||-1!==e.indexOf(t.groupId)));return li(t,r,n)>-1}))}(t,i.levels,s,e,ci);if(-1===n)return null;i.nextLoadLevel=n}if(t.channels||t.audioCodec){const i=li(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.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(y.AUDIO_TRACK_SWITCHING,D({},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||ui(t,e,ci)))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(ui({name:s,lang:e,assocLang:n,characteristics:r,audioCodec:h,channels:o},i[t],ci))return t;for(let s=0;s<i.length;s++)if(On(t.attrs,i[s].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s;for(let s=0;s<i.length;s++)if(On(t.attrs,i[s].attrs,["LANGUAGE"]))return s}return-1}loadPlaylist(t){super.loadPlaylist();const i=this.currentTrack;this.shouldLoadPlaylist(i)&&fi(i.url,this.hls)&&this.scheduleLoading(i,t)}loadingPlaylist(t,i){super.loadingPlaylist(t,i);const s=t.id,e=t.groupId,n=this.getUrlWithDirectives(t.url,i),r=t.details,h=null==r?void 0:r.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${e}${void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:""}${h&&r.live?" age "+h.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:e,deliveryDirectives:i||null,track:t})}},emeController:Pr,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:Kn,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:i,part:s}=t,e=this.hls.levels[i.level],n=this.getObjectType(i),r={d:1e3*(s||i).duration,ot:n};n!==Xn&&n!==Vn&&n!=Wn||(r.br=e.bitrate/1e3,r.tb=this.getTopBandwidth(n)/1e3,r.bl=this.getBufferLength(n));const h=s?this.getNextPart(s):this.getNextFrag(i);null!=h&&h.url&&h.url!==i.url&&(r.nor=h.url),this.apply(t,r)}catch(t){this.hls.logger.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||t.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHED,this.onMediaDetached,this),t.on(y.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHED,this.onMediaDetached,this),t.off(y.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=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:Yn,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,i={}){x(i,this.createData()),this.starved&&(i.ot===zn||i.ot===Xn||i.ot===Wn)&&(i.bs=!0,i.su=!0,this.starved=!1),null==i.su&&(i.su=this.buffering);const{includeKeys:s}=this;s&&(i=Object.keys(i).reduce(((t,e)=>(s.includes(e)&&(t[e]=i[e]),t)),{}));const e={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),function(t,i,s){x(t,function(t,i={}){const s={};if(!t)return s;const e=Object.entries(t),n=Object.entries(ir).concat(Object.entries((null==i?void 0:i.customHeaderMap)||{})),r=e.reduce(((t,i)=>{var s,e;const[r,h]=i,o=(null===(s=n.find((t=>t[1].includes(r))))||void 0===s?void 0:s[0])||Jn;return null!==(e=t[o])&&void 0!==e||(t[o]={}),t[o][r]=h,t}),{});return Object.entries(r).reduce(((t,[s,e])=>(t[s]=Ar(e,i),t)),s)}(i,s))}(t.headers,i,e)):t.url=function(t,i,s){const e=function(t,i={}){if(!t)return"";const s=Ar(t,i);return`CMCD=${encodeURIComponent(s)}`}(i,s);if(!e)return t;if(Lr.test(t))return t.replace(Lr,e);const n=t.includes("?")?"&":"?";return`${t}${n}${e}`}(t.url,i,e)}getNextFrag(t){var i;const s=null==(i=this.hls.levels[t.level])?void 0:i.details;if(s)return s.fragments[t.sn-s.startSN+1]}getNextPart(t){var i,s;const{index:e,fragment:n}=t,r=null==(i=this.hls.levels[n.level])||null==(s=i.details)?void 0:s.partList;if(r){const{sn:t}=n;for(let i=r.length-1;i>=0;i--){const s=r[i];if(s.index===e&&s.fragment.sn===t)return r[i+1]}}}getObjectType(t){const{type:i}=t;return"subtitle"===i?qn:"initSegment"===t.sn?zn:"audio"===i?Vn:"main"===i?this.hls.audioTracks.length?Xn:Wn:void 0}getTopBandwidth(t){let i,s=0;const e=this.hls;if(t===Vn)i=e.audioTracks;else{const t=e.maxAutoLevel;i=e.levels.slice(0,t>-1?t+1:e.levels.length)}return i.forEach((t=>{t.bitrate>s&&(s=t.bitrate)})),s>0?s:NaN}getBufferLength(t){const i=this.media,s=t===Vn?this.audioBuffer:this.videoBuffer;return s&&i?1e3*Vi.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 extends P{constructor(t){super("content-steering",t.logger),this.hls=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.registerListeners()}registerListeners(){const t=this.hls;t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((t,i)=>(-1===t.indexOf(i.pathwayId)&&t.push(i.pathwayId),t)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}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=this.pathways()),e&&e.length>1&&(this.updatePathwayPriority(e),s.resolved=this.pathwayId!==n),i.details!==m.BUFFER_APPEND_ERROR||i.fatal?s.resolved||this.warn(`Could not resolve ${i.details} ("${i.error.message}") with content-steering for Pathway: ${n} levels: ${t?t.length:t} priorities: ${ri(e)} penalized: ${ri(this.penalizedPathways)}`):s.resolved=!0}}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,zs(i),this.hls.trigger(y.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===$&&e[s].hasAudioGroup(t)||i===k&&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 Zi(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=xr(t.uri,i["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",h),l=new ei({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),Mr(this.audioTracks,s,h,n),Mr(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!==(null==n?void 0: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(y.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)}},interstitialsController:class extends P{constructor(t,i){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;const i=t-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const s=i<=-.01;this.timelinePos=t,this.bufferedPos=t;const e=this.playingItem;if(!e)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(t,t-i)&&this.updateSchedule(),this.checkBuffer(),s&&t<e.start||t>=e.end){var n;const t=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(e)&&null!=(n=this.media)&&n.paused&&(this.shouldPlay=!1),!s){const i=this.findItemIndex(e);if(t>i){const s=this.schedule.findJumpRestrictedIndex(i+1,t);if(s>i)return void this.setSchedulePosition(s)}}return void this.setSchedulePosition(t)}const r=this.playingAsset;if(!r){if(this.playingLastItem&&this.isInterstitial(e)){const i=e.event.assetList[0];i&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,i))}return}const h=r.timelineStart;(s&&t<h||t>=h+(r.duration||0))&&this.setScheduleToAssetAtTime(t,r)},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const i=this.playingItem;if(!i||this.playingLastItem)return;if(t>=i.end){this.timelinePos=i.end;const t=this.findItemIndex(i);this.setSchedulePosition(t+1)}const s=this.playingAsset;s&&t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,i)=>{const s=this.schedule,e=this.playingItem,n=s.events||[],r=s.items||[],h=s.durations,o=t.map((t=>t.identifier)),a=!(!n.length&&!o.length);(a||i)&&this.log(`INTERSTITIALS_UPDATED (${n.length}): ${n}\nSchedule: ${r.map((t=>Yr(t)))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`),this.playerQueue.forEach((t=>{if(t.interstitial.appendInPlace){const i=t.assetItem.timelineStart,s=t.timelineOffset-i;if(s)try{t.timelineOffset=i}catch(e){Math.abs(s)>_r&&this.warn(`${e} ("${t.assetId}" ${t.timelineOffset}->${i})`)}}}));let l=null;if(e){const t=this.updateItem(e,this.timelinePos);this.itemsMatch(e,t)&&(this.playingItem=t,this.waitingItem=this.endedItem=null,l=()=>this.trimInPlace(t,e))}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u){const t=this.updateItem(u,this.bufferedPos);this.itemsMatch(u,t)?(this.bufferingItem=t,l||(l=()=>this.trimInPlace(t,u))):u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))}if(t.forEach((t=>{t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,null)}))})),a||i){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:r.slice(0),durations:h,removedIds:o}),this.isInterstitial(e)&&o.includes(e.event.identifier))return this.warn(`Interstitial "${e.event.identifier}" removed while playing`),void this.primaryFallback(e.event);l&&l(),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=i,this.assetListLoader=new Qr(t),this.schedule=new qr(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this),t.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(y.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(y.MEDIA_ENDED,this.onMediaEnded,this),t.on(y.ERROR,this.onError,this),t.on(y.DESTROYING,this.onDestroying,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.BUFFER_APPENDED,this.onBufferAppended,this),t.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(y.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(y.MEDIA_ENDED,this.onMediaEnded,this),t.off(y.ERROR,this.onError,this),t.off(y.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Dr(t,"play",this.onPlay),Dr(t,"pause",this.onPause),Dr(t,"seeking",this.onSeeking),Dr(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,i){const s=this.media=i.media;Ir(s,"seeking",this.onSeeking),Ir(s,"timeupdate",this.onTimeupdate),Ir(s,"play",this.onPlay),Ir(s,"pause",this.onPause)}onMediaAttached(t,i){const s=this.effectivePlayingItem,e=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!e){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,i){const s=!!i.transferMedia,e=this.media;if(this.media=null,!s&&(e&&this.removeMediaListeners(e),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const t=this,i=()=>t.bufferingItem||t.waitingItem,s=i=>i?t.getAssetPlayer(i.identifier):i,e=(i,e,n,h,o)=>{if(i){let a=i[e].start;const l=i.event;if(l){if("playout"===e||l.timelineOccupancy!==jr.Point){const t=s(n);(null==t?void 0:t.interstitial)===l&&(a+=t.assetItem.startOffset+t[o])}}else a+=("bufferedPos"===h?r():t[h])-i.start;return a}return 0},n=(i,s)=>{if(0!==i&&"primary"!==s&&t.schedule.length){var e;const n=t.schedule.findItemIndexAtTime(i),r=null==(e=t.schedule.items)?void 0:e[n];if(r)return i+(r[s].start-r.start)}return i},r=()=>{const i=t.bufferedPos;return i===Number.MAX_VALUE?h("primary"):Math.max(i,0)},h=i=>{var s;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:t.schedule.durations[i]},o=(i,n)=>{var r,h;const o=t.effectivePlayingItem;if(null!=o&&null!=(r=o.event)&&r.restrictions.skip)return;t.log(`seek to ${i} "${n}"`);const a=t.effectivePlayingItem,l=t.schedule.findItemIndexAtTime(i,n),u=null==(h=t.schedule.items)?void 0:h[l],c=t.getBufferingPlayer(),d=null==c?void 0:c.interstitial,f=null==d?void 0:d.appendInPlace,v=a&&t.itemsMatch(a,u);if(a&&(f||v)){const r=s(t.playingAsset),h=(null==r?void 0:r.media)||t.primaryMedia;if(h){const s="primary"===n?h.currentTime:e(a,n,t.playingAsset,"timelinePos","currentTime"),o=(f?s:h.currentTime)+(i-s);if(o>=0&&(!r||f||o<=r.duration))return void(h.currentTime=o)}}if(u){let s=i;"primary"!==n&&(s=u.start+(i-u[n].start));const e=!t.isInterstitial(u);if(t.isInterstitial(a)&&!a.event.appendInPlace||!e&&!u.event.appendInPlace){if(a){const r=t.findItemIndex(a);if(l>r){const i=t.schedule.findJumpRestrictedIndex(r+1,l);if(i>r)return void t.setSchedulePosition(i)}let h=0;if(e)t.timelinePos=s,t.checkBuffer();else{var g;const t=null==u||null==(g=u.event)?void 0:g.assetList;if(t){const s=i-(u[n]||u).start;for(let i=t.length;i--;){const e=t[i];if(e.duration&&s>=e.startOffset&&s<e.startOffset+e.duration){h=i;break}}}}t.setSchedulePosition(l,h)}}else{const i=t.media||(f?null==c?void 0:c.media:null);i&&(i.currentTime=s)}}},a=()=>{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const e=i();return t.isInterstitial(e)?e:null},l={get currentTime(){const i=a(),s=t.effectivePlayingItem;return s&&s===i?e(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(i){const s=a(),e=t.effectivePlayingItem;e&&e===s&&o(i+e.playout.start,"playout")},get duration(){const t=a();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var i;const s=null==(i=a())?void 0:i.event.assetList;return s?s.map((i=>t.getAssetPlayer(i.identifier))):[]},get playingIndex(){var i;const s=null==(i=a())?void 0:i.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return a()}};this.manager={get events(){var i,s;return(null==(i=t.schedule)||null==(s=i.events)?void 0:s.slice(0))||[]},get schedule(){var i,s;return(null==(i=t.schedule)||null==(s=i.items)?void 0:s.slice(0))||[]},get interstitialPlayer(){return a()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return i()},get bufferingIndex(){const s=i();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){return t.findItemIndex(t.effectivePlayingItem)},primary:{get bufferedEnd(){return r()},get currentTime(){const i=t.timelinePos;return i>0?i:0},set currentTime(t){o(t,"primary")},get duration(){return h("primary")},get seekableStart(){var i;return(null==(i=t.primaryDetails)?void 0:i.fragmentStart)||0}},integrated:{get bufferedEnd(){return e(i(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return e(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){o(t,"integrated")},get duration(){return h("integrated")},get seekableStart(){var i;return n((null==(i=t.primaryDetails)?void 0:i.fragmentStart)||0,"integrated")}},skip:()=>{const i=t.effectivePlayingItem,s=null==i?void 0:i.event;if(s&&!s.restrictions.skip){const e=t.findItemIndex(i);s.appendInPlace?o(i.playout.start+i.event.duration+.001,"playout"):t.advanceAfterAssetEnded(s,e,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const i=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&i&&s)&&this.findItemIndex(i)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,i,s;if(null===this.mediaSelection)return;const e=this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&!e.event.appendInPlace)return;let n=this.media;!n&&null!=(t=this.bufferingItem)&&null!=(i=t.event)&&i.appendInPlace&&(n=this.primaryMedia);const r=null==(s=n)?void 0:s.currentTime;return void 0!==r&&f(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,i){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,i)}transferMediaFromPlayer(t,i){const s=t.media;if(t.interstitial.appendInPlace&&s===this.primaryMedia){if(this.bufferingAsset=null,(!i||this.isInterstitial(i)&&!i.event.appendInPlace)&&i&&s)return void(this.detachedData={media:s});const e=t.transferMedia();this.log(`transfer MediaSource from ${t} ${ri(e)}`),this.detachedData=e}else i&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,i){var s,e;if(t.media===i)return;let n=null;const r=this.hls,h=t!==r,o=h&&t.interstitial.appendInPlace,a=null==(s=this.detachedData)?void 0:s.mediaSource;let l;if(r.media)o&&(n=r.transferMedia(),this.detachedData=n),l="Primary";else if(a){const t=this.getBufferingPlayer();t?(n=t.transferMedia(),l=`${t}`):l="detached MediaSource"}else l="detached media";if(!n)if(a)n=this.detachedData,this.log(`using detachedData: MediaSource ${ri(n)}`);else if(!this.detachedData||r.media===i){const t=this.playerQueue;t.length>1&&t.forEach((t=>{if(h&&t.interstitial.appendInPlace!==o){const i=t.interstitial;this.clearInterstitial(t.interstitial,null),i.appendInPlace=!1,i.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${i}`)}})),this.hls.detachMedia(),this.detachedData={media:i}}const u=n&&"mediaSource"in n&&"closed"!==(null==(e=n.mediaSource)?void 0:e.readyState),c=u&&n?n:i;this.log(`${u?"transfering MediaSource":"attaching media"} to ${h?t:"Primary"} from ${l}`),c===n&&(c.overrides={duration:this.schedule.duration,endOfStream:!h||h&&t.assetId===this.schedule.assetIdAtEnd,cueRemoval:!h}),t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,i=t.events;if(!i||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.effectivePlayingItem;if(-1===this.timelinePos){const s=this.hls.startPosition;if(this.timelinePos=s,i.length&&i[0].cue.pre){const s=t.findEventIndex(i[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const i=this.timelinePos=s>0?s:0,e=t.findItemIndexAtTime(i);this.setSchedulePosition(e)}}else if(s&&!this.playingItem){const i=t.findItemIndex(s);this.setSchedulePosition(i)}}advanceAfterAssetEnded(t,i,s){const e=Xr(t,s);if(t.isAssetPastPlayoutLimit(e)){const s=this.schedule.items;if(s){const e=i+1;if(e>=s.length)return void this.setSchedulePosition(-1);const n=t.resumeTime;this.timelinePos<n&&(this.timelinePos=n,this.checkBuffer()),this.setSchedulePosition(e)}}else this.setSchedulePosition(i,e)}setScheduleToAssetAtTime(t,i){const s=this.schedule,e=i.parentIdentifier,n=s.getEvent(e);if(n){const i=s.findEventIndex(e),r=s.findAssetIndex(n,t);this.advanceAfterAssetEnded(n,i,r-1)}}setSchedulePosition(t,i){const s=this.schedule.items;if(!s||this.playbackDisabled)return;this.log(`setSchedulePosition ${t}, ${i}`);const e=t>=0?s[t]:null,n=this.playingItem,r=this.playingLastItem;if(this.isInterstitial(n)){var h;const a=n.event,l=this.playingAsset,u=null==l?void 0:l.identifier,c=u?this.getAssetPlayer(u):null;if(c&&u&&(!this.eventItemsMatch(n,e)||void 0!==i&&u!==(null==(h=a.assetList)?void 0:h[i].identifier))){var o;const i=a.findAssetIndex(l);if(this.log(`INTERSTITIAL_ASSET_ENDED ${i+1}/${a.assetList.length} ${Wr(l)}`),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:i,event:a,schedule:s.slice(0),scheduleIndex:t,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(a,this.findItemIndex(this.playingItem),i));this.retreiveMediaSource(u,e),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,e)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${a} ${Yr(n)}`),a.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:a,schedule:s.slice(0),scheduleIndex:t}),a.cue.once)){this.updateSchedule();const t=this.schedule.items;if(e&&t){const s=this.findItemIndex(e);this.advanceSchedule(s,t,i,n,r)}return}}this.advanceSchedule(t,s,i,n,r)}advanceSchedule(t,i,s,e,n){const r=t>=0?i[t]:null,h=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach((i=>{const s=i.interstitial,e=this.schedule.findEventIndex(s.identifier);(e<t||e>t+1)&&this.clearInterstitial(s,r)})),this.isInterstitial(r)){this.timelinePos=Math.min(Math.max(this.timelinePos,r.start),r.end);const n=r.event;if(void 0===s){const i=Xr(n,(s=this.schedule.findAssetIndex(n,this.timelinePos))-1);if(n.isAssetPastPlayoutLimit(i))return void this.advanceAfterAssetEnded(n,t,s);s=i}const o=this.waitingItem;this.assetsBuffered(r,h)||this.setBufferingItem(r);let a=this.preloadAssets(n,s);if(this.eventItemsMatch(r,o||e)||(this.waitingItem=r,this.log(`INTERSTITIAL_STARTED ${Yr(r)} ${n.appendInPlace?"append in place":""}`),this.hls.trigger(y.INTERSTITIAL_STARTED,{event:n,schedule:i.slice(0),scheduleIndex:t})),!n.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${n}`);if(n.assetListLoader&&(n.assetListLoader.destroy(),n.assetListLoader=void 0),!h)return void this.log(`Waiting for attachMedia to start Interstitial ${n}`);this.waitingItem=this.endedItem=null,this.playingItem=r;const l=n.assetList[s];if(!l){const e=i[t+1],r=this.media;return e&&r&&!this.isInterstitial(e)&&r.currentTime<e.start&&(r.currentTime=this.timelinePos=e.start),void this.advanceAfterAssetEnded(n,t,s||0)}if(a||(a=this.getAssetPlayer(l.identifier)),(null===a||a.destroyed)&&(this.warn(`asset ${s+1}/${n.assetList.length} player destroyed ${n}`),a=this.createAssetPlayer(n,l,s)),!this.eventItemsMatch(r,this.bufferingItem)&&n.appendInPlace&&this.isAssetBuffered(l))return;this.startAssetPlayer(a,s,i,t,h),this.shouldPlay&&Jr(a.media)}else null!==r?(this.resumePrimary(r,t,e),this.shouldPlay&&Jr(this.hls.media)):n&&this.isInterstitial(e)&&(this.endedItem=null,this.playingItem=e,e.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t,i;return null==(t=this.mediaSelection)||null==(i=t.main)?void 0:i.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,i,s){var e;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${Yr(t)}`),null==(e=this.detachedData)||!e.mediaSource){let s=this.timelinePos;(s<t.start||s>=t.end)&&(s=this.getPrimaryResumption(t,i),this.timelinePos=s),this.attachPrimary(s,t)}if(!s)return;const n=this.schedule.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Yr(t)}`),this.hls.trigger(y.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:i}),this.checkBuffer())}getPrimaryResumption(t,i){const s=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===i)return this.hls.startPosition;if(t&&(s<t.fragmentStart||s>t.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(t){const i=this.getAssetPlayer(t.identifier);return null!=i&&i.hls?i.hls.bufferedToEnd:Vi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,i,s){i?this.setBufferingItem(i):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const e=this.primaryMedia;if(!e)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,e),s&&this.startLoadingPrimaryAt(t,s)),s||(this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,i){var s;const e=this.hls;!e.loadingEnabled||!e.media||Math.abs(((null==(s=e.mainForwardBufferInfo)?void 0:s.start)||e.media.currentTime)-t)>.5?e.startLoad(t,i):e.bufferingEnabled||e.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(y.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(y.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,i){if(-1===i.level)return;const s=this.hls.levels[i.level],e=D(D({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=e,this.schedule.parseInterstitialDateRanges(e,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,i){const s=this.hls.audioTracks[i.id],e=this.mediaSelection;if(!e)return void(this.altSelection=D(D({},this.altSelection),{},{audio:s}));const n=D(D({},e),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(t,i){const s=this.hls.subtitleTracks[i.id],e=this.mediaSelection;if(!e)return void(this.altSelection=D(D({},this.altSelection),{},{subtitles:s}));const n=D(D({},e),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(t,i){const s=ai(i);this.playerQueue.forEach((t=>t.hls.setAudioOption(i)||t.hls.setAudioOption(s)))}onSubtitleTrackSwitch(t,i){const s=ai(i);this.playerQueue.forEach((t=>t.hls.setSubtitleOption(i)||-1!==i.id&&t.hls.setSubtitleOption(s)))}onBufferCodecs(t,i){const s=i.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,i){this.checkBuffer()}onBufferFlushed(t,i){const s=this.playingItem;!s||this.itemsMatch(s,this.bufferingItem)||this.isInterstitial(s)||(this.bufferedPos=this.timelinePos,this.checkBuffer())}onBufferedToEnd(t){const i=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&i){for(let t=0;t<i.length;t++){const e=i[t];if(e.cue.post){var s;const t=this.schedule.findEventIndex(e.identifier),i=null==(s=this.schedule.items)?void 0:s[t];this.isInterstitial(i)&&this.eventItemsMatch(i,this.bufferingItem)&&this.bufferedToItem(i,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const i=this.playingItem;if(!this.playingLastItem&&i){const t=this.findItemIndex(i);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,i){const s=this.schedule.items;return t&&s&&s[this.findItemIndex(t,i)]||null}trimInPlace(t,i){if(this.isInterstitial(t)&&t.event.appendInPlace&&i.end-t.end>.25){t.event.assetList.forEach(((i,s)=>{t.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(i.identifier,null)}));const i=t.end+.25,s=Vi.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.attachPrimary(i,null),this.flushFrontBuffer(i))}}itemsMatch(t,i){return!!i&&(t===i||t.event&&i.event&&this.eventItemsMatch(t,i)||!t.event&&!i.event&&this.findItemIndex(t)===this.findItemIndex(i))}eventItemsMatch(t,i){var s;return!!i&&(t===i||t.event.identifier===(null==(s=i.event)?void 0:s.identifier))}findItemIndex(t,i){return t?this.schedule.findItemIndex(t,i):-1}updateSchedule(){const t=this.mediaSelection;t&&this.schedule.updateSchedule(t,[])}checkBuffer(t){const i=this.schedule.items;if(!i)return;const s=Vi.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,i,t)}updateBufferedPos(t,i,s){const e=this.schedule,n=this.bufferingItem;if(this.bufferedPos>t)return;if(1===i.length&&this.itemsMatch(i[0],n))return void(this.bufferedPos=t);const r=this.playingItem,h=this.findItemIndex(r);let o=e.findItemIndexAtTime(t);if(this.bufferedPos<t){var a,l;const s=this.findItemIndex(n),e=Math.min(s+1,i.length-1),r=i[e];if((-1===o&&n&&t>=n.end||null!=(a=r.event)&&a.appendInPlace&&t+.01>=r.start)&&(o=e),e-h>1&&!1===(null==n||null==(l=n.event)?void 0:l.appendInPlace))return;if(this.bufferedPos=t,o>s&&o>h)this.bufferedToItem(r);else{const i=this.primaryDetails;this.primaryLive&&i&&t>i.edge-i.targetduration&&r.start<i.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(r)&&this.preloadAssets(r.event,0)}}else s&&r&&!this.itemsMatch(r,n)&&(o===h?this.bufferedToItem(r):o===h+1&&this.bufferedToItem(i[o]))}assetsBuffered(t,i){return 0!==t.event.assetList.length&&!t.event.assetList.some((t=>{const s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(i))}))}setBufferingItem(t){const i=this.bufferingItem,s=this.schedule;if(this.itemsMatch(t,i))this.bufferingItem!==t&&(this.bufferingItem=t);else{const{items:e,events:n}=s;if(!e||!n)return i;const r=this.isInterstitial(t),h=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=h?h.remaining:i?i.end-this.timelinePos:0;this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Yr(t)}`+(i?` (${o.toFixed(2)} remaining)`:"")),this.playbackDisabled||(r?t.event.assetList.forEach((t=>{const i=this.getAssetPlayer(t.identifier);i&&i.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((t=>t.pauseBuffering())))),this.hls.trigger(y.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:e.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}return i}bufferedToItem(t,i=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,i);else if(null!==s){this.bufferingAsset=null;const i=this.detachedData;i&&i.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t)}}preloadPrimary(t){const i=this.findItemIndex(t),s=this.getPrimaryResumption(t,i);this.startLoadingPrimaryAt(s)}bufferedToEvent(t,i){const s=t.event;if(0===s.assetList.length&&!s.assetListLoader||!s.cue.once){const t=this.preloadAssets(s,i);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;s.assetList[i]&&e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,i){const s=t.assetUrl,e=t.assetList.length;if(0!==e||t.assetListLoader){if(!t.cue.once&&e){for(let s=i;s<e;s++){const i=t.assetList[s],e=this.getAssetPlayerQueueIndex(i.identifier);-1!==e&&!this.playerQueue[e].destroyed||i.error||this.createAssetPlayer(t,i,s)}return this.getAssetPlayer(t.assetList[i].identifier)}}else{const r=t.timelineStart;if(t.appendInPlace){var n;const i=this.playingItem;this.isInterstitial(i)||(null==i||null==(n=i.nextEvent)?void 0:n.identifier)!==t.identifier||this.flushFrontBuffer(r+.25)}let h,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(h=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${i+1}/${s?1:e} ${t}${h?` live-start: ${o} start-offset: ${h}`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const a=this.assetListLoader.loadAssetList(t,h);a&&(t.assetListLoader=a)}return null}flushFrontBuffer(t){const i=this.requiredTracks;i&&(this.log(`Removing front buffer starting at ${t}`),Object.keys(i).forEach((i=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:i})})))}getAssetPlayerQueueIndex(t){const i=this.playerQueue;for(let s=0;s<i.length;s++)if(t===i[s].assetId)return s;return-1}getAssetPlayer(t){const i=this.getAssetPlayerQueueIndex(t);return this.playerQueue[i]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:i}=this;if(i)for(let s=0;s<t.length;s++)if(t[s].media===i)return t[s];return null}createAsset(t,i,s,e,n,r){const h={parentIdentifier:t.identifier,identifier:Gr(t,r,i),duration:n,startOffset:s,timelineStart:e,uri:r};return this.createAssetPlayer(t,h,i)}createAssetPlayer(t,i,s){const e=this.hls,n=e.userConfig;let r=n.videoPreference;const h=e.loadLevelObj||e.levels[e.currentLevel];(r||h)&&(r=x({},r),h.videoCodec&&(r.videoCodec=h.videoCodec),h.videoRange&&(r.allowedVideoRanges=[h.videoRange]));const o=e.audioTracks[e.audioTrack],a=e.subtitleTracks[e.subtitleTrack];let l=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-i.timelineStart;if(t>1){const s=i.duration;s&&t<s&&(l=t)}}const u=i.identifier,c=D(D({},n),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:e.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:e.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:r,audioPreference:o||n.audioPreference,subtitlePreference:a||n.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,i.timelineStart&&(c.timelineOffset=i.timelineStart));const d=c.cmcd;null!=d&&d.sessionId&&d.contentId&&(c.cmcd=x({},d,{contentId:Br(i.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${t} and asset ${u}`);const f=new zr(this.HlsPlayerClass,c,t,i);this.playerQueue.push(f),t.assetList[s]=i;const v=e=>{if(e.live){const i=new Error(`Interstitials MUST be VOD assets ${t}`);return void this.handleAssetItemError({fatal:!0,type:p.OTHER_ERROR,details:m.INTERSTITIAL_ASSET_ITEM_ERROR,error:i},t,this.schedule.findEventIndex(t.identifier),s,i.message)}const n=e.edge-e.fragmentStart,r=i.duration;(null===r||n>r)&&(this.log(`Interstitial asset "${u}" duration change ${r} > ${n}`),i.duration=n,this.updateSchedule())};f.on(y.LEVEL_UPDATED,((t,{details:i})=>v(i))),f.on(y.LEVEL_PTS_UPDATED,((t,{details:i})=>v(i)));const g=(t,i)=>{const s=this.getAssetPlayer(u);if(s&&i.tracks){s.off(y.BUFFER_CODECS,g),s.tracks=i.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};f.on(y.BUFFER_CODECS,g);const b=()=>{var s;const e=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${e}`),!e)return;const n=this.schedule.findEventIndex(t.identifier),r=null==(s=this.schedule.items)?void 0:s[n];if(this.isInterstitial(r)){const s=t.findAssetIndex(i),e=Xr(t,s);if(t.isAssetPastPlayoutLimit(e)){var h;const t=null==(h=this.schedule.items)?void 0:h[n+1];t&&this.bufferedToItem(t)}else this.bufferedToItem(r,e)}};f.on(y.BUFFERED_TO_END,b);const w=i=>()=>{if(!this.getAssetPlayer(u))return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,i)};return f.once(y.MEDIA_ENDED,w(s)),f.once(y.PLAYOUT_LIMIT_REACHED,w(1/0)),f.on(y.ERROR,((i,e)=>{const n=this.getAssetPlayer(u);if(e.details!==m.BUFFER_STALLED_ERROR)this.handleAssetItemError(e,t,this.schedule.findEventIndex(t.identifier),s,`Asset player error ${e.error} ${t}`);else if(null!=n&&n.media){const i=n.currentTime,s=n.duration-i;i&&t.appendInPlace&&s/n.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${u} ${t} at ${n.media.currentTime}`),b()):(this.warn(`Stalled at ${i} of ${i+s} in asset ${u} ${t}`),this.onTimeupdate(),this.checkBuffer(!0))}})),f.on(y.DESTROYING,(()=>{if(!this.getAssetPlayer(u))return;const i=new Error(`Asset player destroyed unexpectedly ${u}`);this.handleAssetItemError({fatal:!0,type:p.OTHER_ERROR,details:m.INTERSTITIAL_ASSET_ITEM_ERROR,error:i},t,this.schedule.findEventIndex(t.identifier),s,i.message)})),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Wr(i)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:i,assetListIndex:s,event:t,player:f}),f}clearInterstitial(t,i){t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,i)})),t.reset()}resetAssetPlayer(t){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){this.log(`reset asset player "${t}" after error`);const s=this.playerQueue[i];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(t,i){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){this.log(`clear asset player "${t}" toSegment: ${i?Yr(i):i}`);const e=this.playerQueue[s];this.transferMediaFromPlayer(e,i),this.playerQueue.splice(s,1),e.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,i,s,e,n){const{interstitial:r,assetItem:h,assetId:o}=t,a=r.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=h,l&&l.identifier===o||(l&&(this.clearAssetPlayer(l.identifier,s[e]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${i+1}/${a} ${Wr(h)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:h,assetListIndex:i,event:r,schedule:s.slice(0),scheduleIndex:e,player:t})),this.bufferAssetPlayer(t,n)}bufferAssetPlayer(t,i){var s,e;const{interstitial:n,assetItem:r}=t,h=this.schedule.findEventIndex(n.identifier),o=null==(s=this.schedule.items)?void 0:s[h];if(!o)return;this.setBufferingItem(o),this.bufferingAsset=r;const a=this.getBufferingPlayer();if(a===t)return;const l=n.appendInPlace;if(l&&!1===(null==a?void 0:a.interstitial.appendInPlace))return;const u=(null==a?void 0:a.tracks)||(null==(e=this.detachedData)?void 0:e.tracks)||this.requiredTracks;if(l&&r!==this.playingAsset){if(!t.tracks)return;if(u&&!_(u,t.tracks)){const i=new Error(`Asset ${Wr(r)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),s={fatal:!0,type:p.OTHER_ERROR,details:m.INTERSTITIAL_ASSET_ITEM_ERROR,error:i},e=n.findAssetIndex(r);return void this.handleAssetItemError(s,n,h,e,i.message)}}this.transferMediaTo(t,i)}handleAssetItemError(t,i,s,e,n){if(t.details===m.BUFFER_STALLED_ERROR)return;const r=i.assetList[e];this.warn(`INTERSTITIAL_ASSET_ERROR ${r?Wr(r):r} ${t.error}`);const h=null==r?void 0:r.identifier,o=this.getAssetPlayerQueueIndex(h),a=this.playerQueue[o]||null,l=this.schedule.items,u=x({},t,{fatal:!1,errorAction:Ti(!0),asset:r,assetListIndex:e,event:i,schedule:l,scheduleIndex:s,player:a});if(this.hls.trigger(y.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const c=this.playingAsset,d=new Error(n);if(r&&(this.clearAssetPlayer(h,null),r.error=d),i.assetList.some((t=>!t.error))){for(let t=e;t<i.assetList.length;t++)this.resetAssetPlayer(i.assetList[t].identifier);this.updateSchedule()}else i.error=d;i.error?this.primaryFallback(i):c&&c.identifier===h&&this.advanceAfterAssetEnded(i,s,e)}primaryFallback(t){const i=t.timelineStart,s=this.effectivePlayingItem;if(this.updateSchedule(),s){this.log(`Fallback to primary from event "${t.identifier}" start: ${i} pos: ${this.timelinePos} playing: ${s?Yr(s):"<none>"} error: ${t.error}`);let e=this.timelinePos;-1===e&&(e=this.hls.startPosition);const n=this.updateItem(s,e);this.itemsMatch(s,n)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(i,null),this.flushFrontBuffer(i));const r=this.schedule.findItemIndexAtTime(e);this.setSchedulePosition(r)}else this.checkStart()}onAssetListLoaded(t,i){var s;const e=i.event,n=e.identifier,r=i.assetListResponse.ASSETS;if(!this.schedule.hasEvent(n))return;const h=e.timelineStart,o=e.duration;let a=0;r.forEach(((t,i)=>{const s=parseFloat(t.DURATION);this.createAsset(e,i,a,h+a,s,t.URI),a+=s})),e.duration=a,this.log(`Loaded asset-list with duration: ${a} (was: ${o}) ${e}`);const l=this.waitingItem,u=(null==l?void 0:l.event.identifier)===n;this.updateSchedule();const c=null==(s=this.bufferingItem)?void 0:s.event;if(u){var d;const t=this.schedule.findEventIndex(n),i=null==(d=this.schedule.items)?void 0:d[t];if(i){if(!this.playingItem&&this.timelinePos>i.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return e.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${e}`),void this.primaryFallback(e);this.setBufferingItem(i)}this.setSchedulePosition(t)}else if((null==c?void 0:c.identifier)===n&&c.appendInPlace){const t=e.assetList[0],i=this.getAssetPlayer(t.identifier),s=this.primaryMedia;t&&i&&s&&this.bufferAssetPlayer(i,s)}}onError(t,i){switch(i.details){case m.ASSET_LIST_PARSING_ERROR:case m.ASSET_LIST_LOAD_ERROR:case m.ASSET_LIST_LOAD_TIMEOUT:{const t=i.interstitial;t&&this.primaryFallback(t);break}case m.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}}}});function io(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(io):Object.keys(t).reduce(((i,s)=>(i[s]=io(t[s]),i)),{}):t}class so extends Gi{constructor(t,i){super("gap-controller",t.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=i,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,i){this.setInterval(100),this.mediaSource=i.mediaSource;const s=this.media=i.media;Ir(s,"playing",this.onMediaPlaying),Ir(s,"waiting",this.onMediaWaiting),Ir(s,"ended",this.onMediaEnded)}onMediaDetaching(t,i){this.clearInterval();const{media:s}=this;s&&(Dr(s,"playing",this.onMediaPlaying),Dr(s,"waiting",this.onMediaWaiting),Dr(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,i){this.buffered=i.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const i=this.media.currentTime;this.poll(i,this.lastCurrentTime),this.lastCurrentTime=i}poll(t,i){var s,e;const n=null==(s=this.hls)?void 0:s.config;if(!n)return;const r=this.media;if(!r)return;const{seeking:h}=r,o=this.seeking&&!h,a=!this.seeking&&h,l=r.paused&&!h||r.ended||0===r.playbackRate;if(this.seeking=h,t!==i)return i&&(this.ended=0),this.moved=!0,h||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!l&&t>i&&this.nudgeOnVideoHole(t,i)),void(0===this.waiting&&this.stallResolved(t));if(a||o)return void(o&&this.stallResolved(t));if(l)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&r.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})));if(!Vi.getBuffered(r).length)return void(this.nudgeRetry=0);const u=Vi.bufferInfo(r,t,0),c=u.nextStart||0,d=this.fragmentTracker;if(h&&d&&this.hls){const i=eo(this.hls.inFlightFragments,t),s=u.len>2,e=!c||i||c-t>2&&!d.getPartialFragment(t);if(s||e)return;this.moved=!1}const f=null==(e=this.hls)?void 0:e.latestLevelDetails;if(!this.moved&&null!==this.stalled&&d){if(!(u.len>0||c))return;const i=Math.max(c,u.start||0)-t,s=null!=f&&f.live?2*f.targetduration:2,e=d.getPartialFragment(t);if(i>0&&(i<=s||e))return void(r.paused||this._trySkipBufferHole(e))}const v=n.detectStallWithCurrentTimeMs,g=self.performance.now(),p=this.waiting;let m=this.stalled;if(null===m){if(!(p>0&&g-p<v))return void(this.stalled=g);m=this.stalled=p}const b=g-m;if(!h&&(b>=v||p)&&this.hls){var w;if("ended"===(null==(w=this.mediaSource)?void 0:w.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(y.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}const $=Vi.bufferInfo(r,t,n.maxBufferHole);this._tryFixBufferStall($,b,t)}stallResolved(t){const i=this.stalled;if(i&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-i;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,i){var s;const e=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&e&&e.length>1&&t>e.end(0)){const s=Vi.bufferedInfo(Vi.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&i>=s.start){const s=Vi.timeRangesToArray(e),n=Vi.bufferedInfo(s,i,0).bufferedIndex;if(n>-1&&n<s.length-1){const i=Vi.bufferedInfo(s,t,0).bufferedIndex,e=s[n].end,r=s[n+1].start;if((-1===i||i>n)&&r-e<1&&t-e<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${e} -> ${r} buffered index: ${i}`);this.warn(s.message),this.media.currentTime+=1e-6;const n=this.fragmentTracker.getPartialFragment(t)||void 0,h=Vi.bufferInfo(this.media,t,0);this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:n,buffer:h.len,bufferInfo:h})}}}}}_tryFixBufferStall(t,i,s){var e,n;const{fragmentTracker:r,media:h}=this,o=null==(e=this.hls)?void 0:e.config;if(!h||!r||!o)return;const a=null==(n=this.hls)?void 0:n.latestLevelDetails,l=r.getPartialFragment(s);if((l||null!=a&&a.live&&s<a.fragmentStart)&&(this._trySkipBufferHole(l)||!this.media))return;const u=t.buffered,c=this.adjacentTraversal(t,s);(u&&u.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-s<o.maxBufferHole||c))&&(i>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,i){const s=this.fragmentTracker,e=t.nextStart;if(s&&e){const t=s.getFragAtPos(i,S),n=s.getFragAtPos(e,S);if(t&&n)return n.sn-t.sn<2}return!1}_reportStall(t){const{hls:i,media:s,stallReported:e,stalled:n}=this;if(!e&&null!==n&&s&&i){this.stallReported=!0;const e=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ri(t)})`);this.warn(e.message),i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_STALLED_ERROR,fatal:!1,error:e,buffer:t.len,bufferInfo:t,stalled:{start:n}})}}_trySkipBufferHole(t){var i;const{fragmentTracker:s,media:e}=this,n=null==(i=this.hls)?void 0:i.config;if(!e||!s||!n)return 0;const r=e.currentTime,h=Vi.bufferInfo(e,r,0),o=r<h.start?h.start:h.nextStart;if(o&&this.hls){const i=o-r;if(i>0&&(h.len<=n.maxBufferHole||h.len>0&&h.len<1&&e.readyState<3)){if(i>n.maxBufferHole){let i=!1;if(0===r){const t=s.getAppendedFrag(0,S);t&&o<t.end&&(i=!0)}if(!i){const i=t||s.getAppendedFrag(r,S);if(i){var a;if(null==(a=this.hls.loadLevelObj)||!a.details)return 0;if(eo(this.hls.inFlightFragments,o))return 0;let t=!1,e=i.end;for(;e<o;){const i=s.getAppendedFrag(e,S)||s.getPartialFragment(e);if(!i){t=!0;break}e+=i.duration}if(t)return 0}}}const l=Math.max(o+.05,r+.1);if(this.warn(`skipping hole, adjusting currentTime from ${r} to ${l}`),this.moved=!0,e.currentTime=l,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${l}`);this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:t||void 0,buffer:h.len,bufferInfo:h})}return l}}return 0}_tryNudgeBuffer(t){const{hls:i,media:s,nudgeRetry:e}=this,n=null==i?void 0:i.config;if(!s||!n)return 0;const r=s.currentTime;if(this.nudgeRetry++,e<n.nudgeMaxRetry){const h=r+(e+1)*n.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${h}`);this.warn(o.message),s.currentTime=h,i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const s=new Error(`Playhead still not moving while enough data buffered @${r} after ${n.nudgeMaxRetry} nudges`);this.error(s.message),i.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:t.len,bufferInfo:t})}}}function eo(t,i){const s=no(t.main);if(s&&s.start<=i)return s;const e=no(t.audio);return e&&e.start<=i?e:null}function no(t){if(!t)return null;switch(t.state){case te.IDLE:case te.STOPPED:case te.ENDED:case te.ERROR:return null}return t.frag}function ro(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ho(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,ri(n?D({type:n},e):e))}return r}const oo=(()=>{const t=ro();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ao{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(t,i){var s;this.media=i.media,!1===(null==(s=i.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const t=this.hls.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(t,i){this.media=null,i.transferMedia||(this.id3Track&&(this.removeCues&&Nr(this.id3Track,this.onEventCueEnter),this.id3Track=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 Rr(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=ro();if(r)for(let t=0;t<n.length;t++){const i=n[t].type;if(i===Pe.emsg&&!s||!e)continue;const h=Me(n[t].data);if(h){const s=n[t].pts;let e=s+n[t].duration;e>oo&&(e=oo),e-s<=0&&(e=s+.25);for(let t=0;t<h.length;t++){const n=h[t];if(!xe(n)){this.updateId3CueEnds(s,i);const t=ho(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===oo&&(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===Pe.audioId3&&o:"video"===e?t=>t.type===Pe.emsg&&h:t=>t.type===Pe.audioId3&&o||t.type===Pe.emsg&&h,Ur(n,i,s,t)}}onLevelUpdated(t,{details:i}){this.updateDateRangeCues(i,!0)}onLevelPtsUpdated(t,i){Math.abs(i.drift)>.01&&this.updateDateRangeCues(i.details)}updateDateRangeCues(t,i){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:e}=t,n=Object.keys(e);let r=this.dateRangeCuesAppended;var h;if(s&&i)if(null!=(h=s.cues)&&h.length){const t=Object.keys(r).filter((t=>!n.includes(t)));for(let i=t.length;i--;){const e=t[i],n=r[e].cues;delete r[e],Object.keys(n).forEach((t=>{try{const i=n[t];i.removeEventListener("enter",this.onEventCueEnter),s.removeCue(i)}catch(t){}}))}}else r=this.dateRangeCuesAppended={};const o=t.fragments[t.fragments.length-1];if(0===n.length||!f(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ro();for(let t=0;t<n.length;t++){const i=n[t],s=e[i],h=s.startTime,o=r[i],u=(null==o?void 0:o.cues)||{};let c=(null==o?void 0:o.durationKnown)||!1,d=oo;const{duration:f,endDate:v}=s;if(v&&null!==f)d=h+f,c=!0;else if(s.endOnNext&&!c){const t=n.reduce(((t,i)=>{if(i!==s.id){const n=e[i];if(n.class===s.class&&n.startDate>s.startDate&&(!t||s.startDate<t.startDate))return n}return t}),null);t&&(d=t.startTime,c=!0)}const g=Object.keys(s.attr);for(let t=0;t<g.length;t++){const e=g[t];if("ID"===(l=e)||"CLASS"===l||"CUE"===l||"START-DATE"===l||"DURATION"===l||"END-DATE"===l||"END-ON-NEXT"===l)continue;const n=u[e];if(n)c&&!o.durationKnown?n.endTime=d:Math.abs(n.startTime-h)>.01&&(n.startTime=h,n.endTime=d);else if(a){let t=s.attr[e];ts(e)&&(t=Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const n=ho(a,h,d,{key:e,data:t},Pe.dateRange);n&&(n.id=i,this.id3Track.addCue(n),u[e]=n,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==e&&"X-ASSET-URL"!==e||n.addEventListener("enter",this.onEventCueEnter)))}}r[i]={cues:u,dateRange:s,durationKnown:c}}var l}}class lo{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;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,e=Math.min(i,Math.max(1,s));this.changeMediaPlaybackRate(t,e)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)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(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===a)&&(a=void 0!==n?n:r*e),a+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,e)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),i=this.targetLatency;if(null===t||null===i)return null;const s=this.levelDetails;if(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 t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;return null===t?0:Math.max(t.age-3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration),0)}get forwardBufferLength(){const{media:t}=this,i=this.levelDetails;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.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.ERROR,this.onError,this))}onMediaAttached(t,i){this.media=i.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:i}){i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,i){var s;i.details===m.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,i){var s,e;t.playbackRate!==i&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(e=this.targetLatency)?void 0:e.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${i}`),t.playbackRate=i)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class uo extends Cn{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.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=>{const i=t.attrs;let{audioCodec:l,videoCodec:u}=t;l&&(t.audioCodec=l=jt(l,s)||void 0),u&&(u=t.videoCodec=function(t){const i=t.split(",");for(let t=0;t<i.length;t++){const s=i[t].split(".");s.length>2&&"avc1"===s[0]&&(i[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return i.join(",")}(u));const{width:c,height:d,unknownCodecs:f}=t;let v=f?f.length:0;if(f)for(let i=v;i--;){const s=f[i];this.isAudioSupported(s)?(t.audioCodec=l=l?`${l},${s}`:s,v--,Pt.audio[l.substring(0,4)]=2):this.isVideoSupported(s)&&(t.videoCodec=u=u?`${u},${s}`:s,v--,Pt.video[u.substring(0,4)]=2)}if(h||(h=!(!c||!d)),o||(o=!!u),a||(a=!!l),v||l&&!this.isAudioSupported(l)||u&&!this.isVideoSupported(u))return void this.log(`Some or all CODECS not supported "${i.CODECS}"`);const{CODECS:g,"FRAME-RATE":p,"HDCP-LEVEL":m,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":w}=i,$=`${y||"."}-${t.bitrate}-${b}-${p}-${g}-${w}-${m}`;if(n[$])if(n[$].uri===t.url||t.attrs["PATHWAY-ID"])n[$].addGroupId("audio",i.AUDIO),n[$].addGroupId("text",i.SUBTITLES);else{const i=r[$]+=1;t.attrs["PATHWAY-ID"]=new Array(i+1).join(".");const s=this.createLevel(t);n[$]=s,e.push(s)}else{const i=this.createLevel(t);n[$]=i,r[$]=1,e.push(i)}})),this.filterAndSortMediaOptions(e,i,h,o,a)}createLevel(t){const i=new ei(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),i.supportedResult=zt(t,[])}return i}isAudioSupported(t){return Rt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Rt(t,"video",this.hls.config.preferManagedMediaSource)}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)&&ti.indexOf(n)>-1;var n}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;i.levels.length&&(s=`one or more CODECS in variant not supported: ${ri(i.levels.map((t=>t.attrs.CODECS)).filter(((t,i,s)=>s.indexOf(t)===i)))}`,this.warn(s),t+=` (${s})`);const e=new Error(t);this.hls.trigger(y.ERROR,{type:p.MEDIA_ERROR,details:m.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:i.url,error:e,reason:s})}}));i.audioTracks&&(r=i.audioTracks.filter((t=>!t.audioCodec||this.isAudioSupported(t.audioCodec))),co(r)),i.subtitles&&(h=i.subtitles,co(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 ti.indexOf(t.videoRange)-ti.indexOf(i.videoRange);if(t.videoCodec!==i.videoCodec){const s=Ut(t.videoCodec),e=Ut(i.videoCodec);if(s!==e)return e-s}if(t.uri===i.uri&&t.codecSet!==i.codecSet){const s=Ft(t.codecSet),e=Ft(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 u;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==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const t=Math.min(i,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const c=this.hls.config,d={levels:o,audioTracks:r,subtitleTracks:h,sessionData:i.sessionData,sessionKeys:i.sessionKeys,firstLevel:this._firstLevel,stats:i.stats,audio:n,video:e,altAudio:!(!c.audioStreamController||!c.audioTrackController)&&!(n&&!e)&&r.some((t=>!!t.url))};this.hls.trigger(y.MANIFEST_PARSED,d)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}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(y.ERROR,{type:p.OTHER_ERROR,details:m.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&&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(y.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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const i=this.steering.pathways(),s=t.filter((t=>-1!==i.indexOf(t)));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${i}`);this.steering.pathwayPriority=s}}onError(t,i){!i.fatal&&i.context&&i.context.type===w&&i.context.level===this.level&&this.checkRetry(i)}onFragBuffered(t,{frag:i}){if(void 0!==i&&i.type===S){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=i.levelInfo;var h;if(!r)return this.warn(`Invalid level index ${e}`),void(null!=(h=i.deliveryDirectives)&&h.skip&&(n.deltaUpdateFailed=!0));if(r===this.currentLevel||i.withoutMultiVariant){0===r.fragmentError&&(r.loadError=0);let t=r.details;t===i.details&&t.advanced&&(t=void 0),this.playlistLoaded(e,i,t)}else null!=(s=i.deliveryDirectives)&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,i){super.loadingPlaylist(t,i);const s=this.getUrlWithDirectives(t.uri,i),e=this.currentLevelIndex,n=t.attrs["PATHWAY-ID"],r=t.details,h=null==r?void 0:r.age;this.log(`Loading level index ${e}${void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:""}${n?" Pathway "+n:""}${h&&r.live?" age "+h.toFixed(1)+(r.type&&" "+r.type||""):""} ${s}`),this.hls.trigger(y.LEVEL_LOADING,{url:s,level:e,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||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;if(1===this._levels.length)return;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)));zs(s),this._levels=s,this.currentLevelIndex>-1&&null!=(i=this.currentLevel)&&i.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const e=s.length-1;this._firstLevel=Math.min(this._firstLevel,e),this._startLevel&&(this._startLevel=Math.min(this._startLevel,e)),this.hls.trigger(y.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(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function co(t){const i={};t.forEach((t=>{const s=t.groupId||"";t.id=i[s]=i[s]||0,i[s]++}))}function fo(){return self.SourceBuffer||self.WebKitSourceBuffer}function vo(){if(!B())return!1;const t=fo();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class go extends ie{constructor(t,i,s){super(t,i,s,"stream-controller",S),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,i=t?t.currentTime:null;if(null===i||!f(i))return;if(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i))return;const s=this.getFwdBufferInfoAtPos(t,i,S,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${i} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(y.BUFFER_CREATED,this.onBufferCreated,this),t.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(y.BUFFER_CREATED,this.onBufferCreated,this),t.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,i){if(this.levels){const{lastCurrentTime:s,hls:e}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=e.startLevel;-1===t&&(e.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=e.firstAutoLevel),e.nextLoadLevel=t,this.level=e.loadLevel,this._hasEnoughToStart=!!i}s>0&&-1===t&&!i&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=te.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=i?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=te.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case te.WAITING_LEVEL:{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&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(e))break;this.state=te.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=te.IDLE;break}break}case te.FRAG_LOADING_WAITING_RETRY:{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=te.IDLE}}}this.state===te.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:i,levels:s,media:e}=this;if(null===i||!e&&!this.primaryPrefetch&&(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 2===this.altAudio&&(t.type="video"),this.hls.trigger(y.BUFFER_EOS,t),void(this.state=te.ENDED)}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===te.WAITING_LEVEL||this.waitForLive(r))return this.level=n,this.state=te.WAITING_LEVEL,void(this.startFragRequested=!1);const l=h.len,u=this.getMaxBufferLength(r.maxBitrate);if(l>=u)return;this.backtrackFragment&&this.backtrackFragment.start>h.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:h.end;let d=this.getNextFragment(c,a);if(this.couldBacktrack&&!this.fragPrevious&&d&&et(d)&&this.fragmentTracker.getState(d)!==Mi){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,c)){if(!d.gap){const t=this.audioOnly&&!this.altAudio?Z:tt,i=(t===tt?this.videoBuffer:this.mediaBuffer)||this.media;i&&this.afterBufferFlushed(i,t,S)}d=this.getNextFragmentLoopLoading(d,a,h,S,u)}d&&(!d.initSegment||d.initSegment.data||this.bitrateTest||(d=d.initSegment),this.loadFragment(d,r,c))}loadFragment(t,i,s){const e=this.fragmentTracker.getState(t);e===Ei||e===Li?et(t)?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)):super.loadFragment(t,i,s):this._loadInitSegment(t,i):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,S)}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 te.KEY_LOADING:case te.FRAG_LOADING:case te.FRAG_LOADING_WAITING_RETRY:case te.PARSING:case te.PARSED:this.state=te.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,i){super.flushMainBuffer(t,i,2===this.altAudio?"video":null)}onMediaAttached(t,i){super.onMediaAttached(t,i);const s=i.media;Ir(s,"playing",this.onMediaPlaying),Ir(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,i){const{media:s}=this;s&&(Dr(s,"playing",this.onMediaPlaying),Dr(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,i),i.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!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=fo();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!==te.IDLE)return;const e=i.levelInfo;(!e.details||e.details.live&&(this.levelLastLoaded!==e||e.details.expired)||this.waitForCdnTuneIn(e.details))&&(this.state=te.WAITING_LEVEL)}onLevelLoaded(t,i){var s;const{levels:e,startFragRequested:n}=this,r=i.level,h=i.details,o=h.totalduration;if(!e)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${h.startSN},${h.endSN}]${h.lastPartSn?`[part-${h.lastPartSn}-${h.lastPartIndex}]`:""}, cc [${h.startCC}, ${h.endCC}] duration:${o}`);const a=i.levelInfo,l=this.fragCurrent;!l||this.state!==te.FRAG_LOADING&&this.state!==te.FRAG_LOADING_WAITING_RETRY||l.level!==i.level&&l.loader&&this.abortCurrentFrag();let u=0;if(h.live||null!=(s=a.details)&&s.live){var c;if(this.checkLiveUpdate(h),h.deltaUpdateFailed)return;u=this.alignPlaylists(h,a.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(a.details=h,this.levelLastLoaded=a,n||this.setStartPosition(h,u),this.hls.trigger(y.LEVEL_UPDATED,{details:h,level:r}),this.state===te.WAITING_LEVEL){if(this.waitForCdnTuneIn(h))return;this.state=te.IDLE}n&&h.live&&this.synchronizeToLiveEdge(h),this.tick()}synchronizeToLiveEdge(t){const{config:i,media:s}=this;if(!s)return;const e=this.hls.liveSyncPosition,n=this.getLoadPosition(),r=t.edge,h=n>=t.fragmentStart-i.maxFragLookUpTolerance&&n<=r;if(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._hasEnoughToStart||(this.nextLoadPosition=e),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${r}, reset currentTime to : ${e.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var o;const t=Vi.bufferInfo(s,e,0);if(null==t||null==(o=t.buffered)||!o.length)return void(s.currentTime=e);if(t.start<=n)return void(s.currentTime=e);const{nextStart:i}=Vi.bufferedInfo(t.buffered,n,0);i&&(s.currentTime=i)}else s.currentTime=e}_handleFragmentLoadProgress(t){var i;const s=t.frag,{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];if(!h)return void this.warn(`Level ${s.level} not found on progress`);const 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,u=null==(i=s.initSegment)?void 0:i.data,c=this._getAudioCodec(h),d=this.transmuxer=this.transmuxer||new Pn(this.hls,S,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=e?e.index:-1,v=new Hi(s.level,s.sn,s.stats.chunkCount,n.byteLength,f,-1!==f);d.push(n,u,c,a,s,e,o.totalduration,l,v,this.initPTS[s.cc])}onAudioTrackSwitching(t,i){const s=this.hls,e=2===this.altAudio;if(fi(i.url,s))this.altAudio=1;else{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();if(e)return this.fragmentTracker.removeAllFragments(),s.once(y.BUFFER_FLUSHED,(()=>{var t;null==(t=this.hls)||t.trigger(y.AUDIO_TRACK_SWITCHED,i)})),void s.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(y.AUDIO_TRACK_SWITCHED,i)}}onAudioTrackSwitched(t,i){const s=fi(i.url,this.hls);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?2:0,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,n=s.type===S;if(n){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===te.PARSED&&(this.state=te.IDLE));const t=e?e.stats:s.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),et(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,e)}const r=this.media;r&&(!this._hasEnoughToStart&&Vi.getBuffered(r).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,i){var s;if(i.fatal)this.state=te.ERROR;else switch(i.details){case m.FRAG_GAP:case m.FRAG_PARSING_ERROR:case m.FRAG_DECRYPT_ERROR:case m.FRAG_LOAD_ERROR:case m.FRAG_LOAD_TIMEOUT:case m.KEY_LOAD_ERROR:case m.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(S,i);break;case m.LEVEL_LOAD_ERROR:case m.LEVEL_LOAD_TIMEOUT:case m.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==te.WAITING_LEVEL||(null==(s=i.context)?void 0:s.type)!==w||(this.state=te.IDLE);break;case m.BUFFER_ADD_CODEC_ERROR:case m.BUFFER_APPEND_ERROR:if("main"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&this.resetLoadingState();break;case m.BUFFER_FULL_ERROR:if("main"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case m.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}onFragLoadEmergencyAborted(){this.state=te.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:i}){if(i!==Z||!this.altAudio){const t=(i===tt?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,i,S),this.tick())}}onLevelsUpdated(t,i){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),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=this.timelineOffset;e&&s&&(s+=e);const n=this.getLevelDetails(),r=Vi.getBuffered(t),h=r.length?r.start(0):0,o=h-s,a=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<a||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),i<s&&(this.log(`seek to target start position ${s} from current time ${i} buffer start ${h}`),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((t=>{const{hls:s}=this,e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e))return;i.fragmentError=0,this.state=te.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(y.FRAG_LOADED,t),e.bitrateTest=!1}))}_handleTransmuxComplete(t){var i;const s=this.playlistType,{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:u,text:c,id3:d,initSegment:v}=n,{details:g}=l,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=te.PARSING,v){if(null!=v&&v.tracks){const t=o.initSegment||o;this._bufferInitSegment(l,v.tracks,t,r),e.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:v.tracks})}const t=v.initPTS,i=v.timescale,n=this.initPTS[o.cc];!f(t)||n&&n.baseTime===t&&n.timescale===i||(this.initPTS[o.cc]={baseTime:t,timescale:i},e.trigger(y.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:i}))}if(u&&g){p&&"audiovideo"===u.type&&this.logMuxedErr(o);const t=g.fragments[o.sn-1-g.startSN],i=o.sn===g.startSN,s=!t||o.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:e,startDTS:n,endDTS:h}=u;if(a)a.elementaryStreams[u.type]={startPTS:t,endPTS:e,startDTS:n,endDTS:h};else if(u.firstKeyFrame&&u.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),u.dropped&&u.independent){const n=this.getMainFwdBufferInfo(),r=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole;if(!i&&r<(u.firstKeyFramePTS?u.firstKeyFramePTS:t)-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,e,o.start,h,!0)}else i&&t-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,t,e,n,h),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,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[Z]={startPTS:t,endPTS:i,startDTS:s,endDTS:e}),o.setElementaryStreamInfo(Z,t,i,s,e),this.bufferFragmentData(p,o,a,r)}g&&null!=d&&null!=(i=d.samples)&&i.length&&e.trigger(y.FRAG_PARSING_METADATA,{id:s,frag:o,details:g,samples:d.samples}),g&&c&&e.trigger(y.FRAG_PARSING_USERDATA,{id:s,frag:o,details:g,samples:c.samples})}}logMuxedErr(t){this.warn(`${et(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,i,s,e){if(this.state!==te.PARSING)return;this.audioOnly=!!i.audio&&!i.video,this.altAudio&&!this.audioOnly&&(delete i.audio,i.audiovideo&&this.logMuxedErr(s));const{audio:n,video:r,audiovideo:h}=i;if(n){const s=t.audioCodec;let e=Gt(n.codec,s);"mp4a"===e&&(e="mp4a.40.5");const r=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=n.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===r.indexOf("firefox")&&(e="mp4a.40.5")}e&&-1!==e.indexOf("mp4a.40.5")&&-1!==r.indexOf("android")&&"audio/mpeg"!==n.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),s&&s!==e&&this.log(`Swapping manifest audio codec "${s}" for "${e}"`),n.levelCodec=e,n.id=S,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${e||""}/${s||""}/${n.codec}]`),delete i.audiovideo}if(r){r.levelCodec=t.videoCodec,r.id=S;const s=r.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":r.codec="hvc1.1.6.L120.90";break;case"av01":r.codec="av01.0.04M.08";break;case"avc1":r.codec="avc1.42e01e"}this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s}]${r.codec!==s?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.supplemental:""}`),delete i.audiovideo}h&&(this.log(`Init audiovideo buffer, container:${h.container}, codecs[level/parsed]=[${t.codecs}/${h.codec}]`),delete i.video,delete i.audio);const o=Object.keys(i);if(o.length){if(this.hls.trigger(y.BUFFER_CODECS,i),!this.hls)return;o.forEach((t=>{const n=i[t].initSegment;null!=n&&n.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:t,data:n,frag:s,part:null,chunkMeta:e,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media,S)}get maxBufferLength(){const{levels:t,level:i}=this,s=null==t?void 0:t[i];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}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=te.IDLE}checkFragmentChanged(){const t=this.media;let i=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(Vi.isBuffered(t,s)?i=this.getAppendedFrag(s):Vi.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(y.FRAG_CHANGED,{frag:i}),t&&t.level===s||this.hls.trigger(y.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return f(i)?this.getAppendedFrag(i):null}get currentProgramDateTime(){var t;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(f(i)){const t=this.getLevelDetails(),s=this.currentFrag||(t?gi(null,t.fragments,i):null);if(s){const t=s.programDateTime;if(null!==t)return new Date(t+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 po{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=m.KEY_LOAD_ERROR,s,e,n){return new ji({type:p.NETWORK_ERROR,details:i,fatal:!1,frag:t,response:n,error:s,networkDetails:e})}loadClear(t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length)if(i.length){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))return this.emeController.selectKeySystemFormat(n).then((t=>{if(n.setKeyFormat(t),this.emeController&&this.config.requireKeySystemAccessOnStart){const i=fs(t);if(i)return this.emeController.getKeySystemAccess([i])}}))}}else if(this.config.requireKeySystemAccessOnStart){const t=ps(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}return null}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,m.KEY_LOAD_ERROR,s))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(t,m.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":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(h,t);default:return Promise.reject(this.createKeyLoadError(t,m.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,m.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,m.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),e,D({url:h.url,data:void 0},t)))},onTimeout:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,m.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),e))},onAbort:(t,s,e)=>{this.resetLoader(s),r(this.createKeyLoadError(i,m.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 mo(t){const{type:i}=t;switch(i){case $:return T;case k:return E;default:return S}}function yo(t,i){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=i.url),s}class bo{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_LOADING,this.onLevelLoading,this),t.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,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:b,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,i){const{id:s,level:e,pathwayId:n,url:r,deliveryDirectives:h,levelInfo:o}=i;this.load({id:s,level:e,pathwayId:n,responseType:"text",type:w,url:r,deliveryDirectives:h,levelOrTrack:o})}onAudioTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r,track:h}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:$,url:n,deliveryDirectives:r,levelOrTrack:h})}onSubtitleTrackLoading(t,i){const{id:s,groupId:e,url:n,deliveryDirectives:r,track:h}=i;this.load({id:s,groupId:e,level:null,responseType:"text",type:k,url:n,deliveryDirectives:r,levelOrTrack:h})}onLevelsUpdated(t,i){const s=this.loaders[w];if(s){const t=s.context;t&&!i.levels.some((i=>i===t.levelOrTrack))&&(s.abort(),delete this.loaders[w])}}load(t){var i;const s=this.hls.config;let e,n=this.getInternalLoader(t);if(n){const i=this.hls.logger,s=n.context;if(s&&s.levelOrTrack===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void i.log(s.url===t.url?`[playlist-loader]: ignore ${t.url} ongoing request`:`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`);i.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(e=t.type===b?s.manifestLoadPolicy.default:x({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),f(null==(i=t.deliveryDirectives)?void 0:i.part)){let i;if(t.type===w&&null!==t.level?i=this.hls.levels[t.level].details:t.type===$&&null!==t.id?i=this.hls.audioTracks[t.id].details:t.type===k&&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=x({},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(),Ls.isMediaPlaylist(r)||s.type!==b?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)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:i},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${i}`),this.hls.startLoad(i))}handleMasterPlaylist(t,i,s,e){const n=this.hls,r=t.data,h=yo(t,s),o=Ls.parseMasterPlaylist(r,h);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,e,i);const{contentSteering:a,levels:l,sessionData:u,sessionKeys:c,startTimeOffset:d,variableList:f}=o;this.variableList=f;const{AUDIO:v=[],SUBTITLES:g,"CLOSED-CAPTIONS":p}=Ls.parseMasterPlaylistMedia(r,h,o);v.length&&(v.some((t=>!t.url))||!l[0].audioCodec||l[0].attrs.AUDIO||(this.hls.logger.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 Zi({}),bitrate:0,url:""}))),n.trigger(y.MANIFEST_LOADED,{levels:l,audioTracks:v,subtitles:g,captions:p,contentSteering:a,url:h,stats:i,networkDetails:e,sessionData:u,sessionKeys:c,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,i,s,e,n){const r=this.hls,{id:h,level:o,type:a}=s,l=yo(t,s),u=f(o)?o:f(h)?h:0,c=mo(s),d=Ls.parseLevelPlaylist(t.data,l,u,c,0,this.variableList);if(a===b){const t={attrs:new Zi({}),bitrate:0,details:d,name:"",url:l};d.requestScheduled=i.loading.start+Ks(d,0),r.trigger(y.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(y.ERROR,{type:p.NETWORK_ERROR,details:m.MANIFEST_PARSING_ERROR,fatal:i.type===b,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===w?r+=`: ${t.level} id: ${t.id}`:t.type!==$&&t.type!==k||(r+=` id: ${t.id} group-id: "${t.groupId}"`);const h=new Error(r);this.hls.logger.warn(`[playlist-loader]: ${r}`);let o=m.UNKNOWN,a=!1;const l=this.getInternalLoader(t);switch(t.type){case b:o=s?m.MANIFEST_LOAD_TIMEOUT:m.MANIFEST_LOAD_ERROR,a=!0;break;case w:o=s?m.LEVEL_LOAD_TIMEOUT:m.LEVEL_LOAD_ERROR,a=!1;break;case $:o=s?m.AUDIO_TRACK_LOAD_TIMEOUT:m.AUDIO_TRACK_LOAD_ERROR,a=!1;break;case k:o=s?m.SUBTITLE_TRACK_LOAD_TIMEOUT:m.SUBTITLE_LOAD_ERROR,a=!1}l&&this.resetInternalLoader(t.type);const u={type:p.NETWORK_ERROR,details:o,fatal:a,url:t.url,loader:l,context:t,error:h,networkDetails:i,stats:n};e&&(u.response=D({url:(null==i?void 0:i.url)||t.url,data:void 0},e)),this.hls.trigger(y.ERROR,u)}handlePlaylistLoaded(t,i,s,e,n,r){const h=this.hls,{type:o,level:a,id:l,groupId:u,deliveryDirectives:c}=e,d=yo(i,e),f=mo(e),v="number"==typeof e.level&&f===S?a:void 0;if(!t.fragments.length){const r=t.playlistParsingError=new Error("No Segments found in Playlist");return void h.trigger(y.ERROR,{type:p.NETWORK_ERROR,details:m.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:r,reason:r.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const g=t.playlistParsingError;if(g){if(this.hls.logger.warn(g),!h.config.ignorePlaylistParsingErrors)return void h.trigger(y.ERROR,{type:p.NETWORK_ERROR,details:m.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:g,reason:g.message,response:i,context:e,level:v,parent:f,networkDetails:n,stats:s});t.playlistParsingError=null}switch(t.live&&r&&(r.getCacheAge&&(t.ageHeader=r.getCacheAge()||0),r.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case b:case w:h.trigger(y.LEVEL_LOADED,{details:t,levelInfo:e.levelOrTrack||h.levels[0],level:v||0,id:l||0,stats:s,networkDetails:n,deliveryDirectives:c,withoutMultiVariant:o===b});break;case $:h.trigger(y.AUDIO_TRACK_LOADED,{details:t,track:e.levelOrTrack,id:l||0,groupId:u||"",stats:s,networkDetails:n,deliveryDirectives:c});break;case k:h.trigger(y.SUBTITLE_TRACK_LOADED,{details:t,track:e.levelOrTrack,id:l||0,groupId:u||"",stats:s,networkDetails:n,deliveryDirectives:c})}}}class wo{static get version(){return ae}static isMSESupported(){return vo()}static isSupported(){return function(){if(!vo())return!1;const t=B();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(Nt(i,"video"))))||["mp4a.40.2","fLaC"].some((i=>t.isTypeSupported(Nt(i,"audio")))))}()}static getMediaSource(){return B()}static get Events(){return y}static get MetadataSchema(){return Pe}static get ErrorTypes(){return p}static get ErrorDetails(){return m}static get DefaultConfig(){return wo.defaultConfig?wo.defaultConfig:to}static set DefaultConfig(t){wo.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new oe,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const i=this.logger=function(t,i,s){const e=O();if("object"==typeof console&&!0===t||"object"==typeof t){const i=["debug","log","info","warn","error"];i.forEach((i=>{e[i]=N(i,t,s)}));try{e.log('Debug logs enabled for "Hls instance" in hls.js version 1.6.6')}catch(t){return O()}i.forEach((i=>{U[i]=N(i,t)}))}else x(U,e);return e}(t.debug||!1,0,t.assetPlayerId),s=this.config=function(t,i,s){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 e=io(t),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,h=void 0===i[r],o=[];n.forEach((s=>{const n=`${t}Loading${s}`,a=i[n];if(void 0!==a&&h){o.push(n);const t=e[r].default;switch(i[r]={default:t},s){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}}})),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${r}": ${ri(i[r])}`)})),D(D({},e),i)}(wo.DefaultConfig,t,i);this.userConfig=t,s.progressive&&function(t,i){const s=t.loader;s!==qh&&s!==Zh?(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=qh,t.progressive=!0,t.enableSoftwareAES=!0,i.log("[config]: Progressive streaming enabled, using FetchLoader"))}(s,i);const{abrController:e,bufferController:n,capLevelController:r,errorController:h,fpsController:o}=s,a=new h(this),l=this.abrController=new e(this),u=new xi(this),c=s.interstitialsController,d=c?this.interstitialsController=new c(this,wo):null,f=this.bufferController=new n(this,u),v=this.capLevelController=new r(this),g=new o(this),p=new bo(this),m=s.contentSteeringController,b=m?new m(this):null,w=this.levelController=new uo(this,b),$=new ao(this),k=new po(this.config),S=this.streamController=new go(this,u,k),T=this.gapController=new so(this,u);v.setStreamController(S),g.setStreamController(S);const E=[p,w,S];d&&E.splice(1,0,d),b&&E.splice(1,0,b),this.networkControllers=E;const A=[l,f,T,v,g,$,u];this.audioTrackController=this.createController(s.audioTrackController,E);const L=s.audioStreamController;L&&E.push(this.audioStreamController=new L(this,u,k)),this.subtitleTrackController=this.createController(s.subtitleTrackController,E);const M=s.subtitleStreamController;M&&E.push(this.subtititleStreamController=new M(this,u,k)),this.createController(s.timelineController,A),k.emeController=this.emeController=this.createController(s.emeController,A),this.cmcdController=this.createController(s.cmcdController,A),this.latencyController=this.createController(lo,A),this.coreComponents=A,E.push(a);const I=a.onErrorOut;"function"==typeof I&&this.on(y.ERROR,I,a),this.on(y.MANIFEST_LOADED,p.onManifestLoaded,p)}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){this.logger.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(y.ERROR,{type:p.OTHER_ERROR,details:m.INTERNAL_EXCEPTION,fatal:t===y.ERROR,event:t,error:i}),this.triggeringException=!1)}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(y.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){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(y.ERROR,{type:p.OTHER_ERROR,details:m.ATTACH_MEDIA_ERROR,fatal:!0,error:i})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const i="media"in t,s=i?t.media:t,e=i?t:{media:s};this._media=s,this.trigger(y.MEDIA_ATTACHING,e)}detachMedia(){this.logger.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(y.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const i=this.media,s=this._url,e=this._url=Q.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${e}`),i&&s&&(s!==e||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(y.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,i){this.logger.log(`startLoad(${t+(i?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,i),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((t=>{t.resumeBuffering&&t.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((t=>{t.pauseBuffering&&t.pauseBuffering()})))}get inFlightFragments(){const t={[S]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[T]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[E]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,i=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),i&&this.startLoad(i))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._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)}))}}}()),t}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.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){this.logger.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){this.logger.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 abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Zt.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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var i;return(null==(i=this.audioTrackController)?void 0:i.setAudioOption(t))||null}setSubtitleOption(t){var i;return(null==(i=this.subtitleTrackController)?void 0: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}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,i=this.allAudioTracks){return Yt(t,oi(i),navigator.mediaCapabilities)}}function $o(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")}`}wo.defaultConfig=void 0;var ko=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 So=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.isDragging=!1,this.seekPosition=0,this.isSeeking=!1,this.hideControlsTimeout=null,this.seekingTimeout=null,this.livestreamUpdateListener=t=>{this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=t},this.updateProgress=()=>{this.isSeeking||(this.currentTime=this.videoRef.currentTime)},this.updateHlsStatsPeriodically=()=>{var t,i,s;this.duration=(null===(t=this.videoRef)||void 0===t?void 0:t.seekable)&&this.videoRef.seekable.length>0?this.videoRef.seekable.end(this.videoRef.seekable.length-1):((null===(i=this.videoRef)||void 0===i?void 0:i.currentTime)||0)+((null===(s=this.hls)||void 0===s?void 0:s.latency)||0)},this.fastForwardToLatest=()=>{var t;this.videoRef.currentTime=(null===(t=this.videoRef)||void 0===t?void 0:t.seekable)&&this.videoRef.seekable.length>0?this.videoRef.seekable.end(this.videoRef.seekable.length-1)-1: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.seekToPosition=t=>{if(!this.videoRef)return;const i=Math.max(0,Math.min(t,this.duration));this.isSeeking=!0,this.currentTime=i;try{this.videoRef.currentTime=i,this.seekingTimeout&&clearTimeout(this.seekingTimeout),this.seekingTimeout=setTimeout((()=>{this.isSeeking=!1,this.currentTime=this.videoRef.currentTime}),200)}catch(t){this.isSeeking=!1,this.meeting.__internals__.logger.warn("rtk-livestream-player:: Seek failed",{error:t})}},this.onSeekbarMouseDown=t=>{t.preventDefault(),this.isDragging=!0,this.updateSeekPosition(t),document.addEventListener("mousemove",this.onSeekbarMouseMove),document.addEventListener("mouseup",this.onSeekbarMouseUp)},this.onSeekbarMouseMove=t=>{this.isDragging&&this.updateSeekPosition(t)},this.onSeekbarMouseUp=t=>{this.isDragging&&(this.isDragging=!1,this.updateSeekPosition(t),this.seekToPosition(this.seekPosition),document.removeEventListener("mousemove",this.onSeekbarMouseMove),document.removeEventListener("mouseup",this.onSeekbarMouseUp))},this.onSeekbarClick=t=>{this.isDragging||(this.updateSeekPosition(t),this.seekToPosition(this.seekPosition))},this.updateSeekPosition=t=>{const i=t.currentTarget.getBoundingClientRect(),s=Math.max(0,Math.min(1,(t.clientX-i.left)/i.width));this.seekPosition=s*this.duration},this.getSeekbarProgress=()=>this.isDragging?this.duration>0?this.seekPosition/this.duration:0:this.duration>0?this.currentTime/this.duration:0,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}`),wo.isSupported()?(this.meeting.__internals__.logger.info("rtk-livestream-player:: Initialising HLS. HLS is Supported"),this.hls=new wo({lowLatencyMode:!1}),window.rtk_hls=this.hls,this.meeting.__internals__.logger.info("rtk-livestream-player:: Loading source"),this.hls.loadSource(this.playbackUrl+"?dvrEnabled=true"),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(wo.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+"?dvrEnabled=true"))}),5e3)}else this.meeting.__internals__.logger.warn(`rtk-livestream-player:: non-fatal error: ${i.details}`,{error:i.error})})),this.hls.on(wo.Events.MEDIA_ATTACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media attached")})),this.hls.on(wo.Events.MEDIA_DETACHED,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: media detached")})),this.hls.on(wo.Events.DESTROYING,(()=>{this.meeting.__internals__.logger.info("rtk-livestream-player:: hls is getting destroyed")})),this.hls.on(wo.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.seekingTimeout&&clearTimeout(this.seekingTimeout),this.videoRef=null,this.hls&&this.hls.destroy(),window.rtk_hls=null}meetingChanged(t){t&&(this.playbackUrl=this.meeting.livestream.playbackUrl,this.livestreamState=this.meeting.livestream.state,this.meeting.livestream.on("livestreamUpdate",this.livestreamUpdateListener))}render(){if(!o(this.meeting))return;const{isError:t,errorMessage:e}=this.getErrorState(),{isLoading:n,loadingMessage:r,showIcon:h}=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"},i("video",{onMouseMove:this.onMouseMovePlayer,ref:async t=>{this.videoRef=t,await this.conditionallyStartLivestreamViewer()},id:"livestream-video",class:"livestream-video",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"},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"},$o(this.currentTime)," /"," ",$o(this.duration))),i("div",{class:"seekbar-container"},i("div",{class:"seekbar",onMouseDown:this.onSeekbarMouseDown,onClick:this.onSeekbarClick},i("div",{class:"seekbar-track"},i("div",{class:"seekbar-progress",style:{width:100*this.getSeekbarProgress()+"%"}}),i("div",{class:"seekbar-handle",style:{left:100*this.getSeekbarProgress()+"%"}})))),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"))),t&&i("div",{class:"loader"},i("rtk-icon",{icon:this.iconPack.warning}),i("p",null,e)),!t&&n&&i("div",{class:"loader"},h&&i("rtk-spinner",{id:"icon",part:"spinner",iconPack:this.iconPack,size:"md"}),i("p",null,r))))}get el(){return n(this)}static get watchers(){return{livestreamState:["updateLivestreamId"],meeting:["meetingChanged"]}}};ko([u()],So.prototype,"meeting",void 0),ko([u()],So.prototype,"t",void 0),ko([u()],So.prototype,"iconPack",void 0),So.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-left:var(--rtk-space-4, 16px);margin-right:var(--rtk-space-4, 16px);margin-top:var(--rtk-space-4, 16px);margin-bottom:var(--rtk-space-0, 0px);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;left:16px;right:16px;display:flex;height:auto;align-items:center;padding:12px 16px;z-index:30;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity));border-radius:6px;border-radius:var(--rtk-border-radius-md, 8px);background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / 0.8);gap:12px}.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;gap:12px;flex-shrink:0}#livestream-video,.livestream-video{position:absolute;top:0;left:0;width:100% !important;height:100% !important;max-width:none !important;max-height:none !important;min-width:100% !important;min-height:100% !important;-o-object-fit:fill !important;object-fit:fill !important;z-index:10;border-radius:var(--rtk-border-radius-md, 8px);border-width:0px}:host:not(:fullscreen) .video-container{padding:16px 16px 0 16px}:host(:fullscreen) .video-container,:host(:-webkit-full-screen) .video-container,:host(:-moz-full-screen) .video-container{padding:0}.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}.seekbar-container{flex:1;min-width:100px;padding:0 12px;display:flex;align-items:center}.seekbar{width:100%;height:20px;cursor:pointer;display:flex;align-items:center}.seekbar-track{position:relative;width:100%;height:4px;border-radius:9999px;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-600, 60 60 60) / var(--tw-bg-opacity))}.seekbar-progress{position:absolute;top:0;left:0;height:100%;border-radius:9999px;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));transition:width 0.1s ease}.seekbar-handle{position:absolute;top:50%;width:12px;height:12px;border-radius:9999px;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));transform:translate(-50%, -50%);transition:left 0.1s ease;opacity:0}.seekbar:hover .seekbar-handle{opacity:1}.seekbar:hover .seekbar-track{height:6px}.seekbar:hover .seekbar-handle{width:14px;height:14px}";var To=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 Eo=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"]}}};To([u()],Eo.prototype,"meeting",void 0),To([u()],Eo.prototype,"iconPack",void 0),To([u()],Eo.prototype,"t",void 0),Eo.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,So as rtk_livestream_player,Eo as rtk_viewer_count}
|